ctl.c revision 268673
1/*-
2 * Copyright (c) 2003-2009 Silicon Graphics International Corp.
3 * Copyright (c) 2012 The FreeBSD Foundation
4 * All rights reserved.
5 *
6 * Portions of this software were developed by Edward Tomasz Napierala
7 * under sponsorship from the FreeBSD Foundation.
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
12 * 1. Redistributions of source code must retain the above copyright
13 *    notice, this list of conditions, and the following disclaimer,
14 *    without modification.
15 * 2. Redistributions in binary form must reproduce at minimum a disclaimer
16 *    substantially similar to the "NO WARRANTY" disclaimer below
17 *    ("Disclaimer") and any redistribution must be conditioned upon
18 *    including a substantially similar Disclaimer requirement for further
19 *    binary redistribution.
20 *
21 * NO WARRANTY
22 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
25 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
26 * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
30 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
31 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32 * POSSIBILITY OF SUCH DAMAGES.
33 *
34 * $Id: //depot/users/kenm/FreeBSD-test2/sys/cam/ctl/ctl.c#8 $
35 */
36/*
37 * CAM Target Layer, a SCSI device emulation subsystem.
38 *
39 * Author: Ken Merry <ken@FreeBSD.org>
40 */
41
42#define _CTL_C
43
44#include <sys/cdefs.h>
45__FBSDID("$FreeBSD: stable/10/sys/cam/ctl/ctl.c 268673 2014-07-15 16:49:35Z mav $");
46
47#include <sys/param.h>
48#include <sys/systm.h>
49#include <sys/kernel.h>
50#include <sys/types.h>
51#include <sys/kthread.h>
52#include <sys/bio.h>
53#include <sys/fcntl.h>
54#include <sys/lock.h>
55#include <sys/module.h>
56#include <sys/mutex.h>
57#include <sys/condvar.h>
58#include <sys/malloc.h>
59#include <sys/conf.h>
60#include <sys/ioccom.h>
61#include <sys/queue.h>
62#include <sys/sbuf.h>
63#include <sys/smp.h>
64#include <sys/endian.h>
65#include <sys/sysctl.h>
66
67#include <cam/cam.h>
68#include <cam/scsi/scsi_all.h>
69#include <cam/scsi/scsi_da.h>
70#include <cam/ctl/ctl_io.h>
71#include <cam/ctl/ctl.h>
72#include <cam/ctl/ctl_frontend.h>
73#include <cam/ctl/ctl_frontend_internal.h>
74#include <cam/ctl/ctl_util.h>
75#include <cam/ctl/ctl_backend.h>
76#include <cam/ctl/ctl_ioctl.h>
77#include <cam/ctl/ctl_ha.h>
78#include <cam/ctl/ctl_private.h>
79#include <cam/ctl/ctl_debug.h>
80#include <cam/ctl/ctl_scsi_all.h>
81#include <cam/ctl/ctl_error.h>
82
83struct ctl_softc *control_softc = NULL;
84
85/*
86 * Size and alignment macros needed for Copan-specific HA hardware.  These
87 * can go away when the HA code is re-written, and uses busdma for any
88 * hardware.
89 */
90#define	CTL_ALIGN_8B(target, source, type)				\
91	if (((uint32_t)source & 0x7) != 0)				\
92		target = (type)(source + (0x8 - ((uint32_t)source & 0x7)));\
93	else								\
94		target = (type)source;
95
96#define	CTL_SIZE_8B(target, size)					\
97	if ((size & 0x7) != 0)						\
98		target = size + (0x8 - (size & 0x7));			\
99	else								\
100		target = size;
101
102#define CTL_ALIGN_8B_MARGIN	16
103
104/*
105 * Template mode pages.
106 */
107
108/*
109 * Note that these are default values only.  The actual values will be
110 * filled in when the user does a mode sense.
111 */
112static struct copan_power_subpage power_page_default = {
113	/*page_code*/ PWR_PAGE_CODE | SMPH_SPF,
114	/*subpage*/ PWR_SUBPAGE_CODE,
115	/*page_length*/ {(sizeof(struct copan_power_subpage) - 4) & 0xff00,
116			 (sizeof(struct copan_power_subpage) - 4) & 0x00ff},
117	/*page_version*/ PWR_VERSION,
118	/* total_luns */ 26,
119	/* max_active_luns*/ PWR_DFLT_MAX_LUNS,
120	/*reserved*/ {0, 0, 0, 0, 0, 0, 0, 0, 0,
121		      0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
122		      0, 0, 0, 0, 0, 0}
123};
124
125static struct copan_power_subpage power_page_changeable = {
126	/*page_code*/ PWR_PAGE_CODE | SMPH_SPF,
127	/*subpage*/ PWR_SUBPAGE_CODE,
128	/*page_length*/ {(sizeof(struct copan_power_subpage) - 4) & 0xff00,
129			 (sizeof(struct copan_power_subpage) - 4) & 0x00ff},
130	/*page_version*/ 0,
131	/* total_luns */ 0,
132	/* max_active_luns*/ 0,
133	/*reserved*/ {0, 0, 0, 0, 0, 0, 0, 0, 0,
134		      0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
135		      0, 0, 0, 0, 0, 0}
136};
137
138static struct copan_aps_subpage aps_page_default = {
139	APS_PAGE_CODE | SMPH_SPF, //page_code
140	APS_SUBPAGE_CODE, //subpage
141	{(sizeof(struct copan_aps_subpage) - 4) & 0xff00,
142	 (sizeof(struct copan_aps_subpage) - 4) & 0x00ff}, //page_length
143	APS_VERSION, //page_version
144	0, //lock_active
145	{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
146	0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
147	0, 0, 0, 0, 0} //reserved
148};
149
150static struct copan_aps_subpage aps_page_changeable = {
151	APS_PAGE_CODE | SMPH_SPF, //page_code
152	APS_SUBPAGE_CODE, //subpage
153	{(sizeof(struct copan_aps_subpage) - 4) & 0xff00,
154	 (sizeof(struct copan_aps_subpage) - 4) & 0x00ff}, //page_length
155	0, //page_version
156	0, //lock_active
157	{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
158	0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
159	0, 0, 0, 0, 0} //reserved
160};
161
162static struct copan_debugconf_subpage debugconf_page_default = {
163	DBGCNF_PAGE_CODE | SMPH_SPF,	/* page_code */
164	DBGCNF_SUBPAGE_CODE,		/* subpage */
165	{(sizeof(struct copan_debugconf_subpage) - 4) >> 8,
166	 (sizeof(struct copan_debugconf_subpage) - 4) >> 0}, /* page_length */
167	DBGCNF_VERSION,			/* page_version */
168	{CTL_TIME_IO_DEFAULT_SECS>>8,
169	 CTL_TIME_IO_DEFAULT_SECS>>0},	/* ctl_time_io_secs */
170};
171
172static struct copan_debugconf_subpage debugconf_page_changeable = {
173	DBGCNF_PAGE_CODE | SMPH_SPF,	/* page_code */
174	DBGCNF_SUBPAGE_CODE,		/* subpage */
175	{(sizeof(struct copan_debugconf_subpage) - 4) >> 8,
176	 (sizeof(struct copan_debugconf_subpage) - 4) >> 0}, /* page_length */
177	0,				/* page_version */
178	{0xff,0xff},			/* ctl_time_io_secs */
179};
180
181static struct scsi_format_page format_page_default = {
182	/*page_code*/SMS_FORMAT_DEVICE_PAGE,
183	/*page_length*/sizeof(struct scsi_format_page) - 2,
184	/*tracks_per_zone*/ {0, 0},
185	/*alt_sectors_per_zone*/ {0, 0},
186	/*alt_tracks_per_zone*/ {0, 0},
187	/*alt_tracks_per_lun*/ {0, 0},
188	/*sectors_per_track*/ {(CTL_DEFAULT_SECTORS_PER_TRACK >> 8) & 0xff,
189			        CTL_DEFAULT_SECTORS_PER_TRACK & 0xff},
190	/*bytes_per_sector*/ {0, 0},
191	/*interleave*/ {0, 0},
192	/*track_skew*/ {0, 0},
193	/*cylinder_skew*/ {0, 0},
194	/*flags*/ SFP_HSEC,
195	/*reserved*/ {0, 0, 0}
196};
197
198static struct scsi_format_page format_page_changeable = {
199	/*page_code*/SMS_FORMAT_DEVICE_PAGE,
200	/*page_length*/sizeof(struct scsi_format_page) - 2,
201	/*tracks_per_zone*/ {0, 0},
202	/*alt_sectors_per_zone*/ {0, 0},
203	/*alt_tracks_per_zone*/ {0, 0},
204	/*alt_tracks_per_lun*/ {0, 0},
205	/*sectors_per_track*/ {0, 0},
206	/*bytes_per_sector*/ {0, 0},
207	/*interleave*/ {0, 0},
208	/*track_skew*/ {0, 0},
209	/*cylinder_skew*/ {0, 0},
210	/*flags*/ 0,
211	/*reserved*/ {0, 0, 0}
212};
213
214static struct scsi_rigid_disk_page rigid_disk_page_default = {
215	/*page_code*/SMS_RIGID_DISK_PAGE,
216	/*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
217	/*cylinders*/ {0, 0, 0},
218	/*heads*/ CTL_DEFAULT_HEADS,
219	/*start_write_precomp*/ {0, 0, 0},
220	/*start_reduced_current*/ {0, 0, 0},
221	/*step_rate*/ {0, 0},
222	/*landing_zone_cylinder*/ {0, 0, 0},
223	/*rpl*/ SRDP_RPL_DISABLED,
224	/*rotational_offset*/ 0,
225	/*reserved1*/ 0,
226	/*rotation_rate*/ {(CTL_DEFAULT_ROTATION_RATE >> 8) & 0xff,
227			   CTL_DEFAULT_ROTATION_RATE & 0xff},
228	/*reserved2*/ {0, 0}
229};
230
231static struct scsi_rigid_disk_page rigid_disk_page_changeable = {
232	/*page_code*/SMS_RIGID_DISK_PAGE,
233	/*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
234	/*cylinders*/ {0, 0, 0},
235	/*heads*/ 0,
236	/*start_write_precomp*/ {0, 0, 0},
237	/*start_reduced_current*/ {0, 0, 0},
238	/*step_rate*/ {0, 0},
239	/*landing_zone_cylinder*/ {0, 0, 0},
240	/*rpl*/ 0,
241	/*rotational_offset*/ 0,
242	/*reserved1*/ 0,
243	/*rotation_rate*/ {0, 0},
244	/*reserved2*/ {0, 0}
245};
246
247static struct scsi_caching_page caching_page_default = {
248	/*page_code*/SMS_CACHING_PAGE,
249	/*page_length*/sizeof(struct scsi_caching_page) - 2,
250	/*flags1*/ SCP_DISC | SCP_WCE,
251	/*ret_priority*/ 0,
252	/*disable_pf_transfer_len*/ {0xff, 0xff},
253	/*min_prefetch*/ {0, 0},
254	/*max_prefetch*/ {0xff, 0xff},
255	/*max_pf_ceiling*/ {0xff, 0xff},
256	/*flags2*/ 0,
257	/*cache_segments*/ 0,
258	/*cache_seg_size*/ {0, 0},
259	/*reserved*/ 0,
260	/*non_cache_seg_size*/ {0, 0, 0}
261};
262
263static struct scsi_caching_page caching_page_changeable = {
264	/*page_code*/SMS_CACHING_PAGE,
265	/*page_length*/sizeof(struct scsi_caching_page) - 2,
266	/*flags1*/ 0,
267	/*ret_priority*/ 0,
268	/*disable_pf_transfer_len*/ {0, 0},
269	/*min_prefetch*/ {0, 0},
270	/*max_prefetch*/ {0, 0},
271	/*max_pf_ceiling*/ {0, 0},
272	/*flags2*/ 0,
273	/*cache_segments*/ 0,
274	/*cache_seg_size*/ {0, 0},
275	/*reserved*/ 0,
276	/*non_cache_seg_size*/ {0, 0, 0}
277};
278
279static struct scsi_control_page control_page_default = {
280	/*page_code*/SMS_CONTROL_MODE_PAGE,
281	/*page_length*/sizeof(struct scsi_control_page) - 2,
282	/*rlec*/0,
283	/*queue_flags*/0,
284	/*eca_and_aen*/0,
285	/*reserved*/0,
286	/*aen_holdoff_period*/{0, 0}
287};
288
289static struct scsi_control_page control_page_changeable = {
290	/*page_code*/SMS_CONTROL_MODE_PAGE,
291	/*page_length*/sizeof(struct scsi_control_page) - 2,
292	/*rlec*/SCP_DSENSE,
293	/*queue_flags*/0,
294	/*eca_and_aen*/0,
295	/*reserved*/0,
296	/*aen_holdoff_period*/{0, 0}
297};
298
299
300/*
301 * XXX KDM move these into the softc.
302 */
303static int rcv_sync_msg;
304static int persis_offset;
305static uint8_t ctl_pause_rtr;
306static int     ctl_is_single = 1;
307static int     index_to_aps_page;
308
309SYSCTL_NODE(_kern_cam, OID_AUTO, ctl, CTLFLAG_RD, 0, "CAM Target Layer");
310static int worker_threads = -1;
311TUNABLE_INT("kern.cam.ctl.worker_threads", &worker_threads);
312SYSCTL_INT(_kern_cam_ctl, OID_AUTO, worker_threads, CTLFLAG_RDTUN,
313    &worker_threads, 1, "Number of worker threads");
314static int verbose = 0;
315TUNABLE_INT("kern.cam.ctl.verbose", &verbose);
316SYSCTL_INT(_kern_cam_ctl, OID_AUTO, verbose, CTLFLAG_RWTUN,
317    &verbose, 0, "Show SCSI errors returned to initiator");
318
319/*
320 * Serial number (0x80), device id (0x83), supported pages (0x00),
321 * Block limits (0xB0) and Logical Block Provisioning (0xB2)
322 */
323#define SCSI_EVPD_NUM_SUPPORTED_PAGES	5
324
325static void ctl_isc_event_handler(ctl_ha_channel chanel, ctl_ha_event event,
326				  int param);
327static void ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest);
328static int ctl_init(void);
329void ctl_shutdown(void);
330static int ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td);
331static int ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td);
332static void ctl_ioctl_online(void *arg);
333static void ctl_ioctl_offline(void *arg);
334static int ctl_ioctl_targ_enable(void *arg, struct ctl_id targ_id);
335static int ctl_ioctl_targ_disable(void *arg, struct ctl_id targ_id);
336static int ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id);
337static int ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id);
338static int ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio);
339static int ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio);
340static int ctl_ioctl_submit_wait(union ctl_io *io);
341static void ctl_ioctl_datamove(union ctl_io *io);
342static void ctl_ioctl_done(union ctl_io *io);
343static void ctl_ioctl_hard_startstop_callback(void *arg,
344					      struct cfi_metatask *metatask);
345static void ctl_ioctl_bbrread_callback(void *arg,struct cfi_metatask *metatask);
346static int ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
347			      struct ctl_ooa *ooa_hdr,
348			      struct ctl_ooa_entry *kern_entries);
349static int ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
350		     struct thread *td);
351uint32_t ctl_get_resindex(struct ctl_nexus *nexus);
352uint32_t ctl_port_idx(int port_num);
353#ifdef unused
354static union ctl_io *ctl_malloc_io(ctl_io_type io_type, uint32_t targ_port,
355				   uint32_t targ_target, uint32_t targ_lun,
356				   int can_wait);
357static void ctl_kfree_io(union ctl_io *io);
358#endif /* unused */
359static int ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
360			 struct ctl_be_lun *be_lun, struct ctl_id target_id);
361static int ctl_free_lun(struct ctl_lun *lun);
362static void ctl_create_lun(struct ctl_be_lun *be_lun);
363/**
364static void ctl_failover_change_pages(struct ctl_softc *softc,
365				      struct ctl_scsiio *ctsio, int master);
366**/
367
368static int ctl_do_mode_select(union ctl_io *io);
369static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
370			   uint64_t res_key, uint64_t sa_res_key,
371			   uint8_t type, uint32_t residx,
372			   struct ctl_scsiio *ctsio,
373			   struct scsi_per_res_out *cdb,
374			   struct scsi_per_res_out_parms* param);
375static void ctl_pro_preempt_other(struct ctl_lun *lun,
376				  union ctl_ha_msg *msg);
377static void ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg);
378static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
379static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
380static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
381static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
382					 int alloc_len);
383static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
384static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
385static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
386static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint32_t *len);
387static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2);
388static ctl_action ctl_check_for_blockage(union ctl_io *pending_io,
389					 union ctl_io *ooa_io);
390static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
391				union ctl_io *starting_io);
392static int ctl_check_blocked(struct ctl_lun *lun);
393static int ctl_scsiio_lun_check(struct ctl_softc *ctl_softc,
394				struct ctl_lun *lun,
395				struct ctl_cmd_entry *entry,
396				struct ctl_scsiio *ctsio);
397//static int ctl_check_rtr(union ctl_io *pending_io, struct ctl_softc *softc);
398static void ctl_failover(void);
399static int ctl_scsiio_precheck(struct ctl_softc *ctl_softc,
400			       struct ctl_scsiio *ctsio);
401static int ctl_scsiio(struct ctl_scsiio *ctsio);
402
403static int ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
404static int ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
405			    ctl_ua_type ua_type);
406static int ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io,
407			 ctl_ua_type ua_type);
408static int ctl_abort_task(union ctl_io *io);
409static void ctl_run_task(union ctl_io *io);
410#ifdef CTL_IO_DELAY
411static void ctl_datamove_timer_wakeup(void *arg);
412static void ctl_done_timer_wakeup(void *arg);
413#endif /* CTL_IO_DELAY */
414
415static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
416static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
417static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
418static void ctl_datamove_remote_write(union ctl_io *io);
419static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
420static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
421static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
422static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
423				    ctl_ha_dt_cb callback);
424static void ctl_datamove_remote_read(union ctl_io *io);
425static void ctl_datamove_remote(union ctl_io *io);
426static int ctl_process_done(union ctl_io *io);
427static void ctl_lun_thread(void *arg);
428static void ctl_work_thread(void *arg);
429static void ctl_enqueue_incoming(union ctl_io *io);
430static void ctl_enqueue_rtr(union ctl_io *io);
431static void ctl_enqueue_done(union ctl_io *io);
432static void ctl_enqueue_isc(union ctl_io *io);
433
434/*
435 * Load the serialization table.  This isn't very pretty, but is probably
436 * the easiest way to do it.
437 */
438#include "ctl_ser_table.c"
439
440/*
441 * We only need to define open, close and ioctl routines for this driver.
442 */
443static struct cdevsw ctl_cdevsw = {
444	.d_version =	D_VERSION,
445	.d_flags =	0,
446	.d_open =	ctl_open,
447	.d_close =	ctl_close,
448	.d_ioctl =	ctl_ioctl,
449	.d_name =	"ctl",
450};
451
452
453MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
454MALLOC_DEFINE(M_CTLIO, "ctlio", "Memory used for CTL requests");
455
456static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
457
458static moduledata_t ctl_moduledata = {
459	"ctl",
460	ctl_module_event_handler,
461	NULL
462};
463
464DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
465MODULE_VERSION(ctl, 1);
466
467static void
468ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
469			    union ctl_ha_msg *msg_info)
470{
471	struct ctl_scsiio *ctsio;
472
473	if (msg_info->hdr.original_sc == NULL) {
474		printf("%s: original_sc == NULL!\n", __func__);
475		/* XXX KDM now what? */
476		return;
477	}
478
479	ctsio = &msg_info->hdr.original_sc->scsiio;
480	ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
481	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
482	ctsio->io_hdr.status = msg_info->hdr.status;
483	ctsio->scsi_status = msg_info->scsi.scsi_status;
484	ctsio->sense_len = msg_info->scsi.sense_len;
485	ctsio->sense_residual = msg_info->scsi.sense_residual;
486	ctsio->residual = msg_info->scsi.residual;
487	memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
488	       sizeof(ctsio->sense_data));
489	memcpy(&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
490	       &msg_info->scsi.lbalen, sizeof(msg_info->scsi.lbalen));
491	ctl_enqueue_isc((union ctl_io *)ctsio);
492}
493
494static void
495ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
496				union ctl_ha_msg *msg_info)
497{
498	struct ctl_scsiio *ctsio;
499
500	if (msg_info->hdr.serializing_sc == NULL) {
501		printf("%s: serializing_sc == NULL!\n", __func__);
502		/* XXX KDM now what? */
503		return;
504	}
505
506	ctsio = &msg_info->hdr.serializing_sc->scsiio;
507#if 0
508	/*
509	 * Attempt to catch the situation where an I/O has
510	 * been freed, and we're using it again.
511	 */
512	if (ctsio->io_hdr.io_type == 0xff) {
513		union ctl_io *tmp_io;
514		tmp_io = (union ctl_io *)ctsio;
515		printf("%s: %p use after free!\n", __func__,
516		       ctsio);
517		printf("%s: type %d msg %d cdb %x iptl: "
518		       "%d:%d:%d:%d tag 0x%04x "
519		       "flag %#x status %x\n",
520			__func__,
521			tmp_io->io_hdr.io_type,
522			tmp_io->io_hdr.msg_type,
523			tmp_io->scsiio.cdb[0],
524			tmp_io->io_hdr.nexus.initid.id,
525			tmp_io->io_hdr.nexus.targ_port,
526			tmp_io->io_hdr.nexus.targ_target.id,
527			tmp_io->io_hdr.nexus.targ_lun,
528			(tmp_io->io_hdr.io_type ==
529			CTL_IO_TASK) ?
530			tmp_io->taskio.tag_num :
531			tmp_io->scsiio.tag_num,
532		        tmp_io->io_hdr.flags,
533			tmp_io->io_hdr.status);
534	}
535#endif
536	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
537	ctl_enqueue_isc((union ctl_io *)ctsio);
538}
539
540/*
541 * ISC (Inter Shelf Communication) event handler.  Events from the HA
542 * subsystem come in here.
543 */
544static void
545ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
546{
547	struct ctl_softc *ctl_softc;
548	union ctl_io *io;
549	struct ctl_prio *presio;
550	ctl_ha_status isc_status;
551
552	ctl_softc = control_softc;
553	io = NULL;
554
555
556#if 0
557	printf("CTL: Isc Msg event %d\n", event);
558#endif
559	if (event == CTL_HA_EVT_MSG_RECV) {
560		union ctl_ha_msg msg_info;
561
562		isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
563					     sizeof(msg_info), /*wait*/ 0);
564#if 0
565		printf("CTL: msg_type %d\n", msg_info.msg_type);
566#endif
567		if (isc_status != 0) {
568			printf("Error receiving message, status = %d\n",
569			       isc_status);
570			return;
571		}
572
573		switch (msg_info.hdr.msg_type) {
574		case CTL_MSG_SERIALIZE:
575#if 0
576			printf("Serialize\n");
577#endif
578			io = ctl_alloc_io((void *)ctl_softc->othersc_pool);
579			if (io == NULL) {
580				printf("ctl_isc_event_handler: can't allocate "
581				       "ctl_io!\n");
582				/* Bad Juju */
583				/* Need to set busy and send msg back */
584				msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
585				msg_info.hdr.status = CTL_SCSI_ERROR;
586				msg_info.scsi.scsi_status = SCSI_STATUS_BUSY;
587				msg_info.scsi.sense_len = 0;
588			        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
589				    sizeof(msg_info), 0) > CTL_HA_STATUS_SUCCESS){
590				}
591				goto bailout;
592			}
593			ctl_zero_io(io);
594			// populate ctsio from msg_info
595			io->io_hdr.io_type = CTL_IO_SCSI;
596			io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
597			io->io_hdr.original_sc = msg_info.hdr.original_sc;
598#if 0
599			printf("pOrig %x\n", (int)msg_info.original_sc);
600#endif
601			io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
602					    CTL_FLAG_IO_ACTIVE;
603			/*
604			 * If we're in serialization-only mode, we don't
605			 * want to go through full done processing.  Thus
606			 * the COPY flag.
607			 *
608			 * XXX KDM add another flag that is more specific.
609			 */
610			if (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)
611				io->io_hdr.flags |= CTL_FLAG_INT_COPY;
612			io->io_hdr.nexus = msg_info.hdr.nexus;
613#if 0
614			printf("targ %d, port %d, iid %d, lun %d\n",
615			       io->io_hdr.nexus.targ_target.id,
616			       io->io_hdr.nexus.targ_port,
617			       io->io_hdr.nexus.initid.id,
618			       io->io_hdr.nexus.targ_lun);
619#endif
620			io->scsiio.tag_num = msg_info.scsi.tag_num;
621			io->scsiio.tag_type = msg_info.scsi.tag_type;
622			memcpy(io->scsiio.cdb, msg_info.scsi.cdb,
623			       CTL_MAX_CDBLEN);
624			if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
625				struct ctl_cmd_entry *entry;
626				uint8_t opcode;
627
628				opcode = io->scsiio.cdb[0];
629				entry = &ctl_cmd_table[opcode];
630				io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
631				io->io_hdr.flags |=
632					entry->flags & CTL_FLAG_DATA_MASK;
633			}
634			ctl_enqueue_isc(io);
635			break;
636
637		/* Performed on the Originating SC, XFER mode only */
638		case CTL_MSG_DATAMOVE: {
639			struct ctl_sg_entry *sgl;
640			int i, j;
641
642			io = msg_info.hdr.original_sc;
643			if (io == NULL) {
644				printf("%s: original_sc == NULL!\n", __func__);
645				/* XXX KDM do something here */
646				break;
647			}
648			io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
649			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
650			/*
651			 * Keep track of this, we need to send it back over
652			 * when the datamove is complete.
653			 */
654			io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
655
656			if (msg_info.dt.sg_sequence == 0) {
657				/*
658				 * XXX KDM we use the preallocated S/G list
659				 * here, but we'll need to change this to
660				 * dynamic allocation if we need larger S/G
661				 * lists.
662				 */
663				if (msg_info.dt.kern_sg_entries >
664				    sizeof(io->io_hdr.remote_sglist) /
665				    sizeof(io->io_hdr.remote_sglist[0])) {
666					printf("%s: number of S/G entries "
667					    "needed %u > allocated num %zd\n",
668					    __func__,
669					    msg_info.dt.kern_sg_entries,
670					    sizeof(io->io_hdr.remote_sglist)/
671					    sizeof(io->io_hdr.remote_sglist[0]));
672
673					/*
674					 * XXX KDM send a message back to
675					 * the other side to shut down the
676					 * DMA.  The error will come back
677					 * through via the normal channel.
678					 */
679					break;
680				}
681				sgl = io->io_hdr.remote_sglist;
682				memset(sgl, 0,
683				       sizeof(io->io_hdr.remote_sglist));
684
685				io->scsiio.kern_data_ptr = (uint8_t *)sgl;
686
687				io->scsiio.kern_sg_entries =
688					msg_info.dt.kern_sg_entries;
689				io->scsiio.rem_sg_entries =
690					msg_info.dt.kern_sg_entries;
691				io->scsiio.kern_data_len =
692					msg_info.dt.kern_data_len;
693				io->scsiio.kern_total_len =
694					msg_info.dt.kern_total_len;
695				io->scsiio.kern_data_resid =
696					msg_info.dt.kern_data_resid;
697				io->scsiio.kern_rel_offset =
698					msg_info.dt.kern_rel_offset;
699				/*
700				 * Clear out per-DMA flags.
701				 */
702				io->io_hdr.flags &= ~CTL_FLAG_RDMA_MASK;
703				/*
704				 * Add per-DMA flags that are set for this
705				 * particular DMA request.
706				 */
707				io->io_hdr.flags |= msg_info.dt.flags &
708						    CTL_FLAG_RDMA_MASK;
709			} else
710				sgl = (struct ctl_sg_entry *)
711					io->scsiio.kern_data_ptr;
712
713			for (i = msg_info.dt.sent_sg_entries, j = 0;
714			     i < (msg_info.dt.sent_sg_entries +
715			     msg_info.dt.cur_sg_entries); i++, j++) {
716				sgl[i].addr = msg_info.dt.sg_list[j].addr;
717				sgl[i].len = msg_info.dt.sg_list[j].len;
718
719#if 0
720				printf("%s: L: %p,%d -> %p,%d j=%d, i=%d\n",
721				       __func__,
722				       msg_info.dt.sg_list[j].addr,
723				       msg_info.dt.sg_list[j].len,
724				       sgl[i].addr, sgl[i].len, j, i);
725#endif
726			}
727#if 0
728			memcpy(&sgl[msg_info.dt.sent_sg_entries],
729			       msg_info.dt.sg_list,
730			       sizeof(*sgl) * msg_info.dt.cur_sg_entries);
731#endif
732
733			/*
734			 * If this is the last piece of the I/O, we've got
735			 * the full S/G list.  Queue processing in the thread.
736			 * Otherwise wait for the next piece.
737			 */
738			if (msg_info.dt.sg_last != 0)
739				ctl_enqueue_isc(io);
740			break;
741		}
742		/* Performed on the Serializing (primary) SC, XFER mode only */
743		case CTL_MSG_DATAMOVE_DONE: {
744			if (msg_info.hdr.serializing_sc == NULL) {
745				printf("%s: serializing_sc == NULL!\n",
746				       __func__);
747				/* XXX KDM now what? */
748				break;
749			}
750			/*
751			 * We grab the sense information here in case
752			 * there was a failure, so we can return status
753			 * back to the initiator.
754			 */
755			io = msg_info.hdr.serializing_sc;
756			io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
757			io->io_hdr.status = msg_info.hdr.status;
758			io->scsiio.scsi_status = msg_info.scsi.scsi_status;
759			io->scsiio.sense_len = msg_info.scsi.sense_len;
760			io->scsiio.sense_residual =msg_info.scsi.sense_residual;
761			io->io_hdr.port_status = msg_info.scsi.fetd_status;
762			io->scsiio.residual = msg_info.scsi.residual;
763			memcpy(&io->scsiio.sense_data,&msg_info.scsi.sense_data,
764			       sizeof(io->scsiio.sense_data));
765			ctl_enqueue_isc(io);
766			break;
767		}
768
769		/* Preformed on Originating SC, SER_ONLY mode */
770		case CTL_MSG_R2R:
771			io = msg_info.hdr.original_sc;
772			if (io == NULL) {
773				printf("%s: Major Bummer\n", __func__);
774				return;
775			} else {
776#if 0
777				printf("pOrig %x\n",(int) ctsio);
778#endif
779			}
780			io->io_hdr.msg_type = CTL_MSG_R2R;
781			io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
782			ctl_enqueue_isc(io);
783			break;
784
785		/*
786		 * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
787		 * mode.
788		 * Performed on the Originating (i.e. secondary) SC in XFER
789		 * mode
790		 */
791		case CTL_MSG_FINISH_IO:
792			if (ctl_softc->ha_mode == CTL_HA_MODE_XFER)
793				ctl_isc_handler_finish_xfer(ctl_softc,
794							    &msg_info);
795			else
796				ctl_isc_handler_finish_ser_only(ctl_softc,
797								&msg_info);
798			break;
799
800		/* Preformed on Originating SC */
801		case CTL_MSG_BAD_JUJU:
802			io = msg_info.hdr.original_sc;
803			if (io == NULL) {
804				printf("%s: Bad JUJU!, original_sc is NULL!\n",
805				       __func__);
806				break;
807			}
808			ctl_copy_sense_data(&msg_info, io);
809			/*
810			 * IO should have already been cleaned up on other
811			 * SC so clear this flag so we won't send a message
812			 * back to finish the IO there.
813			 */
814			io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
815			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
816
817			/* io = msg_info.hdr.serializing_sc; */
818			io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
819			ctl_enqueue_isc(io);
820			break;
821
822		/* Handle resets sent from the other side */
823		case CTL_MSG_MANAGE_TASKS: {
824			struct ctl_taskio *taskio;
825			taskio = (struct ctl_taskio *)ctl_alloc_io(
826				(void *)ctl_softc->othersc_pool);
827			if (taskio == NULL) {
828				printf("ctl_isc_event_handler: can't allocate "
829				       "ctl_io!\n");
830				/* Bad Juju */
831				/* should I just call the proper reset func
832				   here??? */
833				goto bailout;
834			}
835			ctl_zero_io((union ctl_io *)taskio);
836			taskio->io_hdr.io_type = CTL_IO_TASK;
837			taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
838			taskio->io_hdr.nexus = msg_info.hdr.nexus;
839			taskio->task_action = msg_info.task.task_action;
840			taskio->tag_num = msg_info.task.tag_num;
841			taskio->tag_type = msg_info.task.tag_type;
842#ifdef CTL_TIME_IO
843			taskio->io_hdr.start_time = time_uptime;
844			getbintime(&taskio->io_hdr.start_bt);
845#if 0
846			cs_prof_gettime(&taskio->io_hdr.start_ticks);
847#endif
848#endif /* CTL_TIME_IO */
849			ctl_run_task((union ctl_io *)taskio);
850			break;
851		}
852		/* Persistent Reserve action which needs attention */
853		case CTL_MSG_PERS_ACTION:
854			presio = (struct ctl_prio *)ctl_alloc_io(
855				(void *)ctl_softc->othersc_pool);
856			if (presio == NULL) {
857				printf("ctl_isc_event_handler: can't allocate "
858				       "ctl_io!\n");
859				/* Bad Juju */
860				/* Need to set busy and send msg back */
861				goto bailout;
862			}
863			ctl_zero_io((union ctl_io *)presio);
864			presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
865			presio->pr_msg = msg_info.pr;
866			ctl_enqueue_isc((union ctl_io *)presio);
867			break;
868		case CTL_MSG_SYNC_FE:
869			rcv_sync_msg = 1;
870			break;
871		case CTL_MSG_APS_LOCK: {
872			// It's quicker to execute this then to
873			// queue it.
874			struct ctl_lun *lun;
875			struct ctl_page_index *page_index;
876			struct copan_aps_subpage *current_sp;
877			uint32_t targ_lun;
878
879			targ_lun = msg_info.hdr.nexus.targ_mapped_lun;
880			lun = ctl_softc->ctl_luns[targ_lun];
881			mtx_lock(&lun->lun_lock);
882			page_index = &lun->mode_pages.index[index_to_aps_page];
883			current_sp = (struct copan_aps_subpage *)
884				     (page_index->page_data +
885				     (page_index->page_len * CTL_PAGE_CURRENT));
886
887			current_sp->lock_active = msg_info.aps.lock_flag;
888			mtx_unlock(&lun->lun_lock);
889		        break;
890		}
891		default:
892		        printf("How did I get here?\n");
893		}
894	} else if (event == CTL_HA_EVT_MSG_SENT) {
895		if (param != CTL_HA_STATUS_SUCCESS) {
896			printf("Bad status from ctl_ha_msg_send status %d\n",
897			       param);
898		}
899		return;
900	} else if (event == CTL_HA_EVT_DISCONNECT) {
901		printf("CTL: Got a disconnect from Isc\n");
902		return;
903	} else {
904		printf("ctl_isc_event_handler: Unknown event %d\n", event);
905		return;
906	}
907
908bailout:
909	return;
910}
911
912static void
913ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
914{
915	struct scsi_sense_data *sense;
916
917	sense = &dest->scsiio.sense_data;
918	bcopy(&src->scsi.sense_data, sense, sizeof(*sense));
919	dest->scsiio.scsi_status = src->scsi.scsi_status;
920	dest->scsiio.sense_len = src->scsi.sense_len;
921	dest->io_hdr.status = src->hdr.status;
922}
923
924static int
925ctl_init(void)
926{
927	struct ctl_softc *softc;
928	struct ctl_io_pool *internal_pool, *emergency_pool, *other_pool;
929	struct ctl_frontend *fe;
930        uint8_t sc_id =0;
931	int i, error, retval;
932	//int isc_retval;
933
934	retval = 0;
935	ctl_pause_rtr = 0;
936        rcv_sync_msg = 0;
937
938	control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
939			       M_WAITOK | M_ZERO);
940	softc = control_softc;
941
942	softc->dev = make_dev(&ctl_cdevsw, 0, UID_ROOT, GID_OPERATOR, 0600,
943			      "cam/ctl");
944
945	softc->dev->si_drv1 = softc;
946
947	/*
948	 * By default, return a "bad LUN" peripheral qualifier for unknown
949	 * LUNs.  The user can override this default using the tunable or
950	 * sysctl.  See the comment in ctl_inquiry_std() for more details.
951	 */
952	softc->inquiry_pq_no_lun = 1;
953	TUNABLE_INT_FETCH("kern.cam.ctl.inquiry_pq_no_lun",
954			  &softc->inquiry_pq_no_lun);
955	sysctl_ctx_init(&softc->sysctl_ctx);
956	softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
957		SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
958		CTLFLAG_RD, 0, "CAM Target Layer");
959
960	if (softc->sysctl_tree == NULL) {
961		printf("%s: unable to allocate sysctl tree\n", __func__);
962		destroy_dev(softc->dev);
963		free(control_softc, M_DEVBUF);
964		control_softc = NULL;
965		return (ENOMEM);
966	}
967
968	SYSCTL_ADD_INT(&softc->sysctl_ctx,
969		       SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
970		       "inquiry_pq_no_lun", CTLFLAG_RW,
971		       &softc->inquiry_pq_no_lun, 0,
972		       "Report no lun possible for invalid LUNs");
973
974	mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
975	mtx_init(&softc->pool_lock, "CTL pool mutex", NULL, MTX_DEF);
976	softc->open_count = 0;
977
978	/*
979	 * Default to actually sending a SYNCHRONIZE CACHE command down to
980	 * the drive.
981	 */
982	softc->flags = CTL_FLAG_REAL_SYNC;
983
984	/*
985	 * In Copan's HA scheme, the "master" and "slave" roles are
986	 * figured out through the slot the controller is in.  Although it
987	 * is an active/active system, someone has to be in charge.
988 	 */
989#ifdef NEEDTOPORT
990        scmicro_rw(SCMICRO_GET_SHELF_ID, &sc_id);
991#endif
992
993        if (sc_id == 0) {
994		softc->flags |= CTL_FLAG_MASTER_SHELF;
995		persis_offset = 0;
996	} else
997		persis_offset = CTL_MAX_INITIATORS;
998
999	/*
1000	 * XXX KDM need to figure out where we want to get our target ID
1001	 * and WWID.  Is it different on each port?
1002	 */
1003	softc->target.id = 0;
1004	softc->target.wwid[0] = 0x12345678;
1005	softc->target.wwid[1] = 0x87654321;
1006	STAILQ_INIT(&softc->lun_list);
1007	STAILQ_INIT(&softc->pending_lun_queue);
1008	STAILQ_INIT(&softc->fe_list);
1009	STAILQ_INIT(&softc->be_list);
1010	STAILQ_INIT(&softc->io_pools);
1011
1012	if (ctl_pool_create(softc, CTL_POOL_INTERNAL, CTL_POOL_ENTRIES_INTERNAL,
1013			    &internal_pool)!= 0){
1014		printf("ctl: can't allocate %d entry internal pool, "
1015		       "exiting\n", CTL_POOL_ENTRIES_INTERNAL);
1016		return (ENOMEM);
1017	}
1018
1019	if (ctl_pool_create(softc, CTL_POOL_EMERGENCY,
1020			    CTL_POOL_ENTRIES_EMERGENCY, &emergency_pool) != 0) {
1021		printf("ctl: can't allocate %d entry emergency pool, "
1022		       "exiting\n", CTL_POOL_ENTRIES_EMERGENCY);
1023		ctl_pool_free(internal_pool);
1024		return (ENOMEM);
1025	}
1026
1027	if (ctl_pool_create(softc, CTL_POOL_4OTHERSC, CTL_POOL_ENTRIES_OTHER_SC,
1028	                    &other_pool) != 0)
1029	{
1030		printf("ctl: can't allocate %d entry other SC pool, "
1031		       "exiting\n", CTL_POOL_ENTRIES_OTHER_SC);
1032		ctl_pool_free(internal_pool);
1033		ctl_pool_free(emergency_pool);
1034		return (ENOMEM);
1035	}
1036
1037	softc->internal_pool = internal_pool;
1038	softc->emergency_pool = emergency_pool;
1039	softc->othersc_pool = other_pool;
1040
1041	if (worker_threads <= 0)
1042		worker_threads = max(1, mp_ncpus / 4);
1043	if (worker_threads > CTL_MAX_THREADS)
1044		worker_threads = CTL_MAX_THREADS;
1045
1046	for (i = 0; i < worker_threads; i++) {
1047		struct ctl_thread *thr = &softc->threads[i];
1048
1049		mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1050		thr->ctl_softc = softc;
1051		STAILQ_INIT(&thr->incoming_queue);
1052		STAILQ_INIT(&thr->rtr_queue);
1053		STAILQ_INIT(&thr->done_queue);
1054		STAILQ_INIT(&thr->isc_queue);
1055
1056		error = kproc_kthread_add(ctl_work_thread, thr,
1057		    &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1058		if (error != 0) {
1059			printf("error creating CTL work thread!\n");
1060			ctl_pool_free(internal_pool);
1061			ctl_pool_free(emergency_pool);
1062			ctl_pool_free(other_pool);
1063			return (error);
1064		}
1065	}
1066	error = kproc_kthread_add(ctl_lun_thread, softc,
1067	    &softc->ctl_proc, NULL, 0, 0, "ctl", "lun");
1068	if (error != 0) {
1069		printf("error creating CTL lun thread!\n");
1070		ctl_pool_free(internal_pool);
1071		ctl_pool_free(emergency_pool);
1072		ctl_pool_free(other_pool);
1073		return (error);
1074	}
1075	if (bootverbose)
1076		printf("ctl: CAM Target Layer loaded\n");
1077
1078	/*
1079	 * Initialize the initiator and portname mappings
1080	 */
1081	memset(softc->wwpn_iid, 0, sizeof(softc->wwpn_iid));
1082
1083	/*
1084	 * Initialize the ioctl front end.
1085	 */
1086	fe = &softc->ioctl_info.fe;
1087	sprintf(softc->ioctl_info.port_name, "CTL ioctl");
1088	fe->port_type = CTL_PORT_IOCTL;
1089	fe->num_requested_ctl_io = 100;
1090	fe->port_name = softc->ioctl_info.port_name;
1091	fe->port_online = ctl_ioctl_online;
1092	fe->port_offline = ctl_ioctl_offline;
1093	fe->onoff_arg = &softc->ioctl_info;
1094	fe->targ_enable = ctl_ioctl_targ_enable;
1095	fe->targ_disable = ctl_ioctl_targ_disable;
1096	fe->lun_enable = ctl_ioctl_lun_enable;
1097	fe->lun_disable = ctl_ioctl_lun_disable;
1098	fe->targ_lun_arg = &softc->ioctl_info;
1099	fe->fe_datamove = ctl_ioctl_datamove;
1100	fe->fe_done = ctl_ioctl_done;
1101	fe->max_targets = 15;
1102	fe->max_target_id = 15;
1103
1104	if (ctl_frontend_register(&softc->ioctl_info.fe,
1105	                  (softc->flags & CTL_FLAG_MASTER_SHELF)) != 0) {
1106		printf("ctl: ioctl front end registration failed, will "
1107		       "continue anyway\n");
1108	}
1109
1110#ifdef CTL_IO_DELAY
1111	if (sizeof(struct callout) > CTL_TIMER_BYTES) {
1112		printf("sizeof(struct callout) %zd > CTL_TIMER_BYTES %zd\n",
1113		       sizeof(struct callout), CTL_TIMER_BYTES);
1114		return (EINVAL);
1115	}
1116#endif /* CTL_IO_DELAY */
1117
1118	return (0);
1119}
1120
1121void
1122ctl_shutdown(void)
1123{
1124	struct ctl_softc *softc;
1125	struct ctl_lun *lun, *next_lun;
1126	struct ctl_io_pool *pool;
1127
1128	softc = (struct ctl_softc *)control_softc;
1129
1130	if (ctl_frontend_deregister(&softc->ioctl_info.fe) != 0)
1131		printf("ctl: ioctl front end deregistration failed\n");
1132
1133	mtx_lock(&softc->ctl_lock);
1134
1135	/*
1136	 * Free up each LUN.
1137	 */
1138	for (lun = STAILQ_FIRST(&softc->lun_list); lun != NULL; lun = next_lun){
1139		next_lun = STAILQ_NEXT(lun, links);
1140		ctl_free_lun(lun);
1141	}
1142
1143	mtx_unlock(&softc->ctl_lock);
1144
1145	/*
1146	 * This will rip the rug out from under any FETDs or anyone else
1147	 * that has a pool allocated.  Since we increment our module
1148	 * refcount any time someone outside the main CTL module allocates
1149	 * a pool, we shouldn't have any problems here.  The user won't be
1150	 * able to unload the CTL module until client modules have
1151	 * successfully unloaded.
1152	 */
1153	while ((pool = STAILQ_FIRST(&softc->io_pools)) != NULL)
1154		ctl_pool_free(pool);
1155
1156#if 0
1157	ctl_shutdown_thread(softc->work_thread);
1158	mtx_destroy(&softc->queue_lock);
1159#endif
1160
1161	mtx_destroy(&softc->pool_lock);
1162	mtx_destroy(&softc->ctl_lock);
1163
1164	destroy_dev(softc->dev);
1165
1166	sysctl_ctx_free(&softc->sysctl_ctx);
1167
1168	free(control_softc, M_DEVBUF);
1169	control_softc = NULL;
1170
1171	if (bootverbose)
1172		printf("ctl: CAM Target Layer unloaded\n");
1173}
1174
1175static int
1176ctl_module_event_handler(module_t mod, int what, void *arg)
1177{
1178
1179	switch (what) {
1180	case MOD_LOAD:
1181		return (ctl_init());
1182	case MOD_UNLOAD:
1183		return (EBUSY);
1184	default:
1185		return (EOPNOTSUPP);
1186	}
1187}
1188
1189/*
1190 * XXX KDM should we do some access checks here?  Bump a reference count to
1191 * prevent a CTL module from being unloaded while someone has it open?
1192 */
1193static int
1194ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
1195{
1196	return (0);
1197}
1198
1199static int
1200ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
1201{
1202	return (0);
1203}
1204
1205int
1206ctl_port_enable(ctl_port_type port_type)
1207{
1208	struct ctl_softc *softc;
1209	struct ctl_frontend *fe;
1210
1211	if (ctl_is_single == 0) {
1212		union ctl_ha_msg msg_info;
1213		int isc_retval;
1214
1215#if 0
1216		printf("%s: HA mode, synchronizing frontend enable\n",
1217		        __func__);
1218#endif
1219		msg_info.hdr.msg_type = CTL_MSG_SYNC_FE;
1220	        if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1221		        sizeof(msg_info), 1 )) > CTL_HA_STATUS_SUCCESS) {
1222			printf("Sync msg send error retval %d\n", isc_retval);
1223		}
1224		if (!rcv_sync_msg) {
1225			isc_retval=ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
1226			        sizeof(msg_info), 1);
1227		}
1228#if 0
1229        	printf("CTL:Frontend Enable\n");
1230	} else {
1231		printf("%s: single mode, skipping frontend synchronization\n",
1232		        __func__);
1233#endif
1234	}
1235
1236	softc = control_softc;
1237
1238	STAILQ_FOREACH(fe, &softc->fe_list, links) {
1239		if (port_type & fe->port_type)
1240		{
1241#if 0
1242			printf("port %d\n", fe->targ_port);
1243#endif
1244			ctl_frontend_online(fe);
1245		}
1246	}
1247
1248	return (0);
1249}
1250
1251int
1252ctl_port_disable(ctl_port_type port_type)
1253{
1254	struct ctl_softc *softc;
1255	struct ctl_frontend *fe;
1256
1257	softc = control_softc;
1258
1259	STAILQ_FOREACH(fe, &softc->fe_list, links) {
1260		if (port_type & fe->port_type)
1261			ctl_frontend_offline(fe);
1262	}
1263
1264	return (0);
1265}
1266
1267/*
1268 * Returns 0 for success, 1 for failure.
1269 * Currently the only failure mode is if there aren't enough entries
1270 * allocated.  So, in case of a failure, look at num_entries_dropped,
1271 * reallocate and try again.
1272 */
1273int
1274ctl_port_list(struct ctl_port_entry *entries, int num_entries_alloced,
1275	      int *num_entries_filled, int *num_entries_dropped,
1276	      ctl_port_type port_type, int no_virtual)
1277{
1278	struct ctl_softc *softc;
1279	struct ctl_frontend *fe;
1280	int entries_dropped, entries_filled;
1281	int retval;
1282	int i;
1283
1284	softc = control_softc;
1285
1286	retval = 0;
1287	entries_filled = 0;
1288	entries_dropped = 0;
1289
1290	i = 0;
1291	mtx_lock(&softc->ctl_lock);
1292	STAILQ_FOREACH(fe, &softc->fe_list, links) {
1293		struct ctl_port_entry *entry;
1294
1295		if ((fe->port_type & port_type) == 0)
1296			continue;
1297
1298		if ((no_virtual != 0)
1299		 && (fe->virtual_port != 0))
1300			continue;
1301
1302		if (entries_filled >= num_entries_alloced) {
1303			entries_dropped++;
1304			continue;
1305		}
1306		entry = &entries[i];
1307
1308		entry->port_type = fe->port_type;
1309		strlcpy(entry->port_name, fe->port_name,
1310			sizeof(entry->port_name));
1311		entry->physical_port = fe->physical_port;
1312		entry->virtual_port = fe->virtual_port;
1313		entry->wwnn = fe->wwnn;
1314		entry->wwpn = fe->wwpn;
1315
1316		i++;
1317		entries_filled++;
1318	}
1319
1320	mtx_unlock(&softc->ctl_lock);
1321
1322	if (entries_dropped > 0)
1323		retval = 1;
1324
1325	*num_entries_dropped = entries_dropped;
1326	*num_entries_filled = entries_filled;
1327
1328	return (retval);
1329}
1330
1331static void
1332ctl_ioctl_online(void *arg)
1333{
1334	struct ctl_ioctl_info *ioctl_info;
1335
1336	ioctl_info = (struct ctl_ioctl_info *)arg;
1337
1338	ioctl_info->flags |= CTL_IOCTL_FLAG_ENABLED;
1339}
1340
1341static void
1342ctl_ioctl_offline(void *arg)
1343{
1344	struct ctl_ioctl_info *ioctl_info;
1345
1346	ioctl_info = (struct ctl_ioctl_info *)arg;
1347
1348	ioctl_info->flags &= ~CTL_IOCTL_FLAG_ENABLED;
1349}
1350
1351/*
1352 * Remove an initiator by port number and initiator ID.
1353 * Returns 0 for success, 1 for failure.
1354 */
1355int
1356ctl_remove_initiator(int32_t targ_port, uint32_t iid)
1357{
1358	struct ctl_softc *softc;
1359
1360	softc = control_softc;
1361
1362	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1363
1364	if ((targ_port < 0)
1365	 || (targ_port > CTL_MAX_PORTS)) {
1366		printf("%s: invalid port number %d\n", __func__, targ_port);
1367		return (1);
1368	}
1369	if (iid > CTL_MAX_INIT_PER_PORT) {
1370		printf("%s: initiator ID %u > maximun %u!\n",
1371		       __func__, iid, CTL_MAX_INIT_PER_PORT);
1372		return (1);
1373	}
1374
1375	mtx_lock(&softc->ctl_lock);
1376
1377	softc->wwpn_iid[targ_port][iid].in_use = 0;
1378
1379	mtx_unlock(&softc->ctl_lock);
1380
1381	return (0);
1382}
1383
1384/*
1385 * Add an initiator to the initiator map.
1386 * Returns 0 for success, 1 for failure.
1387 */
1388int
1389ctl_add_initiator(uint64_t wwpn, int32_t targ_port, uint32_t iid)
1390{
1391	struct ctl_softc *softc;
1392	int retval;
1393
1394	softc = control_softc;
1395
1396	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1397
1398	retval = 0;
1399
1400	if ((targ_port < 0)
1401	 || (targ_port > CTL_MAX_PORTS)) {
1402		printf("%s: invalid port number %d\n", __func__, targ_port);
1403		return (1);
1404	}
1405	if (iid > CTL_MAX_INIT_PER_PORT) {
1406		printf("%s: WWPN %#jx initiator ID %u > maximun %u!\n",
1407		       __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
1408		return (1);
1409	}
1410
1411	mtx_lock(&softc->ctl_lock);
1412
1413	if (softc->wwpn_iid[targ_port][iid].in_use != 0) {
1414		/*
1415		 * We don't treat this as an error.
1416		 */
1417		if (softc->wwpn_iid[targ_port][iid].wwpn == wwpn) {
1418			printf("%s: port %d iid %u WWPN %#jx arrived again?\n",
1419			       __func__, targ_port, iid, (uintmax_t)wwpn);
1420			goto bailout;
1421		}
1422
1423		/*
1424		 * This is an error, but what do we do about it?  The
1425		 * driver is telling us we have a new WWPN for this
1426		 * initiator ID, so we pretty much need to use it.
1427		 */
1428		printf("%s: port %d iid %u WWPN %#jx arrived, WWPN %#jx is "
1429		       "still at that address\n", __func__, targ_port, iid,
1430		       (uintmax_t)wwpn,
1431		       (uintmax_t)softc->wwpn_iid[targ_port][iid].wwpn);
1432
1433		/*
1434		 * XXX KDM clear have_ca and ua_pending on each LUN for
1435		 * this initiator.
1436		 */
1437	}
1438	softc->wwpn_iid[targ_port][iid].in_use = 1;
1439	softc->wwpn_iid[targ_port][iid].iid = iid;
1440	softc->wwpn_iid[targ_port][iid].wwpn = wwpn;
1441	softc->wwpn_iid[targ_port][iid].port = targ_port;
1442
1443bailout:
1444
1445	mtx_unlock(&softc->ctl_lock);
1446
1447	return (retval);
1448}
1449
1450/*
1451 * XXX KDM should we pretend to do something in the target/lun
1452 * enable/disable functions?
1453 */
1454static int
1455ctl_ioctl_targ_enable(void *arg, struct ctl_id targ_id)
1456{
1457	return (0);
1458}
1459
1460static int
1461ctl_ioctl_targ_disable(void *arg, struct ctl_id targ_id)
1462{
1463	return (0);
1464}
1465
1466static int
1467ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id)
1468{
1469	return (0);
1470}
1471
1472static int
1473ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id)
1474{
1475	return (0);
1476}
1477
1478/*
1479 * Data movement routine for the CTL ioctl frontend port.
1480 */
1481static int
1482ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio)
1483{
1484	struct ctl_sg_entry *ext_sglist, *kern_sglist;
1485	struct ctl_sg_entry ext_entry, kern_entry;
1486	int ext_sglen, ext_sg_entries, kern_sg_entries;
1487	int ext_sg_start, ext_offset;
1488	int len_to_copy, len_copied;
1489	int kern_watermark, ext_watermark;
1490	int ext_sglist_malloced;
1491	int i, j;
1492
1493	ext_sglist_malloced = 0;
1494	ext_sg_start = 0;
1495	ext_offset = 0;
1496
1497	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove\n"));
1498
1499	/*
1500	 * If this flag is set, fake the data transfer.
1501	 */
1502	if (ctsio->io_hdr.flags & CTL_FLAG_NO_DATAMOVE) {
1503		ctsio->ext_data_filled = ctsio->ext_data_len;
1504		goto bailout;
1505	}
1506
1507	/*
1508	 * To simplify things here, if we have a single buffer, stick it in
1509	 * a S/G entry and just make it a single entry S/G list.
1510	 */
1511	if (ctsio->io_hdr.flags & CTL_FLAG_EDPTR_SGLIST) {
1512		int len_seen;
1513
1514		ext_sglen = ctsio->ext_sg_entries * sizeof(*ext_sglist);
1515
1516		ext_sglist = (struct ctl_sg_entry *)malloc(ext_sglen, M_CTL,
1517							   M_WAITOK);
1518		ext_sglist_malloced = 1;
1519		if (copyin(ctsio->ext_data_ptr, ext_sglist,
1520				   ext_sglen) != 0) {
1521			ctl_set_internal_failure(ctsio,
1522						 /*sks_valid*/ 0,
1523						 /*retry_count*/ 0);
1524			goto bailout;
1525		}
1526		ext_sg_entries = ctsio->ext_sg_entries;
1527		len_seen = 0;
1528		for (i = 0; i < ext_sg_entries; i++) {
1529			if ((len_seen + ext_sglist[i].len) >=
1530			     ctsio->ext_data_filled) {
1531				ext_sg_start = i;
1532				ext_offset = ctsio->ext_data_filled - len_seen;
1533				break;
1534			}
1535			len_seen += ext_sglist[i].len;
1536		}
1537	} else {
1538		ext_sglist = &ext_entry;
1539		ext_sglist->addr = ctsio->ext_data_ptr;
1540		ext_sglist->len = ctsio->ext_data_len;
1541		ext_sg_entries = 1;
1542		ext_sg_start = 0;
1543		ext_offset = ctsio->ext_data_filled;
1544	}
1545
1546	if (ctsio->kern_sg_entries > 0) {
1547		kern_sglist = (struct ctl_sg_entry *)ctsio->kern_data_ptr;
1548		kern_sg_entries = ctsio->kern_sg_entries;
1549	} else {
1550		kern_sglist = &kern_entry;
1551		kern_sglist->addr = ctsio->kern_data_ptr;
1552		kern_sglist->len = ctsio->kern_data_len;
1553		kern_sg_entries = 1;
1554	}
1555
1556
1557	kern_watermark = 0;
1558	ext_watermark = ext_offset;
1559	len_copied = 0;
1560	for (i = ext_sg_start, j = 0;
1561	     i < ext_sg_entries && j < kern_sg_entries;) {
1562		uint8_t *ext_ptr, *kern_ptr;
1563
1564		len_to_copy = ctl_min(ext_sglist[i].len - ext_watermark,
1565				      kern_sglist[j].len - kern_watermark);
1566
1567		ext_ptr = (uint8_t *)ext_sglist[i].addr;
1568		ext_ptr = ext_ptr + ext_watermark;
1569		if (ctsio->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
1570			/*
1571			 * XXX KDM fix this!
1572			 */
1573			panic("need to implement bus address support");
1574#if 0
1575			kern_ptr = bus_to_virt(kern_sglist[j].addr);
1576#endif
1577		} else
1578			kern_ptr = (uint8_t *)kern_sglist[j].addr;
1579		kern_ptr = kern_ptr + kern_watermark;
1580
1581		kern_watermark += len_to_copy;
1582		ext_watermark += len_to_copy;
1583
1584		if ((ctsio->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
1585		     CTL_FLAG_DATA_IN) {
1586			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1587					 "bytes to user\n", len_to_copy));
1588			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1589					 "to %p\n", kern_ptr, ext_ptr));
1590			if (copyout(kern_ptr, ext_ptr, len_to_copy) != 0) {
1591				ctl_set_internal_failure(ctsio,
1592							 /*sks_valid*/ 0,
1593							 /*retry_count*/ 0);
1594				goto bailout;
1595			}
1596		} else {
1597			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1598					 "bytes from user\n", len_to_copy));
1599			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1600					 "to %p\n", ext_ptr, kern_ptr));
1601			if (copyin(ext_ptr, kern_ptr, len_to_copy)!= 0){
1602				ctl_set_internal_failure(ctsio,
1603							 /*sks_valid*/ 0,
1604							 /*retry_count*/0);
1605				goto bailout;
1606			}
1607		}
1608
1609		len_copied += len_to_copy;
1610
1611		if (ext_sglist[i].len == ext_watermark) {
1612			i++;
1613			ext_watermark = 0;
1614		}
1615
1616		if (kern_sglist[j].len == kern_watermark) {
1617			j++;
1618			kern_watermark = 0;
1619		}
1620	}
1621
1622	ctsio->ext_data_filled += len_copied;
1623
1624	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_sg_entries: %d, "
1625			 "kern_sg_entries: %d\n", ext_sg_entries,
1626			 kern_sg_entries));
1627	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_data_len = %d, "
1628			 "kern_data_len = %d\n", ctsio->ext_data_len,
1629			 ctsio->kern_data_len));
1630
1631
1632	/* XXX KDM set residual?? */
1633bailout:
1634
1635	if (ext_sglist_malloced != 0)
1636		free(ext_sglist, M_CTL);
1637
1638	return (CTL_RETVAL_COMPLETE);
1639}
1640
1641/*
1642 * Serialize a command that went down the "wrong" side, and so was sent to
1643 * this controller for execution.  The logic is a little different than the
1644 * standard case in ctl_scsiio_precheck().  Errors in this case need to get
1645 * sent back to the other side, but in the success case, we execute the
1646 * command on this side (XFER mode) or tell the other side to execute it
1647 * (SER_ONLY mode).
1648 */
1649static int
1650ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
1651{
1652	struct ctl_softc *ctl_softc;
1653	union ctl_ha_msg msg_info;
1654	struct ctl_lun *lun;
1655	int retval = 0;
1656	uint32_t targ_lun;
1657
1658	ctl_softc = control_softc;
1659
1660	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
1661	lun = ctl_softc->ctl_luns[targ_lun];
1662	if (lun==NULL)
1663	{
1664		/*
1665		 * Why isn't LUN defined? The other side wouldn't
1666		 * send a cmd if the LUN is undefined.
1667		 */
1668		printf("%s: Bad JUJU!, LUN is NULL!\n", __func__);
1669
1670		/* "Logical unit not supported" */
1671		ctl_set_sense_data(&msg_info.scsi.sense_data,
1672				   lun,
1673				   /*sense_format*/SSD_TYPE_NONE,
1674				   /*current_error*/ 1,
1675				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1676				   /*asc*/ 0x25,
1677				   /*ascq*/ 0x00,
1678				   SSD_ELEM_NONE);
1679
1680		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1681		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1682		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1683		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1684		msg_info.hdr.serializing_sc = NULL;
1685		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1686	        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1687				sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1688		}
1689		return(1);
1690
1691	}
1692
1693	mtx_lock(&lun->lun_lock);
1694    	TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1695
1696	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
1697		(union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
1698		 ooa_links))) {
1699	case CTL_ACTION_BLOCK:
1700		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
1701		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
1702				  blocked_links);
1703		break;
1704	case CTL_ACTION_PASS:
1705	case CTL_ACTION_SKIP:
1706		if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
1707			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
1708			ctl_enqueue_rtr((union ctl_io *)ctsio);
1709		} else {
1710
1711			/* send msg back to other side */
1712			msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1713			msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
1714			msg_info.hdr.msg_type = CTL_MSG_R2R;
1715#if 0
1716			printf("2. pOrig %x\n", (int)msg_info.hdr.original_sc);
1717#endif
1718		        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1719			    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1720			}
1721		}
1722		break;
1723	case CTL_ACTION_OVERLAP:
1724		/* OVERLAPPED COMMANDS ATTEMPTED */
1725		ctl_set_sense_data(&msg_info.scsi.sense_data,
1726				   lun,
1727				   /*sense_format*/SSD_TYPE_NONE,
1728				   /*current_error*/ 1,
1729				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1730				   /*asc*/ 0x4E,
1731				   /*ascq*/ 0x00,
1732				   SSD_ELEM_NONE);
1733
1734		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1735		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1736		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1737		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1738		msg_info.hdr.serializing_sc = NULL;
1739		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1740#if 0
1741		printf("BAD JUJU:Major Bummer Overlap\n");
1742#endif
1743		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1744		retval = 1;
1745		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1746		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1747		}
1748		break;
1749	case CTL_ACTION_OVERLAP_TAG:
1750		/* TAGGED OVERLAPPED COMMANDS (NN = QUEUE TAG) */
1751		ctl_set_sense_data(&msg_info.scsi.sense_data,
1752				   lun,
1753				   /*sense_format*/SSD_TYPE_NONE,
1754				   /*current_error*/ 1,
1755				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1756				   /*asc*/ 0x4D,
1757				   /*ascq*/ ctsio->tag_num & 0xff,
1758				   SSD_ELEM_NONE);
1759
1760		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1761		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1762		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1763		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1764		msg_info.hdr.serializing_sc = NULL;
1765		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1766#if 0
1767		printf("BAD JUJU:Major Bummer Overlap Tag\n");
1768#endif
1769		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1770		retval = 1;
1771		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1772		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1773		}
1774		break;
1775	case CTL_ACTION_ERROR:
1776	default:
1777		/* "Internal target failure" */
1778		ctl_set_sense_data(&msg_info.scsi.sense_data,
1779				   lun,
1780				   /*sense_format*/SSD_TYPE_NONE,
1781				   /*current_error*/ 1,
1782				   /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
1783				   /*asc*/ 0x44,
1784				   /*ascq*/ 0x00,
1785				   SSD_ELEM_NONE);
1786
1787		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1788		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1789		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1790		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1791		msg_info.hdr.serializing_sc = NULL;
1792		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1793#if 0
1794		printf("BAD JUJU:Major Bummer HW Error\n");
1795#endif
1796		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1797		retval = 1;
1798		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1799		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1800		}
1801		break;
1802	}
1803	mtx_unlock(&lun->lun_lock);
1804	return (retval);
1805}
1806
1807static int
1808ctl_ioctl_submit_wait(union ctl_io *io)
1809{
1810	struct ctl_fe_ioctl_params params;
1811	ctl_fe_ioctl_state last_state;
1812	int done, retval;
1813
1814	retval = 0;
1815
1816	bzero(&params, sizeof(params));
1817
1818	mtx_init(&params.ioctl_mtx, "ctliocmtx", NULL, MTX_DEF);
1819	cv_init(&params.sem, "ctlioccv");
1820	params.state = CTL_IOCTL_INPROG;
1821	last_state = params.state;
1822
1823	io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr = &params;
1824
1825	CTL_DEBUG_PRINT(("ctl_ioctl_submit_wait\n"));
1826
1827	/* This shouldn't happen */
1828	if ((retval = ctl_queue(io)) != CTL_RETVAL_COMPLETE)
1829		return (retval);
1830
1831	done = 0;
1832
1833	do {
1834		mtx_lock(&params.ioctl_mtx);
1835		/*
1836		 * Check the state here, and don't sleep if the state has
1837		 * already changed (i.e. wakeup has already occured, but we
1838		 * weren't waiting yet).
1839		 */
1840		if (params.state == last_state) {
1841			/* XXX KDM cv_wait_sig instead? */
1842			cv_wait(&params.sem, &params.ioctl_mtx);
1843		}
1844		last_state = params.state;
1845
1846		switch (params.state) {
1847		case CTL_IOCTL_INPROG:
1848			/* Why did we wake up? */
1849			/* XXX KDM error here? */
1850			mtx_unlock(&params.ioctl_mtx);
1851			break;
1852		case CTL_IOCTL_DATAMOVE:
1853			CTL_DEBUG_PRINT(("got CTL_IOCTL_DATAMOVE\n"));
1854
1855			/*
1856			 * change last_state back to INPROG to avoid
1857			 * deadlock on subsequent data moves.
1858			 */
1859			params.state = last_state = CTL_IOCTL_INPROG;
1860
1861			mtx_unlock(&params.ioctl_mtx);
1862			ctl_ioctl_do_datamove(&io->scsiio);
1863			/*
1864			 * Note that in some cases, most notably writes,
1865			 * this will queue the I/O and call us back later.
1866			 * In other cases, generally reads, this routine
1867			 * will immediately call back and wake us up,
1868			 * probably using our own context.
1869			 */
1870			io->scsiio.be_move_done(io);
1871			break;
1872		case CTL_IOCTL_DONE:
1873			mtx_unlock(&params.ioctl_mtx);
1874			CTL_DEBUG_PRINT(("got CTL_IOCTL_DONE\n"));
1875			done = 1;
1876			break;
1877		default:
1878			mtx_unlock(&params.ioctl_mtx);
1879			/* XXX KDM error here? */
1880			break;
1881		}
1882	} while (done == 0);
1883
1884	mtx_destroy(&params.ioctl_mtx);
1885	cv_destroy(&params.sem);
1886
1887	return (CTL_RETVAL_COMPLETE);
1888}
1889
1890static void
1891ctl_ioctl_datamove(union ctl_io *io)
1892{
1893	struct ctl_fe_ioctl_params *params;
1894
1895	params = (struct ctl_fe_ioctl_params *)
1896		io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
1897
1898	mtx_lock(&params->ioctl_mtx);
1899	params->state = CTL_IOCTL_DATAMOVE;
1900	cv_broadcast(&params->sem);
1901	mtx_unlock(&params->ioctl_mtx);
1902}
1903
1904static void
1905ctl_ioctl_done(union ctl_io *io)
1906{
1907	struct ctl_fe_ioctl_params *params;
1908
1909	params = (struct ctl_fe_ioctl_params *)
1910		io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
1911
1912	mtx_lock(&params->ioctl_mtx);
1913	params->state = CTL_IOCTL_DONE;
1914	cv_broadcast(&params->sem);
1915	mtx_unlock(&params->ioctl_mtx);
1916}
1917
1918static void
1919ctl_ioctl_hard_startstop_callback(void *arg, struct cfi_metatask *metatask)
1920{
1921	struct ctl_fe_ioctl_startstop_info *sd_info;
1922
1923	sd_info = (struct ctl_fe_ioctl_startstop_info *)arg;
1924
1925	sd_info->hs_info.status = metatask->status;
1926	sd_info->hs_info.total_luns = metatask->taskinfo.startstop.total_luns;
1927	sd_info->hs_info.luns_complete =
1928		metatask->taskinfo.startstop.luns_complete;
1929	sd_info->hs_info.luns_failed = metatask->taskinfo.startstop.luns_failed;
1930
1931	cv_broadcast(&sd_info->sem);
1932}
1933
1934static void
1935ctl_ioctl_bbrread_callback(void *arg, struct cfi_metatask *metatask)
1936{
1937	struct ctl_fe_ioctl_bbrread_info *fe_bbr_info;
1938
1939	fe_bbr_info = (struct ctl_fe_ioctl_bbrread_info *)arg;
1940
1941	mtx_lock(fe_bbr_info->lock);
1942	fe_bbr_info->bbr_info->status = metatask->status;
1943	fe_bbr_info->bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
1944	fe_bbr_info->wakeup_done = 1;
1945	mtx_unlock(fe_bbr_info->lock);
1946
1947	cv_broadcast(&fe_bbr_info->sem);
1948}
1949
1950/*
1951 * Returns 0 for success, errno for failure.
1952 */
1953static int
1954ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
1955		   struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
1956{
1957	union ctl_io *io;
1958	int retval;
1959
1960	retval = 0;
1961
1962	mtx_lock(&lun->lun_lock);
1963	for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
1964	     (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
1965	     ooa_links)) {
1966		struct ctl_ooa_entry *entry;
1967
1968		/*
1969		 * If we've got more than we can fit, just count the
1970		 * remaining entries.
1971		 */
1972		if (*cur_fill_num >= ooa_hdr->alloc_num)
1973			continue;
1974
1975		entry = &kern_entries[*cur_fill_num];
1976
1977		entry->tag_num = io->scsiio.tag_num;
1978		entry->lun_num = lun->lun;
1979#ifdef CTL_TIME_IO
1980		entry->start_bt = io->io_hdr.start_bt;
1981#endif
1982		bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
1983		entry->cdb_len = io->scsiio.cdb_len;
1984		if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
1985			entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
1986
1987		if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
1988			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
1989
1990		if (io->io_hdr.flags & CTL_FLAG_ABORT)
1991			entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
1992
1993		if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
1994			entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
1995
1996		if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
1997			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
1998	}
1999	mtx_unlock(&lun->lun_lock);
2000
2001	return (retval);
2002}
2003
2004static void *
2005ctl_copyin_alloc(void *user_addr, int len, char *error_str,
2006		 size_t error_str_len)
2007{
2008	void *kptr;
2009
2010	kptr = malloc(len, M_CTL, M_WAITOK | M_ZERO);
2011
2012	if (copyin(user_addr, kptr, len) != 0) {
2013		snprintf(error_str, error_str_len, "Error copying %d bytes "
2014			 "from user address %p to kernel address %p", len,
2015			 user_addr, kptr);
2016		free(kptr, M_CTL);
2017		return (NULL);
2018	}
2019
2020	return (kptr);
2021}
2022
2023static void
2024ctl_free_args(int num_be_args, struct ctl_be_arg *be_args)
2025{
2026	int i;
2027
2028	if (be_args == NULL)
2029		return;
2030
2031	for (i = 0; i < num_be_args; i++) {
2032		free(be_args[i].kname, M_CTL);
2033		free(be_args[i].kvalue, M_CTL);
2034	}
2035
2036	free(be_args, M_CTL);
2037}
2038
2039static struct ctl_be_arg *
2040ctl_copyin_args(int num_be_args, struct ctl_be_arg *be_args,
2041		char *error_str, size_t error_str_len)
2042{
2043	struct ctl_be_arg *args;
2044	int i;
2045
2046	args = ctl_copyin_alloc(be_args, num_be_args * sizeof(*be_args),
2047				error_str, error_str_len);
2048
2049	if (args == NULL)
2050		goto bailout;
2051
2052	for (i = 0; i < num_be_args; i++) {
2053		args[i].kname = NULL;
2054		args[i].kvalue = NULL;
2055	}
2056
2057	for (i = 0; i < num_be_args; i++) {
2058		uint8_t *tmpptr;
2059
2060		args[i].kname = ctl_copyin_alloc(args[i].name,
2061			args[i].namelen, error_str, error_str_len);
2062		if (args[i].kname == NULL)
2063			goto bailout;
2064
2065		if (args[i].kname[args[i].namelen - 1] != '\0') {
2066			snprintf(error_str, error_str_len, "Argument %d "
2067				 "name is not NUL-terminated", i);
2068			goto bailout;
2069		}
2070
2071		args[i].kvalue = NULL;
2072
2073		tmpptr = ctl_copyin_alloc(args[i].value,
2074			args[i].vallen, error_str, error_str_len);
2075		if (tmpptr == NULL)
2076			goto bailout;
2077
2078		args[i].kvalue = tmpptr;
2079
2080		if ((args[i].flags & CTL_BEARG_ASCII)
2081		 && (tmpptr[args[i].vallen - 1] != '\0')) {
2082			snprintf(error_str, error_str_len, "Argument %d "
2083				 "value is not NUL-terminated", i);
2084			goto bailout;
2085		}
2086	}
2087
2088	return (args);
2089bailout:
2090
2091	ctl_free_args(num_be_args, args);
2092
2093	return (NULL);
2094}
2095
2096/*
2097 * Escape characters that are illegal or not recommended in XML.
2098 */
2099int
2100ctl_sbuf_printf_esc(struct sbuf *sb, char *str)
2101{
2102	int retval;
2103
2104	retval = 0;
2105
2106	for (; *str; str++) {
2107		switch (*str) {
2108		case '&':
2109			retval = sbuf_printf(sb, "&amp;");
2110			break;
2111		case '>':
2112			retval = sbuf_printf(sb, "&gt;");
2113			break;
2114		case '<':
2115			retval = sbuf_printf(sb, "&lt;");
2116			break;
2117		default:
2118			retval = sbuf_putc(sb, *str);
2119			break;
2120		}
2121
2122		if (retval != 0)
2123			break;
2124
2125	}
2126
2127	return (retval);
2128}
2129
2130static int
2131ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2132	  struct thread *td)
2133{
2134	struct ctl_softc *softc;
2135	int retval;
2136
2137	softc = control_softc;
2138
2139	retval = 0;
2140
2141	switch (cmd) {
2142	case CTL_IO: {
2143		union ctl_io *io;
2144		void *pool_tmp;
2145
2146		/*
2147		 * If we haven't been "enabled", don't allow any SCSI I/O
2148		 * to this FETD.
2149		 */
2150		if ((softc->ioctl_info.flags & CTL_IOCTL_FLAG_ENABLED) == 0) {
2151			retval = EPERM;
2152			break;
2153		}
2154
2155		io = ctl_alloc_io(softc->ioctl_info.fe.ctl_pool_ref);
2156		if (io == NULL) {
2157			printf("ctl_ioctl: can't allocate ctl_io!\n");
2158			retval = ENOSPC;
2159			break;
2160		}
2161
2162		/*
2163		 * Need to save the pool reference so it doesn't get
2164		 * spammed by the user's ctl_io.
2165		 */
2166		pool_tmp = io->io_hdr.pool;
2167
2168		memcpy(io, (void *)addr, sizeof(*io));
2169
2170		io->io_hdr.pool = pool_tmp;
2171		/*
2172		 * No status yet, so make sure the status is set properly.
2173		 */
2174		io->io_hdr.status = CTL_STATUS_NONE;
2175
2176		/*
2177		 * The user sets the initiator ID, target and LUN IDs.
2178		 */
2179		io->io_hdr.nexus.targ_port = softc->ioctl_info.fe.targ_port;
2180		io->io_hdr.flags |= CTL_FLAG_USER_REQ;
2181		if ((io->io_hdr.io_type == CTL_IO_SCSI)
2182		 && (io->scsiio.tag_type != CTL_TAG_UNTAGGED))
2183			io->scsiio.tag_num = softc->ioctl_info.cur_tag_num++;
2184
2185		retval = ctl_ioctl_submit_wait(io);
2186
2187		if (retval != 0) {
2188			ctl_free_io(io);
2189			break;
2190		}
2191
2192		memcpy((void *)addr, io, sizeof(*io));
2193
2194		/* return this to our pool */
2195		ctl_free_io(io);
2196
2197		break;
2198	}
2199	case CTL_ENABLE_PORT:
2200	case CTL_DISABLE_PORT:
2201	case CTL_SET_PORT_WWNS: {
2202		struct ctl_frontend *fe;
2203		struct ctl_port_entry *entry;
2204
2205		entry = (struct ctl_port_entry *)addr;
2206
2207		mtx_lock(&softc->ctl_lock);
2208		STAILQ_FOREACH(fe, &softc->fe_list, links) {
2209			int action, done;
2210
2211			action = 0;
2212			done = 0;
2213
2214			if ((entry->port_type == CTL_PORT_NONE)
2215			 && (entry->targ_port == fe->targ_port)) {
2216				/*
2217				 * If the user only wants to enable or
2218				 * disable or set WWNs on a specific port,
2219				 * do the operation and we're done.
2220				 */
2221				action = 1;
2222				done = 1;
2223			} else if (entry->port_type & fe->port_type) {
2224				/*
2225				 * Compare the user's type mask with the
2226				 * particular frontend type to see if we
2227				 * have a match.
2228				 */
2229				action = 1;
2230				done = 0;
2231
2232				/*
2233				 * Make sure the user isn't trying to set
2234				 * WWNs on multiple ports at the same time.
2235				 */
2236				if (cmd == CTL_SET_PORT_WWNS) {
2237					printf("%s: Can't set WWNs on "
2238					       "multiple ports\n", __func__);
2239					retval = EINVAL;
2240					break;
2241				}
2242			}
2243			if (action != 0) {
2244				/*
2245				 * XXX KDM we have to drop the lock here,
2246				 * because the online/offline operations
2247				 * can potentially block.  We need to
2248				 * reference count the frontends so they
2249				 * can't go away,
2250				 */
2251				mtx_unlock(&softc->ctl_lock);
2252
2253				if (cmd == CTL_ENABLE_PORT) {
2254					struct ctl_lun *lun;
2255
2256					STAILQ_FOREACH(lun, &softc->lun_list,
2257						       links) {
2258						fe->lun_enable(fe->targ_lun_arg,
2259						    lun->target,
2260						    lun->lun);
2261					}
2262
2263					ctl_frontend_online(fe);
2264				} else if (cmd == CTL_DISABLE_PORT) {
2265					struct ctl_lun *lun;
2266
2267					ctl_frontend_offline(fe);
2268
2269					STAILQ_FOREACH(lun, &softc->lun_list,
2270						       links) {
2271						fe->lun_disable(
2272						    fe->targ_lun_arg,
2273						    lun->target,
2274						    lun->lun);
2275					}
2276				}
2277
2278				mtx_lock(&softc->ctl_lock);
2279
2280				if (cmd == CTL_SET_PORT_WWNS)
2281					ctl_frontend_set_wwns(fe,
2282					    (entry->flags & CTL_PORT_WWNN_VALID) ?
2283					    1 : 0, entry->wwnn,
2284					    (entry->flags & CTL_PORT_WWPN_VALID) ?
2285					    1 : 0, entry->wwpn);
2286			}
2287			if (done != 0)
2288				break;
2289		}
2290		mtx_unlock(&softc->ctl_lock);
2291		break;
2292	}
2293	case CTL_GET_PORT_LIST: {
2294		struct ctl_frontend *fe;
2295		struct ctl_port_list *list;
2296		int i;
2297
2298		list = (struct ctl_port_list *)addr;
2299
2300		if (list->alloc_len != (list->alloc_num *
2301		    sizeof(struct ctl_port_entry))) {
2302			printf("%s: CTL_GET_PORT_LIST: alloc_len %u != "
2303			       "alloc_num %u * sizeof(struct ctl_port_entry) "
2304			       "%zu\n", __func__, list->alloc_len,
2305			       list->alloc_num, sizeof(struct ctl_port_entry));
2306			retval = EINVAL;
2307			break;
2308		}
2309		list->fill_len = 0;
2310		list->fill_num = 0;
2311		list->dropped_num = 0;
2312		i = 0;
2313		mtx_lock(&softc->ctl_lock);
2314		STAILQ_FOREACH(fe, &softc->fe_list, links) {
2315			struct ctl_port_entry entry, *list_entry;
2316
2317			if (list->fill_num >= list->alloc_num) {
2318				list->dropped_num++;
2319				continue;
2320			}
2321
2322			entry.port_type = fe->port_type;
2323			strlcpy(entry.port_name, fe->port_name,
2324				sizeof(entry.port_name));
2325			entry.targ_port = fe->targ_port;
2326			entry.physical_port = fe->physical_port;
2327			entry.virtual_port = fe->virtual_port;
2328			entry.wwnn = fe->wwnn;
2329			entry.wwpn = fe->wwpn;
2330			if (fe->status & CTL_PORT_STATUS_ONLINE)
2331				entry.online = 1;
2332			else
2333				entry.online = 0;
2334
2335			list_entry = &list->entries[i];
2336
2337			retval = copyout(&entry, list_entry, sizeof(entry));
2338			if (retval != 0) {
2339				printf("%s: CTL_GET_PORT_LIST: copyout "
2340				       "returned %d\n", __func__, retval);
2341				break;
2342			}
2343			i++;
2344			list->fill_num++;
2345			list->fill_len += sizeof(entry);
2346		}
2347		mtx_unlock(&softc->ctl_lock);
2348
2349		/*
2350		 * If this is non-zero, we had a copyout fault, so there's
2351		 * probably no point in attempting to set the status inside
2352		 * the structure.
2353		 */
2354		if (retval != 0)
2355			break;
2356
2357		if (list->dropped_num > 0)
2358			list->status = CTL_PORT_LIST_NEED_MORE_SPACE;
2359		else
2360			list->status = CTL_PORT_LIST_OK;
2361		break;
2362	}
2363	case CTL_DUMP_OOA: {
2364		struct ctl_lun *lun;
2365		union ctl_io *io;
2366		char printbuf[128];
2367		struct sbuf sb;
2368
2369		mtx_lock(&softc->ctl_lock);
2370		printf("Dumping OOA queues:\n");
2371		STAILQ_FOREACH(lun, &softc->lun_list, links) {
2372			mtx_lock(&lun->lun_lock);
2373			for (io = (union ctl_io *)TAILQ_FIRST(
2374			     &lun->ooa_queue); io != NULL;
2375			     io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2376			     ooa_links)) {
2377				sbuf_new(&sb, printbuf, sizeof(printbuf),
2378					 SBUF_FIXEDLEN);
2379				sbuf_printf(&sb, "LUN %jd tag 0x%04x%s%s%s%s: ",
2380					    (intmax_t)lun->lun,
2381					    io->scsiio.tag_num,
2382					    (io->io_hdr.flags &
2383					    CTL_FLAG_BLOCKED) ? "" : " BLOCKED",
2384					    (io->io_hdr.flags &
2385					    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
2386					    (io->io_hdr.flags &
2387					    CTL_FLAG_ABORT) ? " ABORT" : "",
2388			                    (io->io_hdr.flags &
2389		                        CTL_FLAG_IS_WAS_ON_RTR) ? " RTR" : "");
2390				ctl_scsi_command_string(&io->scsiio, NULL, &sb);
2391				sbuf_finish(&sb);
2392				printf("%s\n", sbuf_data(&sb));
2393			}
2394			mtx_unlock(&lun->lun_lock);
2395		}
2396		printf("OOA queues dump done\n");
2397		mtx_unlock(&softc->ctl_lock);
2398		break;
2399	}
2400	case CTL_GET_OOA: {
2401		struct ctl_lun *lun;
2402		struct ctl_ooa *ooa_hdr;
2403		struct ctl_ooa_entry *entries;
2404		uint32_t cur_fill_num;
2405
2406		ooa_hdr = (struct ctl_ooa *)addr;
2407
2408		if ((ooa_hdr->alloc_len == 0)
2409		 || (ooa_hdr->alloc_num == 0)) {
2410			printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2411			       "must be non-zero\n", __func__,
2412			       ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2413			retval = EINVAL;
2414			break;
2415		}
2416
2417		if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2418		    sizeof(struct ctl_ooa_entry))) {
2419			printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2420			       "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2421			       __func__, ooa_hdr->alloc_len,
2422			       ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2423			retval = EINVAL;
2424			break;
2425		}
2426
2427		entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2428		if (entries == NULL) {
2429			printf("%s: could not allocate %d bytes for OOA "
2430			       "dump\n", __func__, ooa_hdr->alloc_len);
2431			retval = ENOMEM;
2432			break;
2433		}
2434
2435		mtx_lock(&softc->ctl_lock);
2436		if (((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0)
2437		 && ((ooa_hdr->lun_num > CTL_MAX_LUNS)
2438		  || (softc->ctl_luns[ooa_hdr->lun_num] == NULL))) {
2439			mtx_unlock(&softc->ctl_lock);
2440			free(entries, M_CTL);
2441			printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2442			       __func__, (uintmax_t)ooa_hdr->lun_num);
2443			retval = EINVAL;
2444			break;
2445		}
2446
2447		cur_fill_num = 0;
2448
2449		if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2450			STAILQ_FOREACH(lun, &softc->lun_list, links) {
2451				retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2452					ooa_hdr, entries);
2453				if (retval != 0)
2454					break;
2455			}
2456			if (retval != 0) {
2457				mtx_unlock(&softc->ctl_lock);
2458				free(entries, M_CTL);
2459				break;
2460			}
2461		} else {
2462			lun = softc->ctl_luns[ooa_hdr->lun_num];
2463
2464			retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,ooa_hdr,
2465						    entries);
2466		}
2467		mtx_unlock(&softc->ctl_lock);
2468
2469		ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2470		ooa_hdr->fill_len = ooa_hdr->fill_num *
2471			sizeof(struct ctl_ooa_entry);
2472		retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2473		if (retval != 0) {
2474			printf("%s: error copying out %d bytes for OOA dump\n",
2475			       __func__, ooa_hdr->fill_len);
2476		}
2477
2478		getbintime(&ooa_hdr->cur_bt);
2479
2480		if (cur_fill_num > ooa_hdr->alloc_num) {
2481			ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2482			ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2483		} else {
2484			ooa_hdr->dropped_num = 0;
2485			ooa_hdr->status = CTL_OOA_OK;
2486		}
2487
2488		free(entries, M_CTL);
2489		break;
2490	}
2491	case CTL_CHECK_OOA: {
2492		union ctl_io *io;
2493		struct ctl_lun *lun;
2494		struct ctl_ooa_info *ooa_info;
2495
2496
2497		ooa_info = (struct ctl_ooa_info *)addr;
2498
2499		if (ooa_info->lun_id >= CTL_MAX_LUNS) {
2500			ooa_info->status = CTL_OOA_INVALID_LUN;
2501			break;
2502		}
2503		mtx_lock(&softc->ctl_lock);
2504		lun = softc->ctl_luns[ooa_info->lun_id];
2505		if (lun == NULL) {
2506			mtx_unlock(&softc->ctl_lock);
2507			ooa_info->status = CTL_OOA_INVALID_LUN;
2508			break;
2509		}
2510		mtx_lock(&lun->lun_lock);
2511		mtx_unlock(&softc->ctl_lock);
2512		ooa_info->num_entries = 0;
2513		for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
2514		     io != NULL; io = (union ctl_io *)TAILQ_NEXT(
2515		     &io->io_hdr, ooa_links)) {
2516			ooa_info->num_entries++;
2517		}
2518		mtx_unlock(&lun->lun_lock);
2519
2520		ooa_info->status = CTL_OOA_SUCCESS;
2521
2522		break;
2523	}
2524	case CTL_HARD_START:
2525	case CTL_HARD_STOP: {
2526		struct ctl_fe_ioctl_startstop_info ss_info;
2527		struct cfi_metatask *metatask;
2528		struct mtx hs_mtx;
2529
2530		mtx_init(&hs_mtx, "HS Mutex", NULL, MTX_DEF);
2531
2532		cv_init(&ss_info.sem, "hard start/stop cv" );
2533
2534		metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2535		if (metatask == NULL) {
2536			retval = ENOMEM;
2537			mtx_destroy(&hs_mtx);
2538			break;
2539		}
2540
2541		if (cmd == CTL_HARD_START)
2542			metatask->tasktype = CFI_TASK_STARTUP;
2543		else
2544			metatask->tasktype = CFI_TASK_SHUTDOWN;
2545
2546		metatask->callback = ctl_ioctl_hard_startstop_callback;
2547		metatask->callback_arg = &ss_info;
2548
2549		cfi_action(metatask);
2550
2551		/* Wait for the callback */
2552		mtx_lock(&hs_mtx);
2553		cv_wait_sig(&ss_info.sem, &hs_mtx);
2554		mtx_unlock(&hs_mtx);
2555
2556		/*
2557		 * All information has been copied from the metatask by the
2558		 * time cv_broadcast() is called, so we free the metatask here.
2559		 */
2560		cfi_free_metatask(metatask);
2561
2562		memcpy((void *)addr, &ss_info.hs_info, sizeof(ss_info.hs_info));
2563
2564		mtx_destroy(&hs_mtx);
2565		break;
2566	}
2567	case CTL_BBRREAD: {
2568		struct ctl_bbrread_info *bbr_info;
2569		struct ctl_fe_ioctl_bbrread_info fe_bbr_info;
2570		struct mtx bbr_mtx;
2571		struct cfi_metatask *metatask;
2572
2573		bbr_info = (struct ctl_bbrread_info *)addr;
2574
2575		bzero(&fe_bbr_info, sizeof(fe_bbr_info));
2576
2577		bzero(&bbr_mtx, sizeof(bbr_mtx));
2578		mtx_init(&bbr_mtx, "BBR Mutex", NULL, MTX_DEF);
2579
2580		fe_bbr_info.bbr_info = bbr_info;
2581		fe_bbr_info.lock = &bbr_mtx;
2582
2583		cv_init(&fe_bbr_info.sem, "BBR read cv");
2584		metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2585
2586		if (metatask == NULL) {
2587			mtx_destroy(&bbr_mtx);
2588			cv_destroy(&fe_bbr_info.sem);
2589			retval = ENOMEM;
2590			break;
2591		}
2592		metatask->tasktype = CFI_TASK_BBRREAD;
2593		metatask->callback = ctl_ioctl_bbrread_callback;
2594		metatask->callback_arg = &fe_bbr_info;
2595		metatask->taskinfo.bbrread.lun_num = bbr_info->lun_num;
2596		metatask->taskinfo.bbrread.lba = bbr_info->lba;
2597		metatask->taskinfo.bbrread.len = bbr_info->len;
2598
2599		cfi_action(metatask);
2600
2601		mtx_lock(&bbr_mtx);
2602		while (fe_bbr_info.wakeup_done == 0)
2603			cv_wait_sig(&fe_bbr_info.sem, &bbr_mtx);
2604		mtx_unlock(&bbr_mtx);
2605
2606		bbr_info->status = metatask->status;
2607		bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2608		bbr_info->scsi_status = metatask->taskinfo.bbrread.scsi_status;
2609		memcpy(&bbr_info->sense_data,
2610		       &metatask->taskinfo.bbrread.sense_data,
2611		       ctl_min(sizeof(bbr_info->sense_data),
2612			       sizeof(metatask->taskinfo.bbrread.sense_data)));
2613
2614		cfi_free_metatask(metatask);
2615
2616		mtx_destroy(&bbr_mtx);
2617		cv_destroy(&fe_bbr_info.sem);
2618
2619		break;
2620	}
2621	case CTL_DELAY_IO: {
2622		struct ctl_io_delay_info *delay_info;
2623#ifdef CTL_IO_DELAY
2624		struct ctl_lun *lun;
2625#endif /* CTL_IO_DELAY */
2626
2627		delay_info = (struct ctl_io_delay_info *)addr;
2628
2629#ifdef CTL_IO_DELAY
2630		mtx_lock(&softc->ctl_lock);
2631
2632		if ((delay_info->lun_id > CTL_MAX_LUNS)
2633		 || (softc->ctl_luns[delay_info->lun_id] == NULL)) {
2634			delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2635		} else {
2636			lun = softc->ctl_luns[delay_info->lun_id];
2637			mtx_lock(&lun->lun_lock);
2638
2639			delay_info->status = CTL_DELAY_STATUS_OK;
2640
2641			switch (delay_info->delay_type) {
2642			case CTL_DELAY_TYPE_CONT:
2643				break;
2644			case CTL_DELAY_TYPE_ONESHOT:
2645				break;
2646			default:
2647				delay_info->status =
2648					CTL_DELAY_STATUS_INVALID_TYPE;
2649				break;
2650			}
2651
2652			switch (delay_info->delay_loc) {
2653			case CTL_DELAY_LOC_DATAMOVE:
2654				lun->delay_info.datamove_type =
2655					delay_info->delay_type;
2656				lun->delay_info.datamove_delay =
2657					delay_info->delay_secs;
2658				break;
2659			case CTL_DELAY_LOC_DONE:
2660				lun->delay_info.done_type =
2661					delay_info->delay_type;
2662				lun->delay_info.done_delay =
2663					delay_info->delay_secs;
2664				break;
2665			default:
2666				delay_info->status =
2667					CTL_DELAY_STATUS_INVALID_LOC;
2668				break;
2669			}
2670			mtx_unlock(&lun->lun_lock);
2671		}
2672
2673		mtx_unlock(&softc->ctl_lock);
2674#else
2675		delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2676#endif /* CTL_IO_DELAY */
2677		break;
2678	}
2679	case CTL_REALSYNC_SET: {
2680		int *syncstate;
2681
2682		syncstate = (int *)addr;
2683
2684		mtx_lock(&softc->ctl_lock);
2685		switch (*syncstate) {
2686		case 0:
2687			softc->flags &= ~CTL_FLAG_REAL_SYNC;
2688			break;
2689		case 1:
2690			softc->flags |= CTL_FLAG_REAL_SYNC;
2691			break;
2692		default:
2693			retval = EINVAL;
2694			break;
2695		}
2696		mtx_unlock(&softc->ctl_lock);
2697		break;
2698	}
2699	case CTL_REALSYNC_GET: {
2700		int *syncstate;
2701
2702		syncstate = (int*)addr;
2703
2704		mtx_lock(&softc->ctl_lock);
2705		if (softc->flags & CTL_FLAG_REAL_SYNC)
2706			*syncstate = 1;
2707		else
2708			*syncstate = 0;
2709		mtx_unlock(&softc->ctl_lock);
2710
2711		break;
2712	}
2713	case CTL_SETSYNC:
2714	case CTL_GETSYNC: {
2715		struct ctl_sync_info *sync_info;
2716		struct ctl_lun *lun;
2717
2718		sync_info = (struct ctl_sync_info *)addr;
2719
2720		mtx_lock(&softc->ctl_lock);
2721		lun = softc->ctl_luns[sync_info->lun_id];
2722		if (lun == NULL) {
2723			mtx_unlock(&softc->ctl_lock);
2724			sync_info->status = CTL_GS_SYNC_NO_LUN;
2725		}
2726		/*
2727		 * Get or set the sync interval.  We're not bounds checking
2728		 * in the set case, hopefully the user won't do something
2729		 * silly.
2730		 */
2731		mtx_lock(&lun->lun_lock);
2732		mtx_unlock(&softc->ctl_lock);
2733		if (cmd == CTL_GETSYNC)
2734			sync_info->sync_interval = lun->sync_interval;
2735		else
2736			lun->sync_interval = sync_info->sync_interval;
2737		mtx_unlock(&lun->lun_lock);
2738
2739		sync_info->status = CTL_GS_SYNC_OK;
2740
2741		break;
2742	}
2743	case CTL_GETSTATS: {
2744		struct ctl_stats *stats;
2745		struct ctl_lun *lun;
2746		int i;
2747
2748		stats = (struct ctl_stats *)addr;
2749
2750		if ((sizeof(struct ctl_lun_io_stats) * softc->num_luns) >
2751		     stats->alloc_len) {
2752			stats->status = CTL_SS_NEED_MORE_SPACE;
2753			stats->num_luns = softc->num_luns;
2754			break;
2755		}
2756		/*
2757		 * XXX KDM no locking here.  If the LUN list changes,
2758		 * things can blow up.
2759		 */
2760		for (i = 0, lun = STAILQ_FIRST(&softc->lun_list); lun != NULL;
2761		     i++, lun = STAILQ_NEXT(lun, links)) {
2762			retval = copyout(&lun->stats, &stats->lun_stats[i],
2763					 sizeof(lun->stats));
2764			if (retval != 0)
2765				break;
2766		}
2767		stats->num_luns = softc->num_luns;
2768		stats->fill_len = sizeof(struct ctl_lun_io_stats) *
2769				 softc->num_luns;
2770		stats->status = CTL_SS_OK;
2771#ifdef CTL_TIME_IO
2772		stats->flags = CTL_STATS_FLAG_TIME_VALID;
2773#else
2774		stats->flags = CTL_STATS_FLAG_NONE;
2775#endif
2776		getnanouptime(&stats->timestamp);
2777		break;
2778	}
2779	case CTL_ERROR_INJECT: {
2780		struct ctl_error_desc *err_desc, *new_err_desc;
2781		struct ctl_lun *lun;
2782
2783		err_desc = (struct ctl_error_desc *)addr;
2784
2785		new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2786				      M_WAITOK | M_ZERO);
2787		bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2788
2789		mtx_lock(&softc->ctl_lock);
2790		lun = softc->ctl_luns[err_desc->lun_id];
2791		if (lun == NULL) {
2792			mtx_unlock(&softc->ctl_lock);
2793			printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
2794			       __func__, (uintmax_t)err_desc->lun_id);
2795			retval = EINVAL;
2796			break;
2797		}
2798		mtx_lock(&lun->lun_lock);
2799		mtx_unlock(&softc->ctl_lock);
2800
2801		/*
2802		 * We could do some checking here to verify the validity
2803		 * of the request, but given the complexity of error
2804		 * injection requests, the checking logic would be fairly
2805		 * complex.
2806		 *
2807		 * For now, if the request is invalid, it just won't get
2808		 * executed and might get deleted.
2809		 */
2810		STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
2811
2812		/*
2813		 * XXX KDM check to make sure the serial number is unique,
2814		 * in case we somehow manage to wrap.  That shouldn't
2815		 * happen for a very long time, but it's the right thing to
2816		 * do.
2817		 */
2818		new_err_desc->serial = lun->error_serial;
2819		err_desc->serial = lun->error_serial;
2820		lun->error_serial++;
2821
2822		mtx_unlock(&lun->lun_lock);
2823		break;
2824	}
2825	case CTL_ERROR_INJECT_DELETE: {
2826		struct ctl_error_desc *delete_desc, *desc, *desc2;
2827		struct ctl_lun *lun;
2828		int delete_done;
2829
2830		delete_desc = (struct ctl_error_desc *)addr;
2831		delete_done = 0;
2832
2833		mtx_lock(&softc->ctl_lock);
2834		lun = softc->ctl_luns[delete_desc->lun_id];
2835		if (lun == NULL) {
2836			mtx_unlock(&softc->ctl_lock);
2837			printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
2838			       __func__, (uintmax_t)delete_desc->lun_id);
2839			retval = EINVAL;
2840			break;
2841		}
2842		mtx_lock(&lun->lun_lock);
2843		mtx_unlock(&softc->ctl_lock);
2844		STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
2845			if (desc->serial != delete_desc->serial)
2846				continue;
2847
2848			STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
2849				      links);
2850			free(desc, M_CTL);
2851			delete_done = 1;
2852		}
2853		mtx_unlock(&lun->lun_lock);
2854		if (delete_done == 0) {
2855			printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
2856			       "error serial %ju on LUN %u\n", __func__,
2857			       delete_desc->serial, delete_desc->lun_id);
2858			retval = EINVAL;
2859			break;
2860		}
2861		break;
2862	}
2863	case CTL_DUMP_STRUCTS: {
2864		int i, j, k;
2865		struct ctl_frontend *fe;
2866
2867		printf("CTL IID to WWPN map start:\n");
2868		for (i = 0; i < CTL_MAX_PORTS; i++) {
2869			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
2870				if (softc->wwpn_iid[i][j].in_use == 0)
2871					continue;
2872
2873				printf("port %d iid %u WWPN %#jx\n",
2874				       softc->wwpn_iid[i][j].port,
2875				       softc->wwpn_iid[i][j].iid,
2876				       (uintmax_t)softc->wwpn_iid[i][j].wwpn);
2877			}
2878		}
2879		printf("CTL IID to WWPN map end\n");
2880		printf("CTL Persistent Reservation information start:\n");
2881		for (i = 0; i < CTL_MAX_LUNS; i++) {
2882			struct ctl_lun *lun;
2883
2884			lun = softc->ctl_luns[i];
2885
2886			if ((lun == NULL)
2887			 || ((lun->flags & CTL_LUN_DISABLED) != 0))
2888				continue;
2889
2890			for (j = 0; j < (CTL_MAX_PORTS * 2); j++) {
2891				for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
2892					if (lun->per_res[j+k].registered == 0)
2893						continue;
2894					printf("LUN %d port %d iid %d key "
2895					       "%#jx\n", i, j, k,
2896					       (uintmax_t)scsi_8btou64(
2897					       lun->per_res[j+k].res_key.key));
2898				}
2899			}
2900		}
2901		printf("CTL Persistent Reservation information end\n");
2902		printf("CTL Frontends:\n");
2903		/*
2904		 * XXX KDM calling this without a lock.  We'd likely want
2905		 * to drop the lock before calling the frontend's dump
2906		 * routine anyway.
2907		 */
2908		STAILQ_FOREACH(fe, &softc->fe_list, links) {
2909			printf("Frontend %s Type %u pport %d vport %d WWNN "
2910			       "%#jx WWPN %#jx\n", fe->port_name, fe->port_type,
2911			       fe->physical_port, fe->virtual_port,
2912			       (uintmax_t)fe->wwnn, (uintmax_t)fe->wwpn);
2913
2914			/*
2915			 * Frontends are not required to support the dump
2916			 * routine.
2917			 */
2918			if (fe->fe_dump == NULL)
2919				continue;
2920
2921			fe->fe_dump();
2922		}
2923		printf("CTL Frontend information end\n");
2924		break;
2925	}
2926	case CTL_LUN_REQ: {
2927		struct ctl_lun_req *lun_req;
2928		struct ctl_backend_driver *backend;
2929
2930		lun_req = (struct ctl_lun_req *)addr;
2931
2932		backend = ctl_backend_find(lun_req->backend);
2933		if (backend == NULL) {
2934			lun_req->status = CTL_LUN_ERROR;
2935			snprintf(lun_req->error_str,
2936				 sizeof(lun_req->error_str),
2937				 "Backend \"%s\" not found.",
2938				 lun_req->backend);
2939			break;
2940		}
2941		if (lun_req->num_be_args > 0) {
2942			lun_req->kern_be_args = ctl_copyin_args(
2943				lun_req->num_be_args,
2944				lun_req->be_args,
2945				lun_req->error_str,
2946				sizeof(lun_req->error_str));
2947			if (lun_req->kern_be_args == NULL) {
2948				lun_req->status = CTL_LUN_ERROR;
2949				break;
2950			}
2951		}
2952
2953		retval = backend->ioctl(dev, cmd, addr, flag, td);
2954
2955		if (lun_req->num_be_args > 0) {
2956			ctl_free_args(lun_req->num_be_args,
2957				      lun_req->kern_be_args);
2958		}
2959		break;
2960	}
2961	case CTL_LUN_LIST: {
2962		struct sbuf *sb;
2963		struct ctl_lun *lun;
2964		struct ctl_lun_list *list;
2965		struct ctl_be_lun_option *opt;
2966
2967		list = (struct ctl_lun_list *)addr;
2968
2969		/*
2970		 * Allocate a fixed length sbuf here, based on the length
2971		 * of the user's buffer.  We could allocate an auto-extending
2972		 * buffer, and then tell the user how much larger our
2973		 * amount of data is than his buffer, but that presents
2974		 * some problems:
2975		 *
2976		 * 1.  The sbuf(9) routines use a blocking malloc, and so
2977		 *     we can't hold a lock while calling them with an
2978		 *     auto-extending buffer.
2979 		 *
2980		 * 2.  There is not currently a LUN reference counting
2981		 *     mechanism, outside of outstanding transactions on
2982		 *     the LUN's OOA queue.  So a LUN could go away on us
2983		 *     while we're getting the LUN number, backend-specific
2984		 *     information, etc.  Thus, given the way things
2985		 *     currently work, we need to hold the CTL lock while
2986		 *     grabbing LUN information.
2987		 *
2988		 * So, from the user's standpoint, the best thing to do is
2989		 * allocate what he thinks is a reasonable buffer length,
2990		 * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
2991		 * double the buffer length and try again.  (And repeat
2992		 * that until he succeeds.)
2993		 */
2994		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
2995		if (sb == NULL) {
2996			list->status = CTL_LUN_LIST_ERROR;
2997			snprintf(list->error_str, sizeof(list->error_str),
2998				 "Unable to allocate %d bytes for LUN list",
2999				 list->alloc_len);
3000			break;
3001		}
3002
3003		sbuf_printf(sb, "<ctllunlist>\n");
3004
3005		mtx_lock(&softc->ctl_lock);
3006		STAILQ_FOREACH(lun, &softc->lun_list, links) {
3007			mtx_lock(&lun->lun_lock);
3008			retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3009					     (uintmax_t)lun->lun);
3010
3011			/*
3012			 * Bail out as soon as we see that we've overfilled
3013			 * the buffer.
3014			 */
3015			if (retval != 0)
3016				break;
3017
3018			retval = sbuf_printf(sb, "\t<backend_type>%s"
3019					     "</backend_type>\n",
3020					     (lun->backend == NULL) ?  "none" :
3021					     lun->backend->name);
3022
3023			if (retval != 0)
3024				break;
3025
3026			retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3027					     lun->be_lun->lun_type);
3028
3029			if (retval != 0)
3030				break;
3031
3032			if (lun->backend == NULL) {
3033				retval = sbuf_printf(sb, "</lun>\n");
3034				if (retval != 0)
3035					break;
3036				continue;
3037			}
3038
3039			retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3040					     (lun->be_lun->maxlba > 0) ?
3041					     lun->be_lun->maxlba + 1 : 0);
3042
3043			if (retval != 0)
3044				break;
3045
3046			retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3047					     lun->be_lun->blocksize);
3048
3049			if (retval != 0)
3050				break;
3051
3052			retval = sbuf_printf(sb, "\t<serial_number>");
3053
3054			if (retval != 0)
3055				break;
3056
3057			retval = ctl_sbuf_printf_esc(sb,
3058						     lun->be_lun->serial_num);
3059
3060			if (retval != 0)
3061				break;
3062
3063			retval = sbuf_printf(sb, "</serial_number>\n");
3064
3065			if (retval != 0)
3066				break;
3067
3068			retval = sbuf_printf(sb, "\t<device_id>");
3069
3070			if (retval != 0)
3071				break;
3072
3073			retval = ctl_sbuf_printf_esc(sb,lun->be_lun->device_id);
3074
3075			if (retval != 0)
3076				break;
3077
3078			retval = sbuf_printf(sb, "</device_id>\n");
3079
3080			if (retval != 0)
3081				break;
3082
3083			if (lun->backend->lun_info != NULL) {
3084				retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
3085				if (retval != 0)
3086					break;
3087			}
3088			STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
3089				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3090				    opt->name, opt->value, opt->name);
3091				if (retval != 0)
3092					break;
3093			}
3094
3095			retval = sbuf_printf(sb, "</lun>\n");
3096
3097			if (retval != 0)
3098				break;
3099			mtx_unlock(&lun->lun_lock);
3100		}
3101		if (lun != NULL)
3102			mtx_unlock(&lun->lun_lock);
3103		mtx_unlock(&softc->ctl_lock);
3104
3105		if ((retval != 0)
3106		 || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3107			retval = 0;
3108			sbuf_delete(sb);
3109			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3110			snprintf(list->error_str, sizeof(list->error_str),
3111				 "Out of space, %d bytes is too small",
3112				 list->alloc_len);
3113			break;
3114		}
3115
3116		sbuf_finish(sb);
3117
3118		retval = copyout(sbuf_data(sb), list->lun_xml,
3119				 sbuf_len(sb) + 1);
3120
3121		list->fill_len = sbuf_len(sb) + 1;
3122		list->status = CTL_LUN_LIST_OK;
3123		sbuf_delete(sb);
3124		break;
3125	}
3126	case CTL_ISCSI: {
3127		struct ctl_iscsi *ci;
3128		struct ctl_frontend *fe;
3129
3130		ci = (struct ctl_iscsi *)addr;
3131
3132		mtx_lock(&softc->ctl_lock);
3133		STAILQ_FOREACH(fe, &softc->fe_list, links) {
3134			if (strcmp(fe->port_name, "iscsi") == 0)
3135				break;
3136		}
3137		mtx_unlock(&softc->ctl_lock);
3138
3139		if (fe == NULL) {
3140			ci->status = CTL_ISCSI_ERROR;
3141			snprintf(ci->error_str, sizeof(ci->error_str), "Backend \"iscsi\" not found.");
3142			break;
3143		}
3144
3145		retval = fe->ioctl(dev, cmd, addr, flag, td);
3146		break;
3147	}
3148	default: {
3149		/* XXX KDM should we fix this? */
3150#if 0
3151		struct ctl_backend_driver *backend;
3152		unsigned int type;
3153		int found;
3154
3155		found = 0;
3156
3157		/*
3158		 * We encode the backend type as the ioctl type for backend
3159		 * ioctls.  So parse it out here, and then search for a
3160		 * backend of this type.
3161		 */
3162		type = _IOC_TYPE(cmd);
3163
3164		STAILQ_FOREACH(backend, &softc->be_list, links) {
3165			if (backend->type == type) {
3166				found = 1;
3167				break;
3168			}
3169		}
3170		if (found == 0) {
3171			printf("ctl: unknown ioctl command %#lx or backend "
3172			       "%d\n", cmd, type);
3173			retval = EINVAL;
3174			break;
3175		}
3176		retval = backend->ioctl(dev, cmd, addr, flag, td);
3177#endif
3178		retval = ENOTTY;
3179		break;
3180	}
3181	}
3182	return (retval);
3183}
3184
3185uint32_t
3186ctl_get_initindex(struct ctl_nexus *nexus)
3187{
3188	if (nexus->targ_port < CTL_MAX_PORTS)
3189		return (nexus->initid.id +
3190			(nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3191	else
3192		return (nexus->initid.id +
3193		       ((nexus->targ_port - CTL_MAX_PORTS) *
3194			CTL_MAX_INIT_PER_PORT));
3195}
3196
3197uint32_t
3198ctl_get_resindex(struct ctl_nexus *nexus)
3199{
3200	return (nexus->initid.id + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3201}
3202
3203uint32_t
3204ctl_port_idx(int port_num)
3205{
3206	if (port_num < CTL_MAX_PORTS)
3207		return(port_num);
3208	else
3209		return(port_num - CTL_MAX_PORTS);
3210}
3211
3212/*
3213 * Note:  This only works for bitmask sizes that are at least 32 bits, and
3214 * that are a power of 2.
3215 */
3216int
3217ctl_ffz(uint32_t *mask, uint32_t size)
3218{
3219	uint32_t num_chunks, num_pieces;
3220	int i, j;
3221
3222	num_chunks = (size >> 5);
3223	if (num_chunks == 0)
3224		num_chunks++;
3225	num_pieces = ctl_min((sizeof(uint32_t) * 8), size);
3226
3227	for (i = 0; i < num_chunks; i++) {
3228		for (j = 0; j < num_pieces; j++) {
3229			if ((mask[i] & (1 << j)) == 0)
3230				return ((i << 5) + j);
3231		}
3232	}
3233
3234	return (-1);
3235}
3236
3237int
3238ctl_set_mask(uint32_t *mask, uint32_t bit)
3239{
3240	uint32_t chunk, piece;
3241
3242	chunk = bit >> 5;
3243	piece = bit % (sizeof(uint32_t) * 8);
3244
3245	if ((mask[chunk] & (1 << piece)) != 0)
3246		return (-1);
3247	else
3248		mask[chunk] |= (1 << piece);
3249
3250	return (0);
3251}
3252
3253int
3254ctl_clear_mask(uint32_t *mask, uint32_t bit)
3255{
3256	uint32_t chunk, piece;
3257
3258	chunk = bit >> 5;
3259	piece = bit % (sizeof(uint32_t) * 8);
3260
3261	if ((mask[chunk] & (1 << piece)) == 0)
3262		return (-1);
3263	else
3264		mask[chunk] &= ~(1 << piece);
3265
3266	return (0);
3267}
3268
3269int
3270ctl_is_set(uint32_t *mask, uint32_t bit)
3271{
3272	uint32_t chunk, piece;
3273
3274	chunk = bit >> 5;
3275	piece = bit % (sizeof(uint32_t) * 8);
3276
3277	if ((mask[chunk] & (1 << piece)) == 0)
3278		return (0);
3279	else
3280		return (1);
3281}
3282
3283#ifdef unused
3284/*
3285 * The bus, target and lun are optional, they can be filled in later.
3286 * can_wait is used to determine whether we can wait on the malloc or not.
3287 */
3288union ctl_io*
3289ctl_malloc_io(ctl_io_type io_type, uint32_t targ_port, uint32_t targ_target,
3290	      uint32_t targ_lun, int can_wait)
3291{
3292	union ctl_io *io;
3293
3294	if (can_wait)
3295		io = (union ctl_io *)malloc(sizeof(*io), M_CTL, M_WAITOK);
3296	else
3297		io = (union ctl_io *)malloc(sizeof(*io), M_CTL, M_NOWAIT);
3298
3299	if (io != NULL) {
3300		io->io_hdr.io_type = io_type;
3301		io->io_hdr.targ_port = targ_port;
3302		/*
3303		 * XXX KDM this needs to change/go away.  We need to move
3304		 * to a preallocated pool of ctl_scsiio structures.
3305		 */
3306		io->io_hdr.nexus.targ_target.id = targ_target;
3307		io->io_hdr.nexus.targ_lun = targ_lun;
3308	}
3309
3310	return (io);
3311}
3312
3313void
3314ctl_kfree_io(union ctl_io *io)
3315{
3316	free(io, M_CTL);
3317}
3318#endif /* unused */
3319
3320/*
3321 * ctl_softc, pool_type, total_ctl_io are passed in.
3322 * npool is passed out.
3323 */
3324int
3325ctl_pool_create(struct ctl_softc *ctl_softc, ctl_pool_type pool_type,
3326		uint32_t total_ctl_io, struct ctl_io_pool **npool)
3327{
3328	uint32_t i;
3329	union ctl_io *cur_io, *next_io;
3330	struct ctl_io_pool *pool;
3331	int retval;
3332
3333	retval = 0;
3334
3335	pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3336					    M_NOWAIT | M_ZERO);
3337	if (pool == NULL) {
3338		retval = ENOMEM;
3339		goto bailout;
3340	}
3341
3342	pool->type = pool_type;
3343	pool->ctl_softc = ctl_softc;
3344
3345	mtx_lock(&ctl_softc->pool_lock);
3346	pool->id = ctl_softc->cur_pool_id++;
3347	mtx_unlock(&ctl_softc->pool_lock);
3348
3349	pool->flags = CTL_POOL_FLAG_NONE;
3350	pool->refcount = 1;		/* Reference for validity. */
3351	STAILQ_INIT(&pool->free_queue);
3352
3353	/*
3354	 * XXX KDM other options here:
3355	 * - allocate a page at a time
3356	 * - allocate one big chunk of memory.
3357	 * Page allocation might work well, but would take a little more
3358	 * tracking.
3359	 */
3360	for (i = 0; i < total_ctl_io; i++) {
3361		cur_io = (union ctl_io *)malloc(sizeof(*cur_io), M_CTLIO,
3362						M_NOWAIT);
3363		if (cur_io == NULL) {
3364			retval = ENOMEM;
3365			break;
3366		}
3367		cur_io->io_hdr.pool = pool;
3368		STAILQ_INSERT_TAIL(&pool->free_queue, &cur_io->io_hdr, links);
3369		pool->total_ctl_io++;
3370		pool->free_ctl_io++;
3371	}
3372
3373	if (retval != 0) {
3374		for (cur_io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue);
3375		     cur_io != NULL; cur_io = next_io) {
3376			next_io = (union ctl_io *)STAILQ_NEXT(&cur_io->io_hdr,
3377							      links);
3378			STAILQ_REMOVE(&pool->free_queue, &cur_io->io_hdr,
3379				      ctl_io_hdr, links);
3380			free(cur_io, M_CTLIO);
3381		}
3382
3383		free(pool, M_CTL);
3384		goto bailout;
3385	}
3386	mtx_lock(&ctl_softc->pool_lock);
3387	ctl_softc->num_pools++;
3388	STAILQ_INSERT_TAIL(&ctl_softc->io_pools, pool, links);
3389	/*
3390	 * Increment our usage count if this is an external consumer, so we
3391	 * can't get unloaded until the external consumer (most likely a
3392	 * FETD) unloads and frees his pool.
3393	 *
3394	 * XXX KDM will this increment the caller's module use count, or
3395	 * mine?
3396	 */
3397#if 0
3398	if ((pool_type != CTL_POOL_EMERGENCY)
3399	 && (pool_type != CTL_POOL_INTERNAL)
3400	 && (pool_type != CTL_POOL_IOCTL)
3401	 && (pool_type != CTL_POOL_4OTHERSC))
3402		MOD_INC_USE_COUNT;
3403#endif
3404
3405	mtx_unlock(&ctl_softc->pool_lock);
3406
3407	*npool = pool;
3408
3409bailout:
3410
3411	return (retval);
3412}
3413
3414static int
3415ctl_pool_acquire(struct ctl_io_pool *pool)
3416{
3417
3418	mtx_assert(&pool->ctl_softc->pool_lock, MA_OWNED);
3419
3420	if (pool->flags & CTL_POOL_FLAG_INVALID)
3421		return (EINVAL);
3422
3423	pool->refcount++;
3424
3425	return (0);
3426}
3427
3428static void
3429ctl_pool_release(struct ctl_io_pool *pool)
3430{
3431	struct ctl_softc *ctl_softc = pool->ctl_softc;
3432	union ctl_io *io;
3433
3434	mtx_assert(&ctl_softc->pool_lock, MA_OWNED);
3435
3436	if (--pool->refcount != 0)
3437		return;
3438
3439	while ((io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue)) != NULL) {
3440		STAILQ_REMOVE(&pool->free_queue, &io->io_hdr, ctl_io_hdr,
3441			      links);
3442		free(io, M_CTLIO);
3443	}
3444
3445	STAILQ_REMOVE(&ctl_softc->io_pools, pool, ctl_io_pool, links);
3446	ctl_softc->num_pools--;
3447
3448	/*
3449	 * XXX KDM will this decrement the caller's usage count or mine?
3450	 */
3451#if 0
3452	if ((pool->type != CTL_POOL_EMERGENCY)
3453	 && (pool->type != CTL_POOL_INTERNAL)
3454	 && (pool->type != CTL_POOL_IOCTL))
3455		MOD_DEC_USE_COUNT;
3456#endif
3457
3458	free(pool, M_CTL);
3459}
3460
3461void
3462ctl_pool_free(struct ctl_io_pool *pool)
3463{
3464	struct ctl_softc *ctl_softc;
3465
3466	if (pool == NULL)
3467		return;
3468
3469	ctl_softc = pool->ctl_softc;
3470	mtx_lock(&ctl_softc->pool_lock);
3471	pool->flags |= CTL_POOL_FLAG_INVALID;
3472	ctl_pool_release(pool);
3473	mtx_unlock(&ctl_softc->pool_lock);
3474}
3475
3476/*
3477 * This routine does not block (except for spinlocks of course).
3478 * It tries to allocate a ctl_io union from the caller's pool as quickly as
3479 * possible.
3480 */
3481union ctl_io *
3482ctl_alloc_io(void *pool_ref)
3483{
3484	union ctl_io *io;
3485	struct ctl_softc *ctl_softc;
3486	struct ctl_io_pool *pool, *npool;
3487	struct ctl_io_pool *emergency_pool;
3488
3489	pool = (struct ctl_io_pool *)pool_ref;
3490
3491	if (pool == NULL) {
3492		printf("%s: pool is NULL\n", __func__);
3493		return (NULL);
3494	}
3495
3496	emergency_pool = NULL;
3497
3498	ctl_softc = pool->ctl_softc;
3499
3500	mtx_lock(&ctl_softc->pool_lock);
3501	/*
3502	 * First, try to get the io structure from the user's pool.
3503	 */
3504	if (ctl_pool_acquire(pool) == 0) {
3505		io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue);
3506		if (io != NULL) {
3507			STAILQ_REMOVE_HEAD(&pool->free_queue, links);
3508			pool->total_allocated++;
3509			pool->free_ctl_io--;
3510			mtx_unlock(&ctl_softc->pool_lock);
3511			return (io);
3512		} else
3513			ctl_pool_release(pool);
3514	}
3515	/*
3516	 * If he doesn't have any io structures left, search for an
3517	 * emergency pool and grab one from there.
3518	 */
3519	STAILQ_FOREACH(npool, &ctl_softc->io_pools, links) {
3520		if (npool->type != CTL_POOL_EMERGENCY)
3521			continue;
3522
3523		if (ctl_pool_acquire(npool) != 0)
3524			continue;
3525
3526		emergency_pool = npool;
3527
3528		io = (union ctl_io *)STAILQ_FIRST(&npool->free_queue);
3529		if (io != NULL) {
3530			STAILQ_REMOVE_HEAD(&npool->free_queue, links);
3531			npool->total_allocated++;
3532			npool->free_ctl_io--;
3533			mtx_unlock(&ctl_softc->pool_lock);
3534			return (io);
3535		} else
3536			ctl_pool_release(npool);
3537	}
3538
3539	/* Drop the spinlock before we malloc */
3540	mtx_unlock(&ctl_softc->pool_lock);
3541
3542	/*
3543	 * The emergency pool (if it exists) didn't have one, so try an
3544	 * atomic (i.e. nonblocking) malloc and see if we get lucky.
3545	 */
3546	io = (union ctl_io *)malloc(sizeof(*io), M_CTLIO, M_NOWAIT);
3547	if (io != NULL) {
3548		/*
3549		 * If the emergency pool exists but is empty, add this
3550		 * ctl_io to its list when it gets freed.
3551		 */
3552		if (emergency_pool != NULL) {
3553			mtx_lock(&ctl_softc->pool_lock);
3554			if (ctl_pool_acquire(emergency_pool) == 0) {
3555				io->io_hdr.pool = emergency_pool;
3556				emergency_pool->total_ctl_io++;
3557				/*
3558				 * Need to bump this, otherwise
3559				 * total_allocated and total_freed won't
3560				 * match when we no longer have anything
3561				 * outstanding.
3562				 */
3563				emergency_pool->total_allocated++;
3564			}
3565			mtx_unlock(&ctl_softc->pool_lock);
3566		} else
3567			io->io_hdr.pool = NULL;
3568	}
3569
3570	return (io);
3571}
3572
3573void
3574ctl_free_io(union ctl_io *io)
3575{
3576	if (io == NULL)
3577		return;
3578
3579	/*
3580	 * If this ctl_io has a pool, return it to that pool.
3581	 */
3582	if (io->io_hdr.pool != NULL) {
3583		struct ctl_io_pool *pool;
3584
3585		pool = (struct ctl_io_pool *)io->io_hdr.pool;
3586		mtx_lock(&pool->ctl_softc->pool_lock);
3587		io->io_hdr.io_type = 0xff;
3588		STAILQ_INSERT_TAIL(&pool->free_queue, &io->io_hdr, links);
3589		pool->total_freed++;
3590		pool->free_ctl_io++;
3591		ctl_pool_release(pool);
3592		mtx_unlock(&pool->ctl_softc->pool_lock);
3593	} else {
3594		/*
3595		 * Otherwise, just free it.  We probably malloced it and
3596		 * the emergency pool wasn't available.
3597		 */
3598		free(io, M_CTLIO);
3599	}
3600
3601}
3602
3603void
3604ctl_zero_io(union ctl_io *io)
3605{
3606	void *pool_ref;
3607
3608	if (io == NULL)
3609		return;
3610
3611	/*
3612	 * May need to preserve linked list pointers at some point too.
3613	 */
3614	pool_ref = io->io_hdr.pool;
3615
3616	memset(io, 0, sizeof(*io));
3617
3618	io->io_hdr.pool = pool_ref;
3619}
3620
3621/*
3622 * This routine is currently used for internal copies of ctl_ios that need
3623 * to persist for some reason after we've already returned status to the
3624 * FETD.  (Thus the flag set.)
3625 *
3626 * XXX XXX
3627 * Note that this makes a blind copy of all fields in the ctl_io, except
3628 * for the pool reference.  This includes any memory that has been
3629 * allocated!  That memory will no longer be valid after done has been
3630 * called, so this would be VERY DANGEROUS for command that actually does
3631 * any reads or writes.  Right now (11/7/2005), this is only used for immediate
3632 * start and stop commands, which don't transfer any data, so this is not a
3633 * problem.  If it is used for anything else, the caller would also need to
3634 * allocate data buffer space and this routine would need to be modified to
3635 * copy the data buffer(s) as well.
3636 */
3637void
3638ctl_copy_io(union ctl_io *src, union ctl_io *dest)
3639{
3640	void *pool_ref;
3641
3642	if ((src == NULL)
3643	 || (dest == NULL))
3644		return;
3645
3646	/*
3647	 * May need to preserve linked list pointers at some point too.
3648	 */
3649	pool_ref = dest->io_hdr.pool;
3650
3651	memcpy(dest, src, ctl_min(sizeof(*src), sizeof(*dest)));
3652
3653	dest->io_hdr.pool = pool_ref;
3654	/*
3655	 * We need to know that this is an internal copy, and doesn't need
3656	 * to get passed back to the FETD that allocated it.
3657	 */
3658	dest->io_hdr.flags |= CTL_FLAG_INT_COPY;
3659}
3660
3661#ifdef NEEDTOPORT
3662static void
3663ctl_update_power_subpage(struct copan_power_subpage *page)
3664{
3665	int num_luns, num_partitions, config_type;
3666	struct ctl_softc *softc;
3667	cs_BOOL_t aor_present, shelf_50pct_power;
3668	cs_raidset_personality_t rs_type;
3669	int max_active_luns;
3670
3671	softc = control_softc;
3672
3673	/* subtract out the processor LUN */
3674	num_luns = softc->num_luns - 1;
3675	/*
3676	 * Default to 7 LUNs active, which was the only number we allowed
3677	 * in the past.
3678	 */
3679	max_active_luns = 7;
3680
3681	num_partitions = config_GetRsPartitionInfo();
3682	config_type = config_GetConfigType();
3683	shelf_50pct_power = config_GetShelfPowerMode();
3684	aor_present = config_IsAorRsPresent();
3685
3686	rs_type = ddb_GetRsRaidType(1);
3687	if ((rs_type != CS_RAIDSET_PERSONALITY_RAID5)
3688	 && (rs_type != CS_RAIDSET_PERSONALITY_RAID1)) {
3689		EPRINT(0, "Unsupported RS type %d!", rs_type);
3690	}
3691
3692
3693	page->total_luns = num_luns;
3694
3695	switch (config_type) {
3696	case 40:
3697		/*
3698		 * In a 40 drive configuration, it doesn't matter what DC
3699		 * cards we have, whether we have AOR enabled or not,
3700		 * partitioning or not, or what type of RAIDset we have.
3701		 * In that scenario, we can power up every LUN we present
3702		 * to the user.
3703		 */
3704		max_active_luns = num_luns;
3705
3706		break;
3707	case 64:
3708		if (shelf_50pct_power == CS_FALSE) {
3709			/* 25% power */
3710			if (aor_present == CS_TRUE) {
3711				if (rs_type ==
3712				     CS_RAIDSET_PERSONALITY_RAID5) {
3713					max_active_luns = 7;
3714				} else if (rs_type ==
3715					 CS_RAIDSET_PERSONALITY_RAID1){
3716					max_active_luns = 14;
3717				} else {
3718					/* XXX KDM now what?? */
3719				}
3720			} else {
3721				if (rs_type ==
3722				     CS_RAIDSET_PERSONALITY_RAID5) {
3723					max_active_luns = 8;
3724				} else if (rs_type ==
3725					 CS_RAIDSET_PERSONALITY_RAID1){
3726					max_active_luns = 16;
3727				} else {
3728					/* XXX KDM now what?? */
3729				}
3730			}
3731		} else {
3732			/* 50% power */
3733			/*
3734			 * With 50% power in a 64 drive configuration, we
3735			 * can power all LUNs we present.
3736			 */
3737			max_active_luns = num_luns;
3738		}
3739		break;
3740	case 112:
3741		if (shelf_50pct_power == CS_FALSE) {
3742			/* 25% power */
3743			if (aor_present == CS_TRUE) {
3744				if (rs_type ==
3745				     CS_RAIDSET_PERSONALITY_RAID5) {
3746					max_active_luns = 7;
3747				} else if (rs_type ==
3748					 CS_RAIDSET_PERSONALITY_RAID1){
3749					max_active_luns = 14;
3750				} else {
3751					/* XXX KDM now what?? */
3752				}
3753			} else {
3754				if (rs_type ==
3755				     CS_RAIDSET_PERSONALITY_RAID5) {
3756					max_active_luns = 8;
3757				} else if (rs_type ==
3758					 CS_RAIDSET_PERSONALITY_RAID1){
3759					max_active_luns = 16;
3760				} else {
3761					/* XXX KDM now what?? */
3762				}
3763			}
3764		} else {
3765			/* 50% power */
3766			if (aor_present == CS_TRUE) {
3767				if (rs_type ==
3768				     CS_RAIDSET_PERSONALITY_RAID5) {
3769					max_active_luns = 14;
3770				} else if (rs_type ==
3771					 CS_RAIDSET_PERSONALITY_RAID1){
3772					/*
3773					 * We're assuming here that disk
3774					 * caching is enabled, and so we're
3775					 * able to power up half of each
3776					 * LUN, and cache all writes.
3777					 */
3778					max_active_luns = num_luns;
3779				} else {
3780					/* XXX KDM now what?? */
3781				}
3782			} else {
3783				if (rs_type ==
3784				     CS_RAIDSET_PERSONALITY_RAID5) {
3785					max_active_luns = 15;
3786				} else if (rs_type ==
3787					 CS_RAIDSET_PERSONALITY_RAID1){
3788					max_active_luns = 30;
3789				} else {
3790					/* XXX KDM now what?? */
3791				}
3792			}
3793		}
3794		break;
3795	default:
3796		/*
3797		 * In this case, we have an unknown configuration, so we
3798		 * just use the default from above.
3799		 */
3800		break;
3801	}
3802
3803	page->max_active_luns = max_active_luns;
3804#if 0
3805	printk("%s: total_luns = %d, max_active_luns = %d\n", __func__,
3806	       page->total_luns, page->max_active_luns);
3807#endif
3808}
3809#endif /* NEEDTOPORT */
3810
3811/*
3812 * This routine could be used in the future to load default and/or saved
3813 * mode page parameters for a particuar lun.
3814 */
3815static int
3816ctl_init_page_index(struct ctl_lun *lun)
3817{
3818	int i;
3819	struct ctl_page_index *page_index;
3820	struct ctl_softc *softc;
3821
3822	memcpy(&lun->mode_pages.index, page_index_template,
3823	       sizeof(page_index_template));
3824
3825	softc = lun->ctl_softc;
3826
3827	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
3828
3829		page_index = &lun->mode_pages.index[i];
3830		/*
3831		 * If this is a disk-only mode page, there's no point in
3832		 * setting it up.  For some pages, we have to have some
3833		 * basic information about the disk in order to calculate the
3834		 * mode page data.
3835		 */
3836		if ((lun->be_lun->lun_type != T_DIRECT)
3837		 && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
3838			continue;
3839
3840		switch (page_index->page_code & SMPH_PC_MASK) {
3841		case SMS_FORMAT_DEVICE_PAGE: {
3842			struct scsi_format_page *format_page;
3843
3844			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3845				panic("subpage is incorrect!");
3846
3847			/*
3848			 * Sectors per track are set above.  Bytes per
3849			 * sector need to be set here on a per-LUN basis.
3850			 */
3851			memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
3852			       &format_page_default,
3853			       sizeof(format_page_default));
3854			memcpy(&lun->mode_pages.format_page[
3855			       CTL_PAGE_CHANGEABLE], &format_page_changeable,
3856			       sizeof(format_page_changeable));
3857			memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
3858			       &format_page_default,
3859			       sizeof(format_page_default));
3860			memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
3861			       &format_page_default,
3862			       sizeof(format_page_default));
3863
3864			format_page = &lun->mode_pages.format_page[
3865				CTL_PAGE_CURRENT];
3866			scsi_ulto2b(lun->be_lun->blocksize,
3867				    format_page->bytes_per_sector);
3868
3869			format_page = &lun->mode_pages.format_page[
3870				CTL_PAGE_DEFAULT];
3871			scsi_ulto2b(lun->be_lun->blocksize,
3872				    format_page->bytes_per_sector);
3873
3874			format_page = &lun->mode_pages.format_page[
3875				CTL_PAGE_SAVED];
3876			scsi_ulto2b(lun->be_lun->blocksize,
3877				    format_page->bytes_per_sector);
3878
3879			page_index->page_data =
3880				(uint8_t *)lun->mode_pages.format_page;
3881			break;
3882		}
3883		case SMS_RIGID_DISK_PAGE: {
3884			struct scsi_rigid_disk_page *rigid_disk_page;
3885			uint32_t sectors_per_cylinder;
3886			uint64_t cylinders;
3887#ifndef	__XSCALE__
3888			int shift;
3889#endif /* !__XSCALE__ */
3890
3891			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3892				panic("invalid subpage value %d",
3893				      page_index->subpage);
3894
3895			/*
3896			 * Rotation rate and sectors per track are set
3897			 * above.  We calculate the cylinders here based on
3898			 * capacity.  Due to the number of heads and
3899			 * sectors per track we're using, smaller arrays
3900			 * may turn out to have 0 cylinders.  Linux and
3901			 * FreeBSD don't pay attention to these mode pages
3902			 * to figure out capacity, but Solaris does.  It
3903			 * seems to deal with 0 cylinders just fine, and
3904			 * works out a fake geometry based on the capacity.
3905			 */
3906			memcpy(&lun->mode_pages.rigid_disk_page[
3907			       CTL_PAGE_CURRENT], &rigid_disk_page_default,
3908			       sizeof(rigid_disk_page_default));
3909			memcpy(&lun->mode_pages.rigid_disk_page[
3910			       CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
3911			       sizeof(rigid_disk_page_changeable));
3912			memcpy(&lun->mode_pages.rigid_disk_page[
3913			       CTL_PAGE_DEFAULT], &rigid_disk_page_default,
3914			       sizeof(rigid_disk_page_default));
3915			memcpy(&lun->mode_pages.rigid_disk_page[
3916			       CTL_PAGE_SAVED], &rigid_disk_page_default,
3917			       sizeof(rigid_disk_page_default));
3918
3919			sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
3920				CTL_DEFAULT_HEADS;
3921
3922			/*
3923			 * The divide method here will be more accurate,
3924			 * probably, but results in floating point being
3925			 * used in the kernel on i386 (__udivdi3()).  On the
3926			 * XScale, though, __udivdi3() is implemented in
3927			 * software.
3928			 *
3929			 * The shift method for cylinder calculation is
3930			 * accurate if sectors_per_cylinder is a power of
3931			 * 2.  Otherwise it might be slightly off -- you
3932			 * might have a bit of a truncation problem.
3933			 */
3934#ifdef	__XSCALE__
3935			cylinders = (lun->be_lun->maxlba + 1) /
3936				sectors_per_cylinder;
3937#else
3938			for (shift = 31; shift > 0; shift--) {
3939				if (sectors_per_cylinder & (1 << shift))
3940					break;
3941			}
3942			cylinders = (lun->be_lun->maxlba + 1) >> shift;
3943#endif
3944
3945			/*
3946			 * We've basically got 3 bytes, or 24 bits for the
3947			 * cylinder size in the mode page.  If we're over,
3948			 * just round down to 2^24.
3949			 */
3950			if (cylinders > 0xffffff)
3951				cylinders = 0xffffff;
3952
3953			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
3954				CTL_PAGE_CURRENT];
3955			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
3956
3957			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
3958				CTL_PAGE_DEFAULT];
3959			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
3960
3961			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
3962				CTL_PAGE_SAVED];
3963			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
3964
3965			page_index->page_data =
3966				(uint8_t *)lun->mode_pages.rigid_disk_page;
3967			break;
3968		}
3969		case SMS_CACHING_PAGE: {
3970
3971			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3972				panic("invalid subpage value %d",
3973				      page_index->subpage);
3974			/*
3975			 * Defaults should be okay here, no calculations
3976			 * needed.
3977			 */
3978			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
3979			       &caching_page_default,
3980			       sizeof(caching_page_default));
3981			memcpy(&lun->mode_pages.caching_page[
3982			       CTL_PAGE_CHANGEABLE], &caching_page_changeable,
3983			       sizeof(caching_page_changeable));
3984			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
3985			       &caching_page_default,
3986			       sizeof(caching_page_default));
3987			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
3988			       &caching_page_default,
3989			       sizeof(caching_page_default));
3990			page_index->page_data =
3991				(uint8_t *)lun->mode_pages.caching_page;
3992			break;
3993		}
3994		case SMS_CONTROL_MODE_PAGE: {
3995
3996			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3997				panic("invalid subpage value %d",
3998				      page_index->subpage);
3999
4000			/*
4001			 * Defaults should be okay here, no calculations
4002			 * needed.
4003			 */
4004			memcpy(&lun->mode_pages.control_page[CTL_PAGE_CURRENT],
4005			       &control_page_default,
4006			       sizeof(control_page_default));
4007			memcpy(&lun->mode_pages.control_page[
4008			       CTL_PAGE_CHANGEABLE], &control_page_changeable,
4009			       sizeof(control_page_changeable));
4010			memcpy(&lun->mode_pages.control_page[CTL_PAGE_DEFAULT],
4011			       &control_page_default,
4012			       sizeof(control_page_default));
4013			memcpy(&lun->mode_pages.control_page[CTL_PAGE_SAVED],
4014			       &control_page_default,
4015			       sizeof(control_page_default));
4016			page_index->page_data =
4017				(uint8_t *)lun->mode_pages.control_page;
4018			break;
4019
4020		}
4021		case SMS_VENDOR_SPECIFIC_PAGE:{
4022			switch (page_index->subpage) {
4023			case PWR_SUBPAGE_CODE: {
4024				struct copan_power_subpage *current_page,
4025							   *saved_page;
4026
4027				memcpy(&lun->mode_pages.power_subpage[
4028				       CTL_PAGE_CURRENT],
4029				       &power_page_default,
4030				       sizeof(power_page_default));
4031				memcpy(&lun->mode_pages.power_subpage[
4032				       CTL_PAGE_CHANGEABLE],
4033				       &power_page_changeable,
4034				       sizeof(power_page_changeable));
4035				memcpy(&lun->mode_pages.power_subpage[
4036				       CTL_PAGE_DEFAULT],
4037				       &power_page_default,
4038				       sizeof(power_page_default));
4039				memcpy(&lun->mode_pages.power_subpage[
4040				       CTL_PAGE_SAVED],
4041				       &power_page_default,
4042				       sizeof(power_page_default));
4043				page_index->page_data =
4044				    (uint8_t *)lun->mode_pages.power_subpage;
4045
4046				current_page = (struct copan_power_subpage *)
4047					(page_index->page_data +
4048					 (page_index->page_len *
4049					  CTL_PAGE_CURRENT));
4050			        saved_page = (struct copan_power_subpage *)
4051				        (page_index->page_data +
4052					 (page_index->page_len *
4053					  CTL_PAGE_SAVED));
4054				break;
4055			}
4056			case APS_SUBPAGE_CODE: {
4057				struct copan_aps_subpage *current_page,
4058							 *saved_page;
4059
4060				// This gets set multiple times but
4061				// it should always be the same. It's
4062				// only done during init so who cares.
4063				index_to_aps_page = i;
4064
4065				memcpy(&lun->mode_pages.aps_subpage[
4066				       CTL_PAGE_CURRENT],
4067				       &aps_page_default,
4068				       sizeof(aps_page_default));
4069				memcpy(&lun->mode_pages.aps_subpage[
4070				       CTL_PAGE_CHANGEABLE],
4071				       &aps_page_changeable,
4072				       sizeof(aps_page_changeable));
4073				memcpy(&lun->mode_pages.aps_subpage[
4074				       CTL_PAGE_DEFAULT],
4075				       &aps_page_default,
4076				       sizeof(aps_page_default));
4077				memcpy(&lun->mode_pages.aps_subpage[
4078				       CTL_PAGE_SAVED],
4079				       &aps_page_default,
4080				       sizeof(aps_page_default));
4081				page_index->page_data =
4082					(uint8_t *)lun->mode_pages.aps_subpage;
4083
4084				current_page = (struct copan_aps_subpage *)
4085					(page_index->page_data +
4086					 (page_index->page_len *
4087					  CTL_PAGE_CURRENT));
4088				saved_page = (struct copan_aps_subpage *)
4089					(page_index->page_data +
4090					 (page_index->page_len *
4091					  CTL_PAGE_SAVED));
4092				break;
4093			}
4094			case DBGCNF_SUBPAGE_CODE: {
4095				struct copan_debugconf_subpage *current_page,
4096							       *saved_page;
4097
4098				memcpy(&lun->mode_pages.debugconf_subpage[
4099				       CTL_PAGE_CURRENT],
4100				       &debugconf_page_default,
4101				       sizeof(debugconf_page_default));
4102				memcpy(&lun->mode_pages.debugconf_subpage[
4103				       CTL_PAGE_CHANGEABLE],
4104				       &debugconf_page_changeable,
4105				       sizeof(debugconf_page_changeable));
4106				memcpy(&lun->mode_pages.debugconf_subpage[
4107				       CTL_PAGE_DEFAULT],
4108				       &debugconf_page_default,
4109				       sizeof(debugconf_page_default));
4110				memcpy(&lun->mode_pages.debugconf_subpage[
4111				       CTL_PAGE_SAVED],
4112				       &debugconf_page_default,
4113				       sizeof(debugconf_page_default));
4114				page_index->page_data =
4115					(uint8_t *)lun->mode_pages.debugconf_subpage;
4116
4117				current_page = (struct copan_debugconf_subpage *)
4118					(page_index->page_data +
4119					 (page_index->page_len *
4120					  CTL_PAGE_CURRENT));
4121				saved_page = (struct copan_debugconf_subpage *)
4122					(page_index->page_data +
4123					 (page_index->page_len *
4124					  CTL_PAGE_SAVED));
4125				break;
4126			}
4127			default:
4128				panic("invalid subpage value %d",
4129				      page_index->subpage);
4130				break;
4131			}
4132   			break;
4133		}
4134		default:
4135			panic("invalid page value %d",
4136			      page_index->page_code & SMPH_PC_MASK);
4137			break;
4138    	}
4139	}
4140
4141	return (CTL_RETVAL_COMPLETE);
4142}
4143
4144/*
4145 * LUN allocation.
4146 *
4147 * Requirements:
4148 * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4149 *   wants us to allocate the LUN and he can block.
4150 * - ctl_softc is always set
4151 * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4152 *
4153 * Returns 0 for success, non-zero (errno) for failure.
4154 */
4155static int
4156ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4157	      struct ctl_be_lun *const be_lun, struct ctl_id target_id)
4158{
4159	struct ctl_lun *nlun, *lun;
4160	struct ctl_frontend *fe;
4161	int lun_number, i, lun_malloced;
4162
4163	if (be_lun == NULL)
4164		return (EINVAL);
4165
4166	/*
4167	 * We currently only support Direct Access or Processor LUN types.
4168	 */
4169	switch (be_lun->lun_type) {
4170	case T_DIRECT:
4171		break;
4172	case T_PROCESSOR:
4173		break;
4174	case T_SEQUENTIAL:
4175	case T_CHANGER:
4176	default:
4177		be_lun->lun_config_status(be_lun->be_lun,
4178					  CTL_LUN_CONFIG_FAILURE);
4179		break;
4180	}
4181	if (ctl_lun == NULL) {
4182		lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4183		lun_malloced = 1;
4184	} else {
4185		lun_malloced = 0;
4186		lun = ctl_lun;
4187	}
4188
4189	memset(lun, 0, sizeof(*lun));
4190	if (lun_malloced)
4191		lun->flags = CTL_LUN_MALLOCED;
4192
4193	mtx_lock(&ctl_softc->ctl_lock);
4194	/*
4195	 * See if the caller requested a particular LUN number.  If so, see
4196	 * if it is available.  Otherwise, allocate the first available LUN.
4197	 */
4198	if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4199		if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4200		 || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4201			mtx_unlock(&ctl_softc->ctl_lock);
4202			if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4203				printf("ctl: requested LUN ID %d is higher "
4204				       "than CTL_MAX_LUNS - 1 (%d)\n",
4205				       be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4206			} else {
4207				/*
4208				 * XXX KDM return an error, or just assign
4209				 * another LUN ID in this case??
4210				 */
4211				printf("ctl: requested LUN ID %d is already "
4212				       "in use\n", be_lun->req_lun_id);
4213			}
4214			if (lun->flags & CTL_LUN_MALLOCED)
4215				free(lun, M_CTL);
4216			be_lun->lun_config_status(be_lun->be_lun,
4217						  CTL_LUN_CONFIG_FAILURE);
4218			return (ENOSPC);
4219		}
4220		lun_number = be_lun->req_lun_id;
4221	} else {
4222		lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, CTL_MAX_LUNS);
4223		if (lun_number == -1) {
4224			mtx_unlock(&ctl_softc->ctl_lock);
4225			printf("ctl: can't allocate LUN on target %ju, out of "
4226			       "LUNs\n", (uintmax_t)target_id.id);
4227			if (lun->flags & CTL_LUN_MALLOCED)
4228				free(lun, M_CTL);
4229			be_lun->lun_config_status(be_lun->be_lun,
4230						  CTL_LUN_CONFIG_FAILURE);
4231			return (ENOSPC);
4232		}
4233	}
4234	ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4235
4236	mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4237	lun->target = target_id;
4238	lun->lun = lun_number;
4239	lun->be_lun = be_lun;
4240	/*
4241	 * The processor LUN is always enabled.  Disk LUNs come on line
4242	 * disabled, and must be enabled by the backend.
4243	 */
4244	lun->flags |= CTL_LUN_DISABLED;
4245	lun->backend = be_lun->be;
4246	be_lun->ctl_lun = lun;
4247	be_lun->lun_id = lun_number;
4248	atomic_add_int(&be_lun->be->num_luns, 1);
4249	if (be_lun->flags & CTL_LUN_FLAG_POWERED_OFF)
4250		lun->flags |= CTL_LUN_STOPPED;
4251
4252	if (be_lun->flags & CTL_LUN_FLAG_INOPERABLE)
4253		lun->flags |= CTL_LUN_INOPERABLE;
4254
4255	if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4256		lun->flags |= CTL_LUN_PRIMARY_SC;
4257
4258	lun->ctl_softc = ctl_softc;
4259	TAILQ_INIT(&lun->ooa_queue);
4260	TAILQ_INIT(&lun->blocked_queue);
4261	STAILQ_INIT(&lun->error_list);
4262
4263	/*
4264	 * Initialize the mode page index.
4265	 */
4266	ctl_init_page_index(lun);
4267
4268	/*
4269	 * Set the poweron UA for all initiators on this LUN only.
4270	 */
4271	for (i = 0; i < CTL_MAX_INITIATORS; i++)
4272		lun->pending_sense[i].ua_pending = CTL_UA_POWERON;
4273
4274	/*
4275	 * Now, before we insert this lun on the lun list, set the lun
4276	 * inventory changed UA for all other luns.
4277	 */
4278	STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4279		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
4280			nlun->pending_sense[i].ua_pending |= CTL_UA_LUN_CHANGE;
4281		}
4282	}
4283
4284	STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4285
4286	ctl_softc->ctl_luns[lun_number] = lun;
4287
4288	ctl_softc->num_luns++;
4289
4290	/* Setup statistics gathering */
4291	lun->stats.device_type = be_lun->lun_type;
4292	lun->stats.lun_number = lun_number;
4293	if (lun->stats.device_type == T_DIRECT)
4294		lun->stats.blocksize = be_lun->blocksize;
4295	else
4296		lun->stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4297	for (i = 0;i < CTL_MAX_PORTS;i++)
4298		lun->stats.ports[i].targ_port = i;
4299
4300	mtx_unlock(&ctl_softc->ctl_lock);
4301
4302	lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4303
4304	/*
4305	 * Run through each registered FETD and bring it online if it isn't
4306	 * already.  Enable the target ID if it hasn't been enabled, and
4307	 * enable this particular LUN.
4308	 */
4309	STAILQ_FOREACH(fe, &ctl_softc->fe_list, links) {
4310		int retval;
4311
4312		/*
4313		 * XXX KDM this only works for ONE TARGET ID.  We'll need
4314		 * to do things differently if we go to a multiple target
4315		 * ID scheme.
4316		 */
4317		if ((fe->status & CTL_PORT_STATUS_TARG_ONLINE) == 0) {
4318
4319			retval = fe->targ_enable(fe->targ_lun_arg, target_id);
4320			if (retval != 0) {
4321				printf("ctl_alloc_lun: FETD %s port %d "
4322				       "returned error %d for targ_enable on "
4323				       "target %ju\n", fe->port_name,
4324				       fe->targ_port, retval,
4325				       (uintmax_t)target_id.id);
4326			} else
4327				fe->status |= CTL_PORT_STATUS_TARG_ONLINE;
4328		}
4329
4330		retval = fe->lun_enable(fe->targ_lun_arg, target_id,lun_number);
4331		if (retval != 0) {
4332			printf("ctl_alloc_lun: FETD %s port %d returned error "
4333			       "%d for lun_enable on target %ju lun %d\n",
4334			       fe->port_name, fe->targ_port, retval,
4335			       (uintmax_t)target_id.id, lun_number);
4336		} else
4337			fe->status |= CTL_PORT_STATUS_LUN_ONLINE;
4338	}
4339	return (0);
4340}
4341
4342/*
4343 * Delete a LUN.
4344 * Assumptions:
4345 * - LUN has already been marked invalid and any pending I/O has been taken
4346 *   care of.
4347 */
4348static int
4349ctl_free_lun(struct ctl_lun *lun)
4350{
4351	struct ctl_softc *softc;
4352#if 0
4353	struct ctl_frontend *fe;
4354#endif
4355	struct ctl_lun *nlun;
4356	int i;
4357
4358	softc = lun->ctl_softc;
4359
4360	mtx_assert(&softc->ctl_lock, MA_OWNED);
4361
4362	STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4363
4364	ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4365
4366	softc->ctl_luns[lun->lun] = NULL;
4367
4368	if (!TAILQ_EMPTY(&lun->ooa_queue))
4369		panic("Freeing a LUN %p with outstanding I/O!!\n", lun);
4370
4371	softc->num_luns--;
4372
4373	/*
4374	 * XXX KDM this scheme only works for a single target/multiple LUN
4375	 * setup.  It needs to be revamped for a multiple target scheme.
4376	 *
4377	 * XXX KDM this results in fe->lun_disable() getting called twice,
4378	 * once when ctl_disable_lun() is called, and a second time here.
4379	 * We really need to re-think the LUN disable semantics.  There
4380	 * should probably be several steps/levels to LUN removal:
4381	 *  - disable
4382	 *  - invalidate
4383	 *  - free
4384 	 *
4385	 * Right now we only have a disable method when communicating to
4386	 * the front end ports, at least for individual LUNs.
4387	 */
4388#if 0
4389	STAILQ_FOREACH(fe, &softc->fe_list, links) {
4390		int retval;
4391
4392		retval = fe->lun_disable(fe->targ_lun_arg, lun->target,
4393					 lun->lun);
4394		if (retval != 0) {
4395			printf("ctl_free_lun: FETD %s port %d returned error "
4396			       "%d for lun_disable on target %ju lun %jd\n",
4397			       fe->port_name, fe->targ_port, retval,
4398			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4399		}
4400
4401		if (STAILQ_FIRST(&softc->lun_list) == NULL) {
4402			fe->status &= ~CTL_PORT_STATUS_LUN_ONLINE;
4403
4404			retval = fe->targ_disable(fe->targ_lun_arg,lun->target);
4405			if (retval != 0) {
4406				printf("ctl_free_lun: FETD %s port %d "
4407				       "returned error %d for targ_disable on "
4408				       "target %ju\n", fe->port_name,
4409				       fe->targ_port, retval,
4410				       (uintmax_t)lun->target.id);
4411			} else
4412				fe->status &= ~CTL_PORT_STATUS_TARG_ONLINE;
4413
4414			if ((fe->status & CTL_PORT_STATUS_TARG_ONLINE) != 0)
4415				continue;
4416
4417#if 0
4418			fe->port_offline(fe->onoff_arg);
4419			fe->status &= ~CTL_PORT_STATUS_ONLINE;
4420#endif
4421		}
4422	}
4423#endif
4424
4425	/*
4426	 * Tell the backend to free resources, if this LUN has a backend.
4427	 */
4428	atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4429	lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4430
4431	mtx_destroy(&lun->lun_lock);
4432	if (lun->flags & CTL_LUN_MALLOCED)
4433		free(lun, M_CTL);
4434
4435	STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4436		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
4437			nlun->pending_sense[i].ua_pending |= CTL_UA_LUN_CHANGE;
4438		}
4439	}
4440
4441	return (0);
4442}
4443
4444static void
4445ctl_create_lun(struct ctl_be_lun *be_lun)
4446{
4447	struct ctl_softc *ctl_softc;
4448
4449	ctl_softc = control_softc;
4450
4451	/*
4452	 * ctl_alloc_lun() should handle all potential failure cases.
4453	 */
4454	ctl_alloc_lun(ctl_softc, NULL, be_lun, ctl_softc->target);
4455}
4456
4457int
4458ctl_add_lun(struct ctl_be_lun *be_lun)
4459{
4460	struct ctl_softc *ctl_softc = control_softc;
4461
4462	mtx_lock(&ctl_softc->ctl_lock);
4463	STAILQ_INSERT_TAIL(&ctl_softc->pending_lun_queue, be_lun, links);
4464	mtx_unlock(&ctl_softc->ctl_lock);
4465	wakeup(&ctl_softc->pending_lun_queue);
4466
4467	return (0);
4468}
4469
4470int
4471ctl_enable_lun(struct ctl_be_lun *be_lun)
4472{
4473	struct ctl_softc *ctl_softc;
4474	struct ctl_frontend *fe, *nfe;
4475	struct ctl_lun *lun;
4476	int retval;
4477
4478	ctl_softc = control_softc;
4479
4480	lun = (struct ctl_lun *)be_lun->ctl_lun;
4481
4482	mtx_lock(&ctl_softc->ctl_lock);
4483	mtx_lock(&lun->lun_lock);
4484	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4485		/*
4486		 * eh?  Why did we get called if the LUN is already
4487		 * enabled?
4488		 */
4489		mtx_unlock(&lun->lun_lock);
4490		mtx_unlock(&ctl_softc->ctl_lock);
4491		return (0);
4492	}
4493	lun->flags &= ~CTL_LUN_DISABLED;
4494	mtx_unlock(&lun->lun_lock);
4495
4496	for (fe = STAILQ_FIRST(&ctl_softc->fe_list); fe != NULL; fe = nfe) {
4497		nfe = STAILQ_NEXT(fe, links);
4498
4499		/*
4500		 * Drop the lock while we call the FETD's enable routine.
4501		 * This can lead to a callback into CTL (at least in the
4502		 * case of the internal initiator frontend.
4503		 */
4504		mtx_unlock(&ctl_softc->ctl_lock);
4505		retval = fe->lun_enable(fe->targ_lun_arg, lun->target,lun->lun);
4506		mtx_lock(&ctl_softc->ctl_lock);
4507		if (retval != 0) {
4508			printf("%s: FETD %s port %d returned error "
4509			       "%d for lun_enable on target %ju lun %jd\n",
4510			       __func__, fe->port_name, fe->targ_port, retval,
4511			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4512		}
4513#if 0
4514		 else {
4515            /* NOTE:  TODO:  why does lun enable affect port status? */
4516			fe->status |= CTL_PORT_STATUS_LUN_ONLINE;
4517		}
4518#endif
4519	}
4520
4521	mtx_unlock(&ctl_softc->ctl_lock);
4522
4523	return (0);
4524}
4525
4526int
4527ctl_disable_lun(struct ctl_be_lun *be_lun)
4528{
4529	struct ctl_softc *ctl_softc;
4530	struct ctl_frontend *fe;
4531	struct ctl_lun *lun;
4532	int retval;
4533
4534	ctl_softc = control_softc;
4535
4536	lun = (struct ctl_lun *)be_lun->ctl_lun;
4537
4538	mtx_lock(&ctl_softc->ctl_lock);
4539	mtx_lock(&lun->lun_lock);
4540	if (lun->flags & CTL_LUN_DISABLED) {
4541		mtx_unlock(&lun->lun_lock);
4542		mtx_unlock(&ctl_softc->ctl_lock);
4543		return (0);
4544	}
4545	lun->flags |= CTL_LUN_DISABLED;
4546	mtx_unlock(&lun->lun_lock);
4547
4548	STAILQ_FOREACH(fe, &ctl_softc->fe_list, links) {
4549		mtx_unlock(&ctl_softc->ctl_lock);
4550		/*
4551		 * Drop the lock before we call the frontend's disable
4552		 * routine, to avoid lock order reversals.
4553		 *
4554		 * XXX KDM what happens if the frontend list changes while
4555		 * we're traversing it?  It's unlikely, but should be handled.
4556		 */
4557		retval = fe->lun_disable(fe->targ_lun_arg, lun->target,
4558					 lun->lun);
4559		mtx_lock(&ctl_softc->ctl_lock);
4560		if (retval != 0) {
4561			printf("ctl_alloc_lun: FETD %s port %d returned error "
4562			       "%d for lun_disable on target %ju lun %jd\n",
4563			       fe->port_name, fe->targ_port, retval,
4564			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4565		}
4566	}
4567
4568	mtx_unlock(&ctl_softc->ctl_lock);
4569
4570	return (0);
4571}
4572
4573int
4574ctl_start_lun(struct ctl_be_lun *be_lun)
4575{
4576	struct ctl_softc *ctl_softc;
4577	struct ctl_lun *lun;
4578
4579	ctl_softc = control_softc;
4580
4581	lun = (struct ctl_lun *)be_lun->ctl_lun;
4582
4583	mtx_lock(&lun->lun_lock);
4584	lun->flags &= ~CTL_LUN_STOPPED;
4585	mtx_unlock(&lun->lun_lock);
4586
4587	return (0);
4588}
4589
4590int
4591ctl_stop_lun(struct ctl_be_lun *be_lun)
4592{
4593	struct ctl_softc *ctl_softc;
4594	struct ctl_lun *lun;
4595
4596	ctl_softc = control_softc;
4597
4598	lun = (struct ctl_lun *)be_lun->ctl_lun;
4599
4600	mtx_lock(&lun->lun_lock);
4601	lun->flags |= CTL_LUN_STOPPED;
4602	mtx_unlock(&lun->lun_lock);
4603
4604	return (0);
4605}
4606
4607int
4608ctl_lun_offline(struct ctl_be_lun *be_lun)
4609{
4610	struct ctl_softc *ctl_softc;
4611	struct ctl_lun *lun;
4612
4613	ctl_softc = control_softc;
4614
4615	lun = (struct ctl_lun *)be_lun->ctl_lun;
4616
4617	mtx_lock(&lun->lun_lock);
4618	lun->flags |= CTL_LUN_OFFLINE;
4619	mtx_unlock(&lun->lun_lock);
4620
4621	return (0);
4622}
4623
4624int
4625ctl_lun_online(struct ctl_be_lun *be_lun)
4626{
4627	struct ctl_softc *ctl_softc;
4628	struct ctl_lun *lun;
4629
4630	ctl_softc = control_softc;
4631
4632	lun = (struct ctl_lun *)be_lun->ctl_lun;
4633
4634	mtx_lock(&lun->lun_lock);
4635	lun->flags &= ~CTL_LUN_OFFLINE;
4636	mtx_unlock(&lun->lun_lock);
4637
4638	return (0);
4639}
4640
4641int
4642ctl_invalidate_lun(struct ctl_be_lun *be_lun)
4643{
4644	struct ctl_softc *ctl_softc;
4645	struct ctl_lun *lun;
4646
4647	ctl_softc = control_softc;
4648
4649	lun = (struct ctl_lun *)be_lun->ctl_lun;
4650
4651	mtx_lock(&lun->lun_lock);
4652
4653	/*
4654	 * The LUN needs to be disabled before it can be marked invalid.
4655	 */
4656	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4657		mtx_unlock(&lun->lun_lock);
4658		return (-1);
4659	}
4660	/*
4661	 * Mark the LUN invalid.
4662	 */
4663	lun->flags |= CTL_LUN_INVALID;
4664
4665	/*
4666	 * If there is nothing in the OOA queue, go ahead and free the LUN.
4667	 * If we have something in the OOA queue, we'll free it when the
4668	 * last I/O completes.
4669	 */
4670	if (TAILQ_EMPTY(&lun->ooa_queue)) {
4671		mtx_unlock(&lun->lun_lock);
4672		mtx_lock(&ctl_softc->ctl_lock);
4673		ctl_free_lun(lun);
4674		mtx_unlock(&ctl_softc->ctl_lock);
4675	} else
4676		mtx_unlock(&lun->lun_lock);
4677
4678	return (0);
4679}
4680
4681int
4682ctl_lun_inoperable(struct ctl_be_lun *be_lun)
4683{
4684	struct ctl_softc *ctl_softc;
4685	struct ctl_lun *lun;
4686
4687	ctl_softc = control_softc;
4688	lun = (struct ctl_lun *)be_lun->ctl_lun;
4689
4690	mtx_lock(&lun->lun_lock);
4691	lun->flags |= CTL_LUN_INOPERABLE;
4692	mtx_unlock(&lun->lun_lock);
4693
4694	return (0);
4695}
4696
4697int
4698ctl_lun_operable(struct ctl_be_lun *be_lun)
4699{
4700	struct ctl_softc *ctl_softc;
4701	struct ctl_lun *lun;
4702
4703	ctl_softc = control_softc;
4704	lun = (struct ctl_lun *)be_lun->ctl_lun;
4705
4706	mtx_lock(&lun->lun_lock);
4707	lun->flags &= ~CTL_LUN_INOPERABLE;
4708	mtx_unlock(&lun->lun_lock);
4709
4710	return (0);
4711}
4712
4713int
4714ctl_lun_power_lock(struct ctl_be_lun *be_lun, struct ctl_nexus *nexus,
4715		   int lock)
4716{
4717	struct ctl_softc *softc;
4718	struct ctl_lun *lun;
4719	struct copan_aps_subpage *current_sp;
4720	struct ctl_page_index *page_index;
4721	int i;
4722
4723	softc = control_softc;
4724
4725	mtx_lock(&softc->ctl_lock);
4726
4727	lun = (struct ctl_lun *)be_lun->ctl_lun;
4728	mtx_lock(&lun->lun_lock);
4729
4730	page_index = NULL;
4731	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
4732		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
4733		     APS_PAGE_CODE)
4734			continue;
4735
4736		if (lun->mode_pages.index[i].subpage != APS_SUBPAGE_CODE)
4737			continue;
4738		page_index = &lun->mode_pages.index[i];
4739	}
4740
4741	if (page_index == NULL) {
4742		mtx_unlock(&lun->lun_lock);
4743		mtx_unlock(&softc->ctl_lock);
4744		printf("%s: APS subpage not found for lun %ju!\n", __func__,
4745		       (uintmax_t)lun->lun);
4746		return (1);
4747	}
4748#if 0
4749	if ((softc->aps_locked_lun != 0)
4750	 && (softc->aps_locked_lun != lun->lun)) {
4751		printf("%s: attempt to lock LUN %llu when %llu is already "
4752		       "locked\n");
4753		mtx_unlock(&lun->lun_lock);
4754		mtx_unlock(&softc->ctl_lock);
4755		return (1);
4756	}
4757#endif
4758
4759	current_sp = (struct copan_aps_subpage *)(page_index->page_data +
4760		(page_index->page_len * CTL_PAGE_CURRENT));
4761
4762	if (lock != 0) {
4763		current_sp->lock_active = APS_LOCK_ACTIVE;
4764		softc->aps_locked_lun = lun->lun;
4765	} else {
4766		current_sp->lock_active = 0;
4767		softc->aps_locked_lun = 0;
4768	}
4769
4770
4771	/*
4772	 * If we're in HA mode, try to send the lock message to the other
4773	 * side.
4774	 */
4775	if (ctl_is_single == 0) {
4776		int isc_retval;
4777		union ctl_ha_msg lock_msg;
4778
4779		lock_msg.hdr.nexus = *nexus;
4780		lock_msg.hdr.msg_type = CTL_MSG_APS_LOCK;
4781		if (lock != 0)
4782			lock_msg.aps.lock_flag = 1;
4783		else
4784			lock_msg.aps.lock_flag = 0;
4785		isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &lock_msg,
4786					 sizeof(lock_msg), 0);
4787		if (isc_retval > CTL_HA_STATUS_SUCCESS) {
4788			printf("%s: APS (lock=%d) error returned from "
4789			       "ctl_ha_msg_send: %d\n", __func__, lock, isc_retval);
4790			mtx_unlock(&lun->lun_lock);
4791			mtx_unlock(&softc->ctl_lock);
4792			return (1);
4793		}
4794	}
4795
4796	mtx_unlock(&lun->lun_lock);
4797	mtx_unlock(&softc->ctl_lock);
4798
4799	return (0);
4800}
4801
4802void
4803ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
4804{
4805	struct ctl_lun *lun;
4806	struct ctl_softc *softc;
4807	int i;
4808
4809	softc = control_softc;
4810
4811	lun = (struct ctl_lun *)be_lun->ctl_lun;
4812
4813	mtx_lock(&lun->lun_lock);
4814
4815	for (i = 0; i < CTL_MAX_INITIATORS; i++)
4816		lun->pending_sense[i].ua_pending |= CTL_UA_CAPACITY_CHANGED;
4817
4818	mtx_unlock(&lun->lun_lock);
4819}
4820
4821/*
4822 * Backend "memory move is complete" callback for requests that never
4823 * make it down to say RAIDCore's configuration code.
4824 */
4825int
4826ctl_config_move_done(union ctl_io *io)
4827{
4828	int retval;
4829
4830	retval = CTL_RETVAL_COMPLETE;
4831
4832
4833	CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
4834	/*
4835	 * XXX KDM this shouldn't happen, but what if it does?
4836	 */
4837	if (io->io_hdr.io_type != CTL_IO_SCSI)
4838		panic("I/O type isn't CTL_IO_SCSI!");
4839
4840	if ((io->io_hdr.port_status == 0)
4841	 && ((io->io_hdr.flags & CTL_FLAG_ABORT) == 0)
4842	 && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE))
4843		io->io_hdr.status = CTL_SUCCESS;
4844	else if ((io->io_hdr.port_status != 0)
4845	      && ((io->io_hdr.flags & CTL_FLAG_ABORT) == 0)
4846	      && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE)){
4847		/*
4848		 * For hardware error sense keys, the sense key
4849		 * specific value is defined to be a retry count,
4850		 * but we use it to pass back an internal FETD
4851		 * error code.  XXX KDM  Hopefully the FETD is only
4852		 * using 16 bits for an error code, since that's
4853		 * all the space we have in the sks field.
4854		 */
4855		ctl_set_internal_failure(&io->scsiio,
4856					 /*sks_valid*/ 1,
4857					 /*retry_count*/
4858					 io->io_hdr.port_status);
4859		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
4860			free(io->scsiio.kern_data_ptr, M_CTL);
4861		ctl_done(io);
4862		goto bailout;
4863	}
4864
4865	if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
4866	 || ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)
4867	 || ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
4868		/*
4869		 * XXX KDM just assuming a single pointer here, and not a
4870		 * S/G list.  If we start using S/G lists for config data,
4871		 * we'll need to know how to clean them up here as well.
4872		 */
4873		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
4874			free(io->scsiio.kern_data_ptr, M_CTL);
4875		/* Hopefully the user has already set the status... */
4876		ctl_done(io);
4877	} else {
4878		/*
4879		 * XXX KDM now we need to continue data movement.  Some
4880		 * options:
4881		 * - call ctl_scsiio() again?  We don't do this for data
4882		 *   writes, because for those at least we know ahead of
4883		 *   time where the write will go and how long it is.  For
4884		 *   config writes, though, that information is largely
4885		 *   contained within the write itself, thus we need to
4886		 *   parse out the data again.
4887		 *
4888		 * - Call some other function once the data is in?
4889		 */
4890
4891		/*
4892		 * XXX KDM call ctl_scsiio() again for now, and check flag
4893		 * bits to see whether we're allocated or not.
4894		 */
4895		retval = ctl_scsiio(&io->scsiio);
4896	}
4897bailout:
4898	return (retval);
4899}
4900
4901/*
4902 * This gets called by a backend driver when it is done with a
4903 * data_submit method.
4904 */
4905void
4906ctl_data_submit_done(union ctl_io *io)
4907{
4908	/*
4909	 * If the IO_CONT flag is set, we need to call the supplied
4910	 * function to continue processing the I/O, instead of completing
4911	 * the I/O just yet.
4912	 *
4913	 * If there is an error, though, we don't want to keep processing.
4914	 * Instead, just send status back to the initiator.
4915	 */
4916	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
4917	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
4918	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
4919	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
4920		io->scsiio.io_cont(io);
4921		return;
4922	}
4923	ctl_done(io);
4924}
4925
4926/*
4927 * This gets called by a backend driver when it is done with a
4928 * configuration write.
4929 */
4930void
4931ctl_config_write_done(union ctl_io *io)
4932{
4933	/*
4934	 * If the IO_CONT flag is set, we need to call the supplied
4935	 * function to continue processing the I/O, instead of completing
4936	 * the I/O just yet.
4937	 *
4938	 * If there is an error, though, we don't want to keep processing.
4939	 * Instead, just send status back to the initiator.
4940	 */
4941	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT)
4942	 && (((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE)
4943	  || ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS))) {
4944		io->scsiio.io_cont(io);
4945		return;
4946	}
4947	/*
4948	 * Since a configuration write can be done for commands that actually
4949	 * have data allocated, like write buffer, and commands that have
4950	 * no data, like start/stop unit, we need to check here.
4951	 */
4952	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT)
4953		free(io->scsiio.kern_data_ptr, M_CTL);
4954	ctl_done(io);
4955}
4956
4957/*
4958 * SCSI release command.
4959 */
4960int
4961ctl_scsi_release(struct ctl_scsiio *ctsio)
4962{
4963	int length, longid, thirdparty_id, resv_id;
4964	struct ctl_softc *ctl_softc;
4965	struct ctl_lun *lun;
4966
4967	length = 0;
4968	resv_id = 0;
4969
4970	CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
4971
4972	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
4973	ctl_softc = control_softc;
4974
4975	switch (ctsio->cdb[0]) {
4976	case RELEASE: {
4977		struct scsi_release *cdb;
4978
4979		cdb = (struct scsi_release *)ctsio->cdb;
4980		if ((cdb->byte2 & 0x1f) != 0) {
4981			ctl_set_invalid_field(ctsio,
4982					      /*sks_valid*/ 1,
4983					      /*command*/ 1,
4984					      /*field*/ 1,
4985					      /*bit_valid*/ 0,
4986					      /*bit*/ 0);
4987			ctl_done((union ctl_io *)ctsio);
4988			return (CTL_RETVAL_COMPLETE);
4989		}
4990		break;
4991	}
4992	case RELEASE_10: {
4993		struct scsi_release_10 *cdb;
4994
4995		cdb = (struct scsi_release_10 *)ctsio->cdb;
4996
4997		if ((cdb->byte2 & SR10_EXTENT) != 0) {
4998			ctl_set_invalid_field(ctsio,
4999					      /*sks_valid*/ 1,
5000					      /*command*/ 1,
5001					      /*field*/ 1,
5002					      /*bit_valid*/ 1,
5003					      /*bit*/ 0);
5004			ctl_done((union ctl_io *)ctsio);
5005			return (CTL_RETVAL_COMPLETE);
5006
5007		}
5008
5009		if ((cdb->byte2 & SR10_3RDPTY) != 0) {
5010			ctl_set_invalid_field(ctsio,
5011					      /*sks_valid*/ 1,
5012					      /*command*/ 1,
5013					      /*field*/ 1,
5014					      /*bit_valid*/ 1,
5015					      /*bit*/ 4);
5016			ctl_done((union ctl_io *)ctsio);
5017			return (CTL_RETVAL_COMPLETE);
5018		}
5019
5020		if (cdb->byte2 & SR10_LONGID)
5021			longid = 1;
5022		else
5023			thirdparty_id = cdb->thirdparty_id;
5024
5025		resv_id = cdb->resv_id;
5026		length = scsi_2btoul(cdb->length);
5027		break;
5028	}
5029	}
5030
5031
5032	/*
5033	 * XXX KDM right now, we only support LUN reservation.  We don't
5034	 * support 3rd party reservations, or extent reservations, which
5035	 * might actually need the parameter list.  If we've gotten this
5036	 * far, we've got a LUN reservation.  Anything else got kicked out
5037	 * above.  So, according to SPC, ignore the length.
5038	 */
5039	length = 0;
5040
5041	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5042	 && (length > 0)) {
5043		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5044		ctsio->kern_data_len = length;
5045		ctsio->kern_total_len = length;
5046		ctsio->kern_data_resid = 0;
5047		ctsio->kern_rel_offset = 0;
5048		ctsio->kern_sg_entries = 0;
5049		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5050		ctsio->be_move_done = ctl_config_move_done;
5051		ctl_datamove((union ctl_io *)ctsio);
5052
5053		return (CTL_RETVAL_COMPLETE);
5054	}
5055
5056	if (length > 0)
5057		thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5058
5059	mtx_lock(&lun->lun_lock);
5060
5061	/*
5062	 * According to SPC, it is not an error for an intiator to attempt
5063	 * to release a reservation on a LUN that isn't reserved, or that
5064	 * is reserved by another initiator.  The reservation can only be
5065	 * released, though, by the initiator who made it or by one of
5066	 * several reset type events.
5067	 */
5068	if (lun->flags & CTL_LUN_RESERVED) {
5069		if ((ctsio->io_hdr.nexus.initid.id == lun->rsv_nexus.initid.id)
5070		 && (ctsio->io_hdr.nexus.targ_port == lun->rsv_nexus.targ_port)
5071		 && (ctsio->io_hdr.nexus.targ_target.id ==
5072		     lun->rsv_nexus.targ_target.id)) {
5073			lun->flags &= ~CTL_LUN_RESERVED;
5074		}
5075	}
5076
5077	mtx_unlock(&lun->lun_lock);
5078
5079	ctsio->scsi_status = SCSI_STATUS_OK;
5080	ctsio->io_hdr.status = CTL_SUCCESS;
5081
5082	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5083		free(ctsio->kern_data_ptr, M_CTL);
5084		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5085	}
5086
5087	ctl_done((union ctl_io *)ctsio);
5088	return (CTL_RETVAL_COMPLETE);
5089}
5090
5091int
5092ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5093{
5094	int extent, thirdparty, longid;
5095	int resv_id, length;
5096	uint64_t thirdparty_id;
5097	struct ctl_softc *ctl_softc;
5098	struct ctl_lun *lun;
5099
5100	extent = 0;
5101	thirdparty = 0;
5102	longid = 0;
5103	resv_id = 0;
5104	length = 0;
5105	thirdparty_id = 0;
5106
5107	CTL_DEBUG_PRINT(("ctl_reserve\n"));
5108
5109	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5110	ctl_softc = control_softc;
5111
5112	switch (ctsio->cdb[0]) {
5113	case RESERVE: {
5114		struct scsi_reserve *cdb;
5115
5116		cdb = (struct scsi_reserve *)ctsio->cdb;
5117		if ((cdb->byte2 & 0x1f) != 0) {
5118			ctl_set_invalid_field(ctsio,
5119					      /*sks_valid*/ 1,
5120					      /*command*/ 1,
5121					      /*field*/ 1,
5122					      /*bit_valid*/ 0,
5123					      /*bit*/ 0);
5124			ctl_done((union ctl_io *)ctsio);
5125			return (CTL_RETVAL_COMPLETE);
5126		}
5127		resv_id = cdb->resv_id;
5128		length = scsi_2btoul(cdb->length);
5129		break;
5130	}
5131	case RESERVE_10: {
5132		struct scsi_reserve_10 *cdb;
5133
5134		cdb = (struct scsi_reserve_10 *)ctsio->cdb;
5135
5136		if ((cdb->byte2 & SR10_EXTENT) != 0) {
5137			ctl_set_invalid_field(ctsio,
5138					      /*sks_valid*/ 1,
5139					      /*command*/ 1,
5140					      /*field*/ 1,
5141					      /*bit_valid*/ 1,
5142					      /*bit*/ 0);
5143			ctl_done((union ctl_io *)ctsio);
5144			return (CTL_RETVAL_COMPLETE);
5145		}
5146		if ((cdb->byte2 & SR10_3RDPTY) != 0) {
5147			ctl_set_invalid_field(ctsio,
5148					      /*sks_valid*/ 1,
5149					      /*command*/ 1,
5150					      /*field*/ 1,
5151					      /*bit_valid*/ 1,
5152					      /*bit*/ 4);
5153			ctl_done((union ctl_io *)ctsio);
5154			return (CTL_RETVAL_COMPLETE);
5155		}
5156		if (cdb->byte2 & SR10_LONGID)
5157			longid = 1;
5158		else
5159			thirdparty_id = cdb->thirdparty_id;
5160
5161		resv_id = cdb->resv_id;
5162		length = scsi_2btoul(cdb->length);
5163		break;
5164	}
5165	}
5166
5167	/*
5168	 * XXX KDM right now, we only support LUN reservation.  We don't
5169	 * support 3rd party reservations, or extent reservations, which
5170	 * might actually need the parameter list.  If we've gotten this
5171	 * far, we've got a LUN reservation.  Anything else got kicked out
5172	 * above.  So, according to SPC, ignore the length.
5173	 */
5174	length = 0;
5175
5176	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5177	 && (length > 0)) {
5178		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5179		ctsio->kern_data_len = length;
5180		ctsio->kern_total_len = length;
5181		ctsio->kern_data_resid = 0;
5182		ctsio->kern_rel_offset = 0;
5183		ctsio->kern_sg_entries = 0;
5184		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5185		ctsio->be_move_done = ctl_config_move_done;
5186		ctl_datamove((union ctl_io *)ctsio);
5187
5188		return (CTL_RETVAL_COMPLETE);
5189	}
5190
5191	if (length > 0)
5192		thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5193
5194	mtx_lock(&lun->lun_lock);
5195	if (lun->flags & CTL_LUN_RESERVED) {
5196		if ((ctsio->io_hdr.nexus.initid.id != lun->rsv_nexus.initid.id)
5197		 || (ctsio->io_hdr.nexus.targ_port != lun->rsv_nexus.targ_port)
5198		 || (ctsio->io_hdr.nexus.targ_target.id !=
5199		     lun->rsv_nexus.targ_target.id)) {
5200			ctsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
5201			ctsio->io_hdr.status = CTL_SCSI_ERROR;
5202			goto bailout;
5203		}
5204	}
5205
5206	lun->flags |= CTL_LUN_RESERVED;
5207	lun->rsv_nexus = ctsio->io_hdr.nexus;
5208
5209	ctsio->scsi_status = SCSI_STATUS_OK;
5210	ctsio->io_hdr.status = CTL_SUCCESS;
5211
5212bailout:
5213	mtx_unlock(&lun->lun_lock);
5214
5215	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5216		free(ctsio->kern_data_ptr, M_CTL);
5217		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5218	}
5219
5220	ctl_done((union ctl_io *)ctsio);
5221	return (CTL_RETVAL_COMPLETE);
5222}
5223
5224int
5225ctl_start_stop(struct ctl_scsiio *ctsio)
5226{
5227	struct scsi_start_stop_unit *cdb;
5228	struct ctl_lun *lun;
5229	struct ctl_softc *ctl_softc;
5230	int retval;
5231
5232	CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5233
5234	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5235	ctl_softc = control_softc;
5236	retval = 0;
5237
5238	cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5239
5240	/*
5241	 * XXX KDM
5242	 * We don't support the immediate bit on a stop unit.  In order to
5243	 * do that, we would need to code up a way to know that a stop is
5244	 * pending, and hold off any new commands until it completes, one
5245	 * way or another.  Then we could accept or reject those commands
5246	 * depending on its status.  We would almost need to do the reverse
5247	 * of what we do below for an immediate start -- return the copy of
5248	 * the ctl_io to the FETD with status to send to the host (and to
5249	 * free the copy!) and then free the original I/O once the stop
5250	 * actually completes.  That way, the OOA queue mechanism can work
5251	 * to block commands that shouldn't proceed.  Another alternative
5252	 * would be to put the copy in the queue in place of the original,
5253	 * and return the original back to the caller.  That could be
5254	 * slightly safer..
5255	 */
5256	if ((cdb->byte2 & SSS_IMMED)
5257	 && ((cdb->how & SSS_START) == 0)) {
5258		ctl_set_invalid_field(ctsio,
5259				      /*sks_valid*/ 1,
5260				      /*command*/ 1,
5261				      /*field*/ 1,
5262				      /*bit_valid*/ 1,
5263				      /*bit*/ 0);
5264		ctl_done((union ctl_io *)ctsio);
5265		return (CTL_RETVAL_COMPLETE);
5266	}
5267
5268	/*
5269	 * We don't support the power conditions field.  We need to check
5270	 * this prior to checking the load/eject and start/stop bits.
5271	 */
5272	if ((cdb->how & SSS_PC_MASK) != SSS_PC_START_VALID) {
5273		ctl_set_invalid_field(ctsio,
5274				      /*sks_valid*/ 1,
5275				      /*command*/ 1,
5276				      /*field*/ 4,
5277				      /*bit_valid*/ 1,
5278				      /*bit*/ 4);
5279		ctl_done((union ctl_io *)ctsio);
5280		return (CTL_RETVAL_COMPLETE);
5281	}
5282
5283	/*
5284	 * Media isn't removable, so we can't load or eject it.
5285	 */
5286	if ((cdb->how & SSS_LOEJ) != 0) {
5287		ctl_set_invalid_field(ctsio,
5288				      /*sks_valid*/ 1,
5289				      /*command*/ 1,
5290				      /*field*/ 4,
5291				      /*bit_valid*/ 1,
5292				      /*bit*/ 1);
5293		ctl_done((union ctl_io *)ctsio);
5294		return (CTL_RETVAL_COMPLETE);
5295	}
5296
5297	if ((lun->flags & CTL_LUN_PR_RESERVED)
5298	 && ((cdb->how & SSS_START)==0)) {
5299		uint32_t residx;
5300
5301		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5302		if (!lun->per_res[residx].registered
5303		 || (lun->pr_res_idx!=residx && lun->res_type < 4)) {
5304
5305			ctl_set_reservation_conflict(ctsio);
5306			ctl_done((union ctl_io *)ctsio);
5307			return (CTL_RETVAL_COMPLETE);
5308		}
5309	}
5310
5311	/*
5312	 * If there is no backend on this device, we can't start or stop
5313	 * it.  In theory we shouldn't get any start/stop commands in the
5314	 * first place at this level if the LUN doesn't have a backend.
5315	 * That should get stopped by the command decode code.
5316	 */
5317	if (lun->backend == NULL) {
5318		ctl_set_invalid_opcode(ctsio);
5319		ctl_done((union ctl_io *)ctsio);
5320		return (CTL_RETVAL_COMPLETE);
5321	}
5322
5323	/*
5324	 * XXX KDM Copan-specific offline behavior.
5325	 * Figure out a reasonable way to port this?
5326	 */
5327#ifdef NEEDTOPORT
5328	mtx_lock(&lun->lun_lock);
5329
5330	if (((cdb->byte2 & SSS_ONOFFLINE) == 0)
5331	 && (lun->flags & CTL_LUN_OFFLINE)) {
5332		/*
5333		 * If the LUN is offline, and the on/offline bit isn't set,
5334		 * reject the start or stop.  Otherwise, let it through.
5335		 */
5336		mtx_unlock(&lun->lun_lock);
5337		ctl_set_lun_not_ready(ctsio);
5338		ctl_done((union ctl_io *)ctsio);
5339	} else {
5340		mtx_unlock(&lun->lun_lock);
5341#endif /* NEEDTOPORT */
5342		/*
5343		 * This could be a start or a stop when we're online,
5344		 * or a stop/offline or start/online.  A start or stop when
5345		 * we're offline is covered in the case above.
5346		 */
5347		/*
5348		 * In the non-immediate case, we send the request to
5349		 * the backend and return status to the user when
5350		 * it is done.
5351		 *
5352		 * In the immediate case, we allocate a new ctl_io
5353		 * to hold a copy of the request, and send that to
5354		 * the backend.  We then set good status on the
5355		 * user's request and return it immediately.
5356		 */
5357		if (cdb->byte2 & SSS_IMMED) {
5358			union ctl_io *new_io;
5359
5360			new_io = ctl_alloc_io(ctsio->io_hdr.pool);
5361			if (new_io == NULL) {
5362				ctl_set_busy(ctsio);
5363				ctl_done((union ctl_io *)ctsio);
5364			} else {
5365				ctl_copy_io((union ctl_io *)ctsio,
5366					    new_io);
5367				retval = lun->backend->config_write(new_io);
5368				ctl_set_success(ctsio);
5369				ctl_done((union ctl_io *)ctsio);
5370			}
5371		} else {
5372			retval = lun->backend->config_write(
5373				(union ctl_io *)ctsio);
5374		}
5375#ifdef NEEDTOPORT
5376	}
5377#endif
5378	return (retval);
5379}
5380
5381/*
5382 * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5383 * we don't really do anything with the LBA and length fields if the user
5384 * passes them in.  Instead we'll just flush out the cache for the entire
5385 * LUN.
5386 */
5387int
5388ctl_sync_cache(struct ctl_scsiio *ctsio)
5389{
5390	struct ctl_lun *lun;
5391	struct ctl_softc *ctl_softc;
5392	uint64_t starting_lba;
5393	uint32_t block_count;
5394	int reladr, immed;
5395	int retval;
5396
5397	CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5398
5399	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5400	ctl_softc = control_softc;
5401	retval = 0;
5402	reladr = 0;
5403	immed = 0;
5404
5405	switch (ctsio->cdb[0]) {
5406	case SYNCHRONIZE_CACHE: {
5407		struct scsi_sync_cache *cdb;
5408		cdb = (struct scsi_sync_cache *)ctsio->cdb;
5409
5410		if (cdb->byte2 & SSC_RELADR)
5411			reladr = 1;
5412
5413		if (cdb->byte2 & SSC_IMMED)
5414			immed = 1;
5415
5416		starting_lba = scsi_4btoul(cdb->begin_lba);
5417		block_count = scsi_2btoul(cdb->lb_count);
5418		break;
5419	}
5420	case SYNCHRONIZE_CACHE_16: {
5421		struct scsi_sync_cache_16 *cdb;
5422		cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5423
5424		if (cdb->byte2 & SSC_RELADR)
5425			reladr = 1;
5426
5427		if (cdb->byte2 & SSC_IMMED)
5428			immed = 1;
5429
5430		starting_lba = scsi_8btou64(cdb->begin_lba);
5431		block_count = scsi_4btoul(cdb->lb_count);
5432		break;
5433	}
5434	default:
5435		ctl_set_invalid_opcode(ctsio);
5436		ctl_done((union ctl_io *)ctsio);
5437		goto bailout;
5438		break; /* NOTREACHED */
5439	}
5440
5441	if (immed) {
5442		/*
5443		 * We don't support the immediate bit.  Since it's in the
5444		 * same place for the 10 and 16 byte SYNCHRONIZE CACHE
5445		 * commands, we can just return the same error in either
5446		 * case.
5447		 */
5448		ctl_set_invalid_field(ctsio,
5449				      /*sks_valid*/ 1,
5450				      /*command*/ 1,
5451				      /*field*/ 1,
5452				      /*bit_valid*/ 1,
5453				      /*bit*/ 1);
5454		ctl_done((union ctl_io *)ctsio);
5455		goto bailout;
5456	}
5457
5458	if (reladr) {
5459		/*
5460		 * We don't support the reladr bit either.  It can only be
5461		 * used with linked commands, and we don't support linked
5462		 * commands.  Since the bit is in the same place for the
5463		 * 10 and 16 byte SYNCHRONIZE CACHE * commands, we can
5464		 * just return the same error in either case.
5465		 */
5466		ctl_set_invalid_field(ctsio,
5467				      /*sks_valid*/ 1,
5468				      /*command*/ 1,
5469				      /*field*/ 1,
5470				      /*bit_valid*/ 1,
5471				      /*bit*/ 0);
5472		ctl_done((union ctl_io *)ctsio);
5473		goto bailout;
5474	}
5475
5476	/*
5477	 * We check the LBA and length, but don't do anything with them.
5478	 * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5479	 * get flushed.  This check will just help satisfy anyone who wants
5480	 * to see an error for an out of range LBA.
5481	 */
5482	if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5483		ctl_set_lba_out_of_range(ctsio);
5484		ctl_done((union ctl_io *)ctsio);
5485		goto bailout;
5486	}
5487
5488	/*
5489	 * If this LUN has no backend, we can't flush the cache anyway.
5490	 */
5491	if (lun->backend == NULL) {
5492		ctl_set_invalid_opcode(ctsio);
5493		ctl_done((union ctl_io *)ctsio);
5494		goto bailout;
5495	}
5496
5497	/*
5498	 * Check to see whether we're configured to send the SYNCHRONIZE
5499	 * CACHE command directly to the back end.
5500	 */
5501	mtx_lock(&lun->lun_lock);
5502	if ((ctl_softc->flags & CTL_FLAG_REAL_SYNC)
5503	 && (++(lun->sync_count) >= lun->sync_interval)) {
5504		lun->sync_count = 0;
5505		mtx_unlock(&lun->lun_lock);
5506		retval = lun->backend->config_write((union ctl_io *)ctsio);
5507	} else {
5508		mtx_unlock(&lun->lun_lock);
5509		ctl_set_success(ctsio);
5510		ctl_done((union ctl_io *)ctsio);
5511	}
5512
5513bailout:
5514
5515	return (retval);
5516}
5517
5518int
5519ctl_format(struct ctl_scsiio *ctsio)
5520{
5521	struct scsi_format *cdb;
5522	struct ctl_lun *lun;
5523	struct ctl_softc *ctl_softc;
5524	int length, defect_list_len;
5525
5526	CTL_DEBUG_PRINT(("ctl_format\n"));
5527
5528	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5529	ctl_softc = control_softc;
5530
5531	cdb = (struct scsi_format *)ctsio->cdb;
5532
5533	length = 0;
5534	if (cdb->byte2 & SF_FMTDATA) {
5535		if (cdb->byte2 & SF_LONGLIST)
5536			length = sizeof(struct scsi_format_header_long);
5537		else
5538			length = sizeof(struct scsi_format_header_short);
5539	}
5540
5541	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5542	 && (length > 0)) {
5543		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5544		ctsio->kern_data_len = length;
5545		ctsio->kern_total_len = length;
5546		ctsio->kern_data_resid = 0;
5547		ctsio->kern_rel_offset = 0;
5548		ctsio->kern_sg_entries = 0;
5549		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5550		ctsio->be_move_done = ctl_config_move_done;
5551		ctl_datamove((union ctl_io *)ctsio);
5552
5553		return (CTL_RETVAL_COMPLETE);
5554	}
5555
5556	defect_list_len = 0;
5557
5558	if (cdb->byte2 & SF_FMTDATA) {
5559		if (cdb->byte2 & SF_LONGLIST) {
5560			struct scsi_format_header_long *header;
5561
5562			header = (struct scsi_format_header_long *)
5563				ctsio->kern_data_ptr;
5564
5565			defect_list_len = scsi_4btoul(header->defect_list_len);
5566			if (defect_list_len != 0) {
5567				ctl_set_invalid_field(ctsio,
5568						      /*sks_valid*/ 1,
5569						      /*command*/ 0,
5570						      /*field*/ 2,
5571						      /*bit_valid*/ 0,
5572						      /*bit*/ 0);
5573				goto bailout;
5574			}
5575		} else {
5576			struct scsi_format_header_short *header;
5577
5578			header = (struct scsi_format_header_short *)
5579				ctsio->kern_data_ptr;
5580
5581			defect_list_len = scsi_2btoul(header->defect_list_len);
5582			if (defect_list_len != 0) {
5583				ctl_set_invalid_field(ctsio,
5584						      /*sks_valid*/ 1,
5585						      /*command*/ 0,
5586						      /*field*/ 2,
5587						      /*bit_valid*/ 0,
5588						      /*bit*/ 0);
5589				goto bailout;
5590			}
5591		}
5592	}
5593
5594	/*
5595	 * The format command will clear out the "Medium format corrupted"
5596	 * status if set by the configuration code.  That status is really
5597	 * just a way to notify the host that we have lost the media, and
5598	 * get them to issue a command that will basically make them think
5599	 * they're blowing away the media.
5600	 */
5601	mtx_lock(&lun->lun_lock);
5602	lun->flags &= ~CTL_LUN_INOPERABLE;
5603	mtx_unlock(&lun->lun_lock);
5604
5605	ctsio->scsi_status = SCSI_STATUS_OK;
5606	ctsio->io_hdr.status = CTL_SUCCESS;
5607bailout:
5608
5609	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5610		free(ctsio->kern_data_ptr, M_CTL);
5611		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5612	}
5613
5614	ctl_done((union ctl_io *)ctsio);
5615	return (CTL_RETVAL_COMPLETE);
5616}
5617
5618int
5619ctl_read_buffer(struct ctl_scsiio *ctsio)
5620{
5621	struct scsi_read_buffer *cdb;
5622	struct ctl_lun *lun;
5623	int buffer_offset, len;
5624	static uint8_t descr[4];
5625	static uint8_t echo_descr[4] = { 0 };
5626
5627	CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5628
5629	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5630	cdb = (struct scsi_read_buffer *)ctsio->cdb;
5631
5632	if (lun->flags & CTL_LUN_PR_RESERVED) {
5633		uint32_t residx;
5634
5635		/*
5636		 * XXX KDM need a lock here.
5637		 */
5638		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5639		if ((lun->res_type == SPR_TYPE_EX_AC
5640		  && residx != lun->pr_res_idx)
5641		 || ((lun->res_type == SPR_TYPE_EX_AC_RO
5642		   || lun->res_type == SPR_TYPE_EX_AC_AR)
5643		  && !lun->per_res[residx].registered)) {
5644			ctl_set_reservation_conflict(ctsio);
5645			ctl_done((union ctl_io *)ctsio);
5646			return (CTL_RETVAL_COMPLETE);
5647	        }
5648	}
5649
5650	if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA &&
5651	    (cdb->byte2 & RWB_MODE) != RWB_MODE_ECHO_DESCR &&
5652	    (cdb->byte2 & RWB_MODE) != RWB_MODE_DESCR) {
5653		ctl_set_invalid_field(ctsio,
5654				      /*sks_valid*/ 1,
5655				      /*command*/ 1,
5656				      /*field*/ 1,
5657				      /*bit_valid*/ 1,
5658				      /*bit*/ 4);
5659		ctl_done((union ctl_io *)ctsio);
5660		return (CTL_RETVAL_COMPLETE);
5661	}
5662	if (cdb->buffer_id != 0) {
5663		ctl_set_invalid_field(ctsio,
5664				      /*sks_valid*/ 1,
5665				      /*command*/ 1,
5666				      /*field*/ 2,
5667				      /*bit_valid*/ 0,
5668				      /*bit*/ 0);
5669		ctl_done((union ctl_io *)ctsio);
5670		return (CTL_RETVAL_COMPLETE);
5671	}
5672
5673	len = scsi_3btoul(cdb->length);
5674	buffer_offset = scsi_3btoul(cdb->offset);
5675
5676	if (buffer_offset + len > sizeof(lun->write_buffer)) {
5677		ctl_set_invalid_field(ctsio,
5678				      /*sks_valid*/ 1,
5679				      /*command*/ 1,
5680				      /*field*/ 6,
5681				      /*bit_valid*/ 0,
5682				      /*bit*/ 0);
5683		ctl_done((union ctl_io *)ctsio);
5684		return (CTL_RETVAL_COMPLETE);
5685	}
5686
5687	if ((cdb->byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5688		descr[0] = 0;
5689		scsi_ulto3b(sizeof(lun->write_buffer), &descr[1]);
5690		ctsio->kern_data_ptr = descr;
5691		len = min(len, sizeof(descr));
5692	} else if ((cdb->byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5693		ctsio->kern_data_ptr = echo_descr;
5694		len = min(len, sizeof(echo_descr));
5695	} else
5696		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5697	ctsio->kern_data_len = len;
5698	ctsio->kern_total_len = len;
5699	ctsio->kern_data_resid = 0;
5700	ctsio->kern_rel_offset = 0;
5701	ctsio->kern_sg_entries = 0;
5702	ctsio->be_move_done = ctl_config_move_done;
5703	ctl_datamove((union ctl_io *)ctsio);
5704
5705	return (CTL_RETVAL_COMPLETE);
5706}
5707
5708int
5709ctl_write_buffer(struct ctl_scsiio *ctsio)
5710{
5711	struct scsi_write_buffer *cdb;
5712	struct ctl_lun *lun;
5713	int buffer_offset, len;
5714
5715	CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5716
5717	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5718	cdb = (struct scsi_write_buffer *)ctsio->cdb;
5719
5720	if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA) {
5721		ctl_set_invalid_field(ctsio,
5722				      /*sks_valid*/ 1,
5723				      /*command*/ 1,
5724				      /*field*/ 1,
5725				      /*bit_valid*/ 1,
5726				      /*bit*/ 4);
5727		ctl_done((union ctl_io *)ctsio);
5728		return (CTL_RETVAL_COMPLETE);
5729	}
5730	if (cdb->buffer_id != 0) {
5731		ctl_set_invalid_field(ctsio,
5732				      /*sks_valid*/ 1,
5733				      /*command*/ 1,
5734				      /*field*/ 2,
5735				      /*bit_valid*/ 0,
5736				      /*bit*/ 0);
5737		ctl_done((union ctl_io *)ctsio);
5738		return (CTL_RETVAL_COMPLETE);
5739	}
5740
5741	len = scsi_3btoul(cdb->length);
5742	buffer_offset = scsi_3btoul(cdb->offset);
5743
5744	if (buffer_offset + len > sizeof(lun->write_buffer)) {
5745		ctl_set_invalid_field(ctsio,
5746				      /*sks_valid*/ 1,
5747				      /*command*/ 1,
5748				      /*field*/ 6,
5749				      /*bit_valid*/ 0,
5750				      /*bit*/ 0);
5751		ctl_done((union ctl_io *)ctsio);
5752		return (CTL_RETVAL_COMPLETE);
5753	}
5754
5755	/*
5756	 * If we've got a kernel request that hasn't been malloced yet,
5757	 * malloc it and tell the caller the data buffer is here.
5758	 */
5759	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5760		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5761		ctsio->kern_data_len = len;
5762		ctsio->kern_total_len = len;
5763		ctsio->kern_data_resid = 0;
5764		ctsio->kern_rel_offset = 0;
5765		ctsio->kern_sg_entries = 0;
5766		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5767		ctsio->be_move_done = ctl_config_move_done;
5768		ctl_datamove((union ctl_io *)ctsio);
5769
5770		return (CTL_RETVAL_COMPLETE);
5771	}
5772
5773	ctl_done((union ctl_io *)ctsio);
5774
5775	return (CTL_RETVAL_COMPLETE);
5776}
5777
5778int
5779ctl_write_same(struct ctl_scsiio *ctsio)
5780{
5781	struct ctl_lun *lun;
5782	struct ctl_lba_len_flags *lbalen;
5783	uint64_t lba;
5784	uint32_t num_blocks;
5785	int len, retval;
5786	uint8_t byte2;
5787
5788	retval = CTL_RETVAL_COMPLETE;
5789
5790	CTL_DEBUG_PRINT(("ctl_write_same\n"));
5791
5792	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5793
5794	switch (ctsio->cdb[0]) {
5795	case WRITE_SAME_10: {
5796		struct scsi_write_same_10 *cdb;
5797
5798		cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5799
5800		lba = scsi_4btoul(cdb->addr);
5801		num_blocks = scsi_2btoul(cdb->length);
5802		byte2 = cdb->byte2;
5803		break;
5804	}
5805	case WRITE_SAME_16: {
5806		struct scsi_write_same_16 *cdb;
5807
5808		cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5809
5810		lba = scsi_8btou64(cdb->addr);
5811		num_blocks = scsi_4btoul(cdb->length);
5812		byte2 = cdb->byte2;
5813		break;
5814	}
5815	default:
5816		/*
5817		 * We got a command we don't support.  This shouldn't
5818		 * happen, commands should be filtered out above us.
5819		 */
5820		ctl_set_invalid_opcode(ctsio);
5821		ctl_done((union ctl_io *)ctsio);
5822
5823		return (CTL_RETVAL_COMPLETE);
5824		break; /* NOTREACHED */
5825	}
5826
5827	/*
5828	 * The first check is to make sure we're in bounds, the second
5829	 * check is to catch wrap-around problems.  If the lba + num blocks
5830	 * is less than the lba, then we've wrapped around and the block
5831	 * range is invalid anyway.
5832	 */
5833	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5834	 || ((lba + num_blocks) < lba)) {
5835		ctl_set_lba_out_of_range(ctsio);
5836		ctl_done((union ctl_io *)ctsio);
5837		return (CTL_RETVAL_COMPLETE);
5838	}
5839
5840	/* Zero number of blocks means "to the last logical block" */
5841	if (num_blocks == 0) {
5842		if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5843			ctl_set_invalid_field(ctsio,
5844					      /*sks_valid*/ 0,
5845					      /*command*/ 1,
5846					      /*field*/ 0,
5847					      /*bit_valid*/ 0,
5848					      /*bit*/ 0);
5849			ctl_done((union ctl_io *)ctsio);
5850			return (CTL_RETVAL_COMPLETE);
5851		}
5852		num_blocks = (lun->be_lun->maxlba + 1) - lba;
5853	}
5854
5855	len = lun->be_lun->blocksize;
5856
5857	/*
5858	 * If we've got a kernel request that hasn't been malloced yet,
5859	 * malloc it and tell the caller the data buffer is here.
5860	 */
5861	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5862		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5863		ctsio->kern_data_len = len;
5864		ctsio->kern_total_len = len;
5865		ctsio->kern_data_resid = 0;
5866		ctsio->kern_rel_offset = 0;
5867		ctsio->kern_sg_entries = 0;
5868		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5869		ctsio->be_move_done = ctl_config_move_done;
5870		ctl_datamove((union ctl_io *)ctsio);
5871
5872		return (CTL_RETVAL_COMPLETE);
5873	}
5874
5875	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5876	lbalen->lba = lba;
5877	lbalen->len = num_blocks;
5878	lbalen->flags = byte2;
5879	retval = lun->backend->config_write((union ctl_io *)ctsio);
5880
5881	return (retval);
5882}
5883
5884int
5885ctl_unmap(struct ctl_scsiio *ctsio)
5886{
5887	struct ctl_lun *lun;
5888	struct scsi_unmap *cdb;
5889	struct ctl_ptr_len_flags *ptrlen;
5890	struct scsi_unmap_header *hdr;
5891	struct scsi_unmap_desc *buf, *end;
5892	uint64_t lba;
5893	uint32_t num_blocks;
5894	int len, retval;
5895	uint8_t byte2;
5896
5897	retval = CTL_RETVAL_COMPLETE;
5898
5899	CTL_DEBUG_PRINT(("ctl_unmap\n"));
5900
5901	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5902	cdb = (struct scsi_unmap *)ctsio->cdb;
5903
5904	len = scsi_2btoul(cdb->length);
5905	byte2 = cdb->byte2;
5906
5907	/*
5908	 * If we've got a kernel request that hasn't been malloced yet,
5909	 * malloc it and tell the caller the data buffer is here.
5910	 */
5911	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5912		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5913		ctsio->kern_data_len = len;
5914		ctsio->kern_total_len = len;
5915		ctsio->kern_data_resid = 0;
5916		ctsio->kern_rel_offset = 0;
5917		ctsio->kern_sg_entries = 0;
5918		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5919		ctsio->be_move_done = ctl_config_move_done;
5920		ctl_datamove((union ctl_io *)ctsio);
5921
5922		return (CTL_RETVAL_COMPLETE);
5923	}
5924
5925	len = ctsio->kern_total_len - ctsio->kern_data_resid;
5926	hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
5927	if (len < sizeof (*hdr) ||
5928	    len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
5929	    len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
5930	    scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
5931		ctl_set_invalid_field(ctsio,
5932				      /*sks_valid*/ 0,
5933				      /*command*/ 0,
5934				      /*field*/ 0,
5935				      /*bit_valid*/ 0,
5936				      /*bit*/ 0);
5937		ctl_done((union ctl_io *)ctsio);
5938		return (CTL_RETVAL_COMPLETE);
5939	}
5940	len = scsi_2btoul(hdr->desc_length);
5941	buf = (struct scsi_unmap_desc *)(hdr + 1);
5942	end = buf + len / sizeof(*buf);
5943
5944	ptrlen = (struct ctl_ptr_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5945	ptrlen->ptr = (void *)buf;
5946	ptrlen->len = len;
5947	ptrlen->flags = byte2;
5948
5949	for (; buf < end; buf++) {
5950		lba = scsi_8btou64(buf->lba);
5951		num_blocks = scsi_4btoul(buf->length);
5952		if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5953		 || ((lba + num_blocks) < lba)) {
5954			ctl_set_lba_out_of_range(ctsio);
5955			ctl_done((union ctl_io *)ctsio);
5956			return (CTL_RETVAL_COMPLETE);
5957		}
5958	}
5959
5960	retval = lun->backend->config_write((union ctl_io *)ctsio);
5961
5962	return (retval);
5963}
5964
5965/*
5966 * Note that this function currently doesn't actually do anything inside
5967 * CTL to enforce things if the DQue bit is turned on.
5968 *
5969 * Also note that this function can't be used in the default case, because
5970 * the DQue bit isn't set in the changeable mask for the control mode page
5971 * anyway.  This is just here as an example for how to implement a page
5972 * handler, and a placeholder in case we want to allow the user to turn
5973 * tagged queueing on and off.
5974 *
5975 * The D_SENSE bit handling is functional, however, and will turn
5976 * descriptor sense on and off for a given LUN.
5977 */
5978int
5979ctl_control_page_handler(struct ctl_scsiio *ctsio,
5980			 struct ctl_page_index *page_index, uint8_t *page_ptr)
5981{
5982	struct scsi_control_page *current_cp, *saved_cp, *user_cp;
5983	struct ctl_lun *lun;
5984	struct ctl_softc *softc;
5985	int set_ua;
5986	uint32_t initidx;
5987
5988	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5989	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5990	set_ua = 0;
5991
5992	user_cp = (struct scsi_control_page *)page_ptr;
5993	current_cp = (struct scsi_control_page *)
5994		(page_index->page_data + (page_index->page_len *
5995		CTL_PAGE_CURRENT));
5996	saved_cp = (struct scsi_control_page *)
5997		(page_index->page_data + (page_index->page_len *
5998		CTL_PAGE_SAVED));
5999
6000	softc = control_softc;
6001
6002	mtx_lock(&lun->lun_lock);
6003	if (((current_cp->rlec & SCP_DSENSE) == 0)
6004	 && ((user_cp->rlec & SCP_DSENSE) != 0)) {
6005		/*
6006		 * Descriptor sense is currently turned off and the user
6007		 * wants to turn it on.
6008		 */
6009		current_cp->rlec |= SCP_DSENSE;
6010		saved_cp->rlec |= SCP_DSENSE;
6011		lun->flags |= CTL_LUN_SENSE_DESC;
6012		set_ua = 1;
6013	} else if (((current_cp->rlec & SCP_DSENSE) != 0)
6014		&& ((user_cp->rlec & SCP_DSENSE) == 0)) {
6015		/*
6016		 * Descriptor sense is currently turned on, and the user
6017		 * wants to turn it off.
6018		 */
6019		current_cp->rlec &= ~SCP_DSENSE;
6020		saved_cp->rlec &= ~SCP_DSENSE;
6021		lun->flags &= ~CTL_LUN_SENSE_DESC;
6022		set_ua = 1;
6023	}
6024	if (current_cp->queue_flags & SCP_QUEUE_DQUE) {
6025		if (user_cp->queue_flags & SCP_QUEUE_DQUE) {
6026#ifdef NEEDTOPORT
6027			csevent_log(CSC_CTL | CSC_SHELF_SW |
6028				    CTL_UNTAG_TO_UNTAG,
6029				    csevent_LogType_Trace,
6030				    csevent_Severity_Information,
6031				    csevent_AlertLevel_Green,
6032				    csevent_FRU_Firmware,
6033				    csevent_FRU_Unknown,
6034				    "Received untagged to untagged transition");
6035#endif /* NEEDTOPORT */
6036		} else {
6037#ifdef NEEDTOPORT
6038			csevent_log(CSC_CTL | CSC_SHELF_SW |
6039				    CTL_UNTAG_TO_TAG,
6040				    csevent_LogType_ConfigChange,
6041				    csevent_Severity_Information,
6042				    csevent_AlertLevel_Green,
6043				    csevent_FRU_Firmware,
6044				    csevent_FRU_Unknown,
6045				    "Received untagged to tagged "
6046				    "queueing transition");
6047#endif /* NEEDTOPORT */
6048
6049			current_cp->queue_flags &= ~SCP_QUEUE_DQUE;
6050			saved_cp->queue_flags &= ~SCP_QUEUE_DQUE;
6051			set_ua = 1;
6052		}
6053	} else {
6054		if (user_cp->queue_flags & SCP_QUEUE_DQUE) {
6055#ifdef NEEDTOPORT
6056			csevent_log(CSC_CTL | CSC_SHELF_SW |
6057				    CTL_TAG_TO_UNTAG,
6058				    csevent_LogType_ConfigChange,
6059				    csevent_Severity_Warning,
6060				    csevent_AlertLevel_Yellow,
6061				    csevent_FRU_Firmware,
6062				    csevent_FRU_Unknown,
6063				    "Received tagged queueing to untagged "
6064				    "transition");
6065#endif /* NEEDTOPORT */
6066
6067			current_cp->queue_flags |= SCP_QUEUE_DQUE;
6068			saved_cp->queue_flags |= SCP_QUEUE_DQUE;
6069			set_ua = 1;
6070		} else {
6071#ifdef NEEDTOPORT
6072			csevent_log(CSC_CTL | CSC_SHELF_SW |
6073				    CTL_TAG_TO_TAG,
6074				    csevent_LogType_Trace,
6075				    csevent_Severity_Information,
6076				    csevent_AlertLevel_Green,
6077				    csevent_FRU_Firmware,
6078				    csevent_FRU_Unknown,
6079				    "Received tagged queueing to tagged "
6080				    "queueing transition");
6081#endif /* NEEDTOPORT */
6082		}
6083	}
6084	if (set_ua != 0) {
6085		int i;
6086		/*
6087		 * Let other initiators know that the mode
6088		 * parameters for this LUN have changed.
6089		 */
6090		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
6091			if (i == initidx)
6092				continue;
6093
6094			lun->pending_sense[i].ua_pending |=
6095				CTL_UA_MODE_CHANGE;
6096		}
6097	}
6098	mtx_unlock(&lun->lun_lock);
6099
6100	return (0);
6101}
6102
6103int
6104ctl_power_sp_handler(struct ctl_scsiio *ctsio,
6105		     struct ctl_page_index *page_index, uint8_t *page_ptr)
6106{
6107	return (0);
6108}
6109
6110int
6111ctl_power_sp_sense_handler(struct ctl_scsiio *ctsio,
6112			   struct ctl_page_index *page_index, int pc)
6113{
6114	struct copan_power_subpage *page;
6115
6116	page = (struct copan_power_subpage *)page_index->page_data +
6117		(page_index->page_len * pc);
6118
6119	switch (pc) {
6120	case SMS_PAGE_CTRL_CHANGEABLE >> 6:
6121		/*
6122		 * We don't update the changable bits for this page.
6123		 */
6124		break;
6125	case SMS_PAGE_CTRL_CURRENT >> 6:
6126	case SMS_PAGE_CTRL_DEFAULT >> 6:
6127	case SMS_PAGE_CTRL_SAVED >> 6:
6128#ifdef NEEDTOPORT
6129		ctl_update_power_subpage(page);
6130#endif
6131		break;
6132	default:
6133#ifdef NEEDTOPORT
6134		EPRINT(0, "Invalid PC %d!!", pc);
6135#endif
6136		break;
6137	}
6138	return (0);
6139}
6140
6141
6142int
6143ctl_aps_sp_handler(struct ctl_scsiio *ctsio,
6144		   struct ctl_page_index *page_index, uint8_t *page_ptr)
6145{
6146	struct copan_aps_subpage *user_sp;
6147	struct copan_aps_subpage *current_sp;
6148	union ctl_modepage_info *modepage_info;
6149	struct ctl_softc *softc;
6150	struct ctl_lun *lun;
6151	int retval;
6152
6153	retval = CTL_RETVAL_COMPLETE;
6154	current_sp = (struct copan_aps_subpage *)(page_index->page_data +
6155		     (page_index->page_len * CTL_PAGE_CURRENT));
6156	softc = control_softc;
6157	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6158
6159	user_sp = (struct copan_aps_subpage *)page_ptr;
6160
6161	modepage_info = (union ctl_modepage_info *)
6162		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6163
6164	modepage_info->header.page_code = page_index->page_code & SMPH_PC_MASK;
6165	modepage_info->header.subpage = page_index->subpage;
6166	modepage_info->aps.lock_active = user_sp->lock_active;
6167
6168	mtx_lock(&softc->ctl_lock);
6169
6170	/*
6171	 * If there is a request to lock the LUN and another LUN is locked
6172	 * this is an error. If the requested LUN is already locked ignore
6173	 * the request. If no LUN is locked attempt to lock it.
6174	 * if there is a request to unlock the LUN and the LUN is currently
6175	 * locked attempt to unlock it. Otherwise ignore the request. i.e.
6176	 * if another LUN is locked or no LUN is locked.
6177	 */
6178	if (user_sp->lock_active & APS_LOCK_ACTIVE) {
6179		if (softc->aps_locked_lun == lun->lun) {
6180			/*
6181			 * This LUN is already locked, so we're done.
6182			 */
6183			retval = CTL_RETVAL_COMPLETE;
6184		} else if (softc->aps_locked_lun == 0) {
6185			/*
6186			 * No one has the lock, pass the request to the
6187			 * backend.
6188			 */
6189			retval = lun->backend->config_write(
6190				(union ctl_io *)ctsio);
6191		} else {
6192			/*
6193			 * Someone else has the lock, throw out the request.
6194			 */
6195			ctl_set_already_locked(ctsio);
6196			free(ctsio->kern_data_ptr, M_CTL);
6197			ctl_done((union ctl_io *)ctsio);
6198
6199			/*
6200			 * Set the return value so that ctl_do_mode_select()
6201			 * won't try to complete the command.  We already
6202			 * completed it here.
6203			 */
6204			retval = CTL_RETVAL_ERROR;
6205		}
6206	} else if (softc->aps_locked_lun == lun->lun) {
6207		/*
6208		 * This LUN is locked, so pass the unlock request to the
6209		 * backend.
6210		 */
6211		retval = lun->backend->config_write((union ctl_io *)ctsio);
6212	}
6213	mtx_unlock(&softc->ctl_lock);
6214
6215	return (retval);
6216}
6217
6218int
6219ctl_debugconf_sp_select_handler(struct ctl_scsiio *ctsio,
6220				struct ctl_page_index *page_index,
6221				uint8_t *page_ptr)
6222{
6223	uint8_t *c;
6224	int i;
6225
6226	c = ((struct copan_debugconf_subpage *)page_ptr)->ctl_time_io_secs;
6227	ctl_time_io_secs =
6228		(c[0] << 8) |
6229		(c[1] << 0) |
6230		0;
6231	CTL_DEBUG_PRINT(("set ctl_time_io_secs to %d\n", ctl_time_io_secs));
6232	printf("set ctl_time_io_secs to %d\n", ctl_time_io_secs);
6233	printf("page data:");
6234	for (i=0; i<8; i++)
6235		printf(" %.2x",page_ptr[i]);
6236	printf("\n");
6237	return (0);
6238}
6239
6240int
6241ctl_debugconf_sp_sense_handler(struct ctl_scsiio *ctsio,
6242			       struct ctl_page_index *page_index,
6243			       int pc)
6244{
6245	struct copan_debugconf_subpage *page;
6246
6247	page = (struct copan_debugconf_subpage *)page_index->page_data +
6248		(page_index->page_len * pc);
6249
6250	switch (pc) {
6251	case SMS_PAGE_CTRL_CHANGEABLE >> 6:
6252	case SMS_PAGE_CTRL_DEFAULT >> 6:
6253	case SMS_PAGE_CTRL_SAVED >> 6:
6254		/*
6255		 * We don't update the changable or default bits for this page.
6256		 */
6257		break;
6258	case SMS_PAGE_CTRL_CURRENT >> 6:
6259		page->ctl_time_io_secs[0] = ctl_time_io_secs >> 8;
6260		page->ctl_time_io_secs[1] = ctl_time_io_secs >> 0;
6261		break;
6262	default:
6263#ifdef NEEDTOPORT
6264		EPRINT(0, "Invalid PC %d!!", pc);
6265#endif /* NEEDTOPORT */
6266		break;
6267	}
6268	return (0);
6269}
6270
6271
6272static int
6273ctl_do_mode_select(union ctl_io *io)
6274{
6275	struct scsi_mode_page_header *page_header;
6276	struct ctl_page_index *page_index;
6277	struct ctl_scsiio *ctsio;
6278	int control_dev, page_len;
6279	int page_len_offset, page_len_size;
6280	union ctl_modepage_info *modepage_info;
6281	struct ctl_lun *lun;
6282	int *len_left, *len_used;
6283	int retval, i;
6284
6285	ctsio = &io->scsiio;
6286	page_index = NULL;
6287	page_len = 0;
6288	retval = CTL_RETVAL_COMPLETE;
6289
6290	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6291
6292	if (lun->be_lun->lun_type != T_DIRECT)
6293		control_dev = 1;
6294	else
6295		control_dev = 0;
6296
6297	modepage_info = (union ctl_modepage_info *)
6298		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6299	len_left = &modepage_info->header.len_left;
6300	len_used = &modepage_info->header.len_used;
6301
6302do_next_page:
6303
6304	page_header = (struct scsi_mode_page_header *)
6305		(ctsio->kern_data_ptr + *len_used);
6306
6307	if (*len_left == 0) {
6308		free(ctsio->kern_data_ptr, M_CTL);
6309		ctl_set_success(ctsio);
6310		ctl_done((union ctl_io *)ctsio);
6311		return (CTL_RETVAL_COMPLETE);
6312	} else if (*len_left < sizeof(struct scsi_mode_page_header)) {
6313
6314		free(ctsio->kern_data_ptr, M_CTL);
6315		ctl_set_param_len_error(ctsio);
6316		ctl_done((union ctl_io *)ctsio);
6317		return (CTL_RETVAL_COMPLETE);
6318
6319	} else if ((page_header->page_code & SMPH_SPF)
6320		&& (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
6321
6322		free(ctsio->kern_data_ptr, M_CTL);
6323		ctl_set_param_len_error(ctsio);
6324		ctl_done((union ctl_io *)ctsio);
6325		return (CTL_RETVAL_COMPLETE);
6326	}
6327
6328
6329	/*
6330	 * XXX KDM should we do something with the block descriptor?
6331	 */
6332	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6333
6334		if ((control_dev != 0)
6335		 && (lun->mode_pages.index[i].page_flags &
6336		     CTL_PAGE_FLAG_DISK_ONLY))
6337			continue;
6338
6339		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
6340		    (page_header->page_code & SMPH_PC_MASK))
6341			continue;
6342
6343		/*
6344		 * If neither page has a subpage code, then we've got a
6345		 * match.
6346		 */
6347		if (((lun->mode_pages.index[i].page_code & SMPH_SPF) == 0)
6348		 && ((page_header->page_code & SMPH_SPF) == 0)) {
6349			page_index = &lun->mode_pages.index[i];
6350			page_len = page_header->page_length;
6351			break;
6352		}
6353
6354		/*
6355		 * If both pages have subpages, then the subpage numbers
6356		 * have to match.
6357		 */
6358		if ((lun->mode_pages.index[i].page_code & SMPH_SPF)
6359		  && (page_header->page_code & SMPH_SPF)) {
6360			struct scsi_mode_page_header_sp *sph;
6361
6362			sph = (struct scsi_mode_page_header_sp *)page_header;
6363
6364			if (lun->mode_pages.index[i].subpage ==
6365			    sph->subpage) {
6366				page_index = &lun->mode_pages.index[i];
6367				page_len = scsi_2btoul(sph->page_length);
6368				break;
6369			}
6370		}
6371	}
6372
6373	/*
6374	 * If we couldn't find the page, or if we don't have a mode select
6375	 * handler for it, send back an error to the user.
6376	 */
6377	if ((page_index == NULL)
6378	 || (page_index->select_handler == NULL)) {
6379		ctl_set_invalid_field(ctsio,
6380				      /*sks_valid*/ 1,
6381				      /*command*/ 0,
6382				      /*field*/ *len_used,
6383				      /*bit_valid*/ 0,
6384				      /*bit*/ 0);
6385		free(ctsio->kern_data_ptr, M_CTL);
6386		ctl_done((union ctl_io *)ctsio);
6387		return (CTL_RETVAL_COMPLETE);
6388	}
6389
6390	if (page_index->page_code & SMPH_SPF) {
6391		page_len_offset = 2;
6392		page_len_size = 2;
6393	} else {
6394		page_len_size = 1;
6395		page_len_offset = 1;
6396	}
6397
6398	/*
6399	 * If the length the initiator gives us isn't the one we specify in
6400	 * the mode page header, or if they didn't specify enough data in
6401	 * the CDB to avoid truncating this page, kick out the request.
6402	 */
6403	if ((page_len != (page_index->page_len - page_len_offset -
6404			  page_len_size))
6405	 || (*len_left < page_index->page_len)) {
6406
6407
6408		ctl_set_invalid_field(ctsio,
6409				      /*sks_valid*/ 1,
6410				      /*command*/ 0,
6411				      /*field*/ *len_used + page_len_offset,
6412				      /*bit_valid*/ 0,
6413				      /*bit*/ 0);
6414		free(ctsio->kern_data_ptr, M_CTL);
6415		ctl_done((union ctl_io *)ctsio);
6416		return (CTL_RETVAL_COMPLETE);
6417	}
6418
6419	/*
6420	 * Run through the mode page, checking to make sure that the bits
6421	 * the user changed are actually legal for him to change.
6422	 */
6423	for (i = 0; i < page_index->page_len; i++) {
6424		uint8_t *user_byte, *change_mask, *current_byte;
6425		int bad_bit;
6426		int j;
6427
6428		user_byte = (uint8_t *)page_header + i;
6429		change_mask = page_index->page_data +
6430			      (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6431		current_byte = page_index->page_data +
6432			       (page_index->page_len * CTL_PAGE_CURRENT) + i;
6433
6434		/*
6435		 * Check to see whether the user set any bits in this byte
6436		 * that he is not allowed to set.
6437		 */
6438		if ((*user_byte & ~(*change_mask)) ==
6439		    (*current_byte & ~(*change_mask)))
6440			continue;
6441
6442		/*
6443		 * Go through bit by bit to determine which one is illegal.
6444		 */
6445		bad_bit = 0;
6446		for (j = 7; j >= 0; j--) {
6447			if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6448			    (((1 << i) & ~(*change_mask)) & *current_byte)) {
6449				bad_bit = i;
6450				break;
6451			}
6452		}
6453		ctl_set_invalid_field(ctsio,
6454				      /*sks_valid*/ 1,
6455				      /*command*/ 0,
6456				      /*field*/ *len_used + i,
6457				      /*bit_valid*/ 1,
6458				      /*bit*/ bad_bit);
6459		free(ctsio->kern_data_ptr, M_CTL);
6460		ctl_done((union ctl_io *)ctsio);
6461		return (CTL_RETVAL_COMPLETE);
6462	}
6463
6464	/*
6465	 * Decrement these before we call the page handler, since we may
6466	 * end up getting called back one way or another before the handler
6467	 * returns to this context.
6468	 */
6469	*len_left -= page_index->page_len;
6470	*len_used += page_index->page_len;
6471
6472	retval = page_index->select_handler(ctsio, page_index,
6473					    (uint8_t *)page_header);
6474
6475	/*
6476	 * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6477	 * wait until this queued command completes to finish processing
6478	 * the mode page.  If it returns anything other than
6479	 * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6480	 * already set the sense information, freed the data pointer, and
6481	 * completed the io for us.
6482	 */
6483	if (retval != CTL_RETVAL_COMPLETE)
6484		goto bailout_no_done;
6485
6486	/*
6487	 * If the initiator sent us more than one page, parse the next one.
6488	 */
6489	if (*len_left > 0)
6490		goto do_next_page;
6491
6492	ctl_set_success(ctsio);
6493	free(ctsio->kern_data_ptr, M_CTL);
6494	ctl_done((union ctl_io *)ctsio);
6495
6496bailout_no_done:
6497
6498	return (CTL_RETVAL_COMPLETE);
6499
6500}
6501
6502int
6503ctl_mode_select(struct ctl_scsiio *ctsio)
6504{
6505	int param_len, pf, sp;
6506	int header_size, bd_len;
6507	int len_left, len_used;
6508	struct ctl_page_index *page_index;
6509	struct ctl_lun *lun;
6510	int control_dev, page_len;
6511	union ctl_modepage_info *modepage_info;
6512	int retval;
6513
6514	pf = 0;
6515	sp = 0;
6516	page_len = 0;
6517	len_used = 0;
6518	len_left = 0;
6519	retval = 0;
6520	bd_len = 0;
6521	page_index = NULL;
6522
6523	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6524
6525	if (lun->be_lun->lun_type != T_DIRECT)
6526		control_dev = 1;
6527	else
6528		control_dev = 0;
6529
6530	switch (ctsio->cdb[0]) {
6531	case MODE_SELECT_6: {
6532		struct scsi_mode_select_6 *cdb;
6533
6534		cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6535
6536		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6537		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6538
6539		param_len = cdb->length;
6540		header_size = sizeof(struct scsi_mode_header_6);
6541		break;
6542	}
6543	case MODE_SELECT_10: {
6544		struct scsi_mode_select_10 *cdb;
6545
6546		cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6547
6548		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6549		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6550
6551		param_len = scsi_2btoul(cdb->length);
6552		header_size = sizeof(struct scsi_mode_header_10);
6553		break;
6554	}
6555	default:
6556		ctl_set_invalid_opcode(ctsio);
6557		ctl_done((union ctl_io *)ctsio);
6558		return (CTL_RETVAL_COMPLETE);
6559		break; /* NOTREACHED */
6560	}
6561
6562	/*
6563	 * From SPC-3:
6564	 * "A parameter list length of zero indicates that the Data-Out Buffer
6565	 * shall be empty. This condition shall not be considered as an error."
6566	 */
6567	if (param_len == 0) {
6568		ctl_set_success(ctsio);
6569		ctl_done((union ctl_io *)ctsio);
6570		return (CTL_RETVAL_COMPLETE);
6571	}
6572
6573	/*
6574	 * Since we'll hit this the first time through, prior to
6575	 * allocation, we don't need to free a data buffer here.
6576	 */
6577	if (param_len < header_size) {
6578		ctl_set_param_len_error(ctsio);
6579		ctl_done((union ctl_io *)ctsio);
6580		return (CTL_RETVAL_COMPLETE);
6581	}
6582
6583	/*
6584	 * Allocate the data buffer and grab the user's data.  In theory,
6585	 * we shouldn't have to sanity check the parameter list length here
6586	 * because the maximum size is 64K.  We should be able to malloc
6587	 * that much without too many problems.
6588	 */
6589	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6590		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6591		ctsio->kern_data_len = param_len;
6592		ctsio->kern_total_len = param_len;
6593		ctsio->kern_data_resid = 0;
6594		ctsio->kern_rel_offset = 0;
6595		ctsio->kern_sg_entries = 0;
6596		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6597		ctsio->be_move_done = ctl_config_move_done;
6598		ctl_datamove((union ctl_io *)ctsio);
6599
6600		return (CTL_RETVAL_COMPLETE);
6601	}
6602
6603	switch (ctsio->cdb[0]) {
6604	case MODE_SELECT_6: {
6605		struct scsi_mode_header_6 *mh6;
6606
6607		mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6608		bd_len = mh6->blk_desc_len;
6609		break;
6610	}
6611	case MODE_SELECT_10: {
6612		struct scsi_mode_header_10 *mh10;
6613
6614		mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6615		bd_len = scsi_2btoul(mh10->blk_desc_len);
6616		break;
6617	}
6618	default:
6619		panic("Invalid CDB type %#x", ctsio->cdb[0]);
6620		break;
6621	}
6622
6623	if (param_len < (header_size + bd_len)) {
6624		free(ctsio->kern_data_ptr, M_CTL);
6625		ctl_set_param_len_error(ctsio);
6626		ctl_done((union ctl_io *)ctsio);
6627		return (CTL_RETVAL_COMPLETE);
6628	}
6629
6630	/*
6631	 * Set the IO_CONT flag, so that if this I/O gets passed to
6632	 * ctl_config_write_done(), it'll get passed back to
6633	 * ctl_do_mode_select() for further processing, or completion if
6634	 * we're all done.
6635	 */
6636	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6637	ctsio->io_cont = ctl_do_mode_select;
6638
6639	modepage_info = (union ctl_modepage_info *)
6640		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6641
6642	memset(modepage_info, 0, sizeof(*modepage_info));
6643
6644	len_left = param_len - header_size - bd_len;
6645	len_used = header_size + bd_len;
6646
6647	modepage_info->header.len_left = len_left;
6648	modepage_info->header.len_used = len_used;
6649
6650	return (ctl_do_mode_select((union ctl_io *)ctsio));
6651}
6652
6653int
6654ctl_mode_sense(struct ctl_scsiio *ctsio)
6655{
6656	struct ctl_lun *lun;
6657	int pc, page_code, dbd, llba, subpage;
6658	int alloc_len, page_len, header_len, total_len;
6659	struct scsi_mode_block_descr *block_desc;
6660	struct ctl_page_index *page_index;
6661	int control_dev;
6662
6663	dbd = 0;
6664	llba = 0;
6665	block_desc = NULL;
6666	page_index = NULL;
6667
6668	CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6669
6670	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6671
6672	if (lun->be_lun->lun_type != T_DIRECT)
6673		control_dev = 1;
6674	else
6675		control_dev = 0;
6676
6677	if (lun->flags & CTL_LUN_PR_RESERVED) {
6678		uint32_t residx;
6679
6680		/*
6681		 * XXX KDM need a lock here.
6682		 */
6683		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
6684		if ((lun->res_type == SPR_TYPE_EX_AC
6685		  && residx != lun->pr_res_idx)
6686		 || ((lun->res_type == SPR_TYPE_EX_AC_RO
6687		   || lun->res_type == SPR_TYPE_EX_AC_AR)
6688		  && !lun->per_res[residx].registered)) {
6689			ctl_set_reservation_conflict(ctsio);
6690			ctl_done((union ctl_io *)ctsio);
6691			return (CTL_RETVAL_COMPLETE);
6692		}
6693	}
6694
6695	switch (ctsio->cdb[0]) {
6696	case MODE_SENSE_6: {
6697		struct scsi_mode_sense_6 *cdb;
6698
6699		cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6700
6701		header_len = sizeof(struct scsi_mode_hdr_6);
6702		if (cdb->byte2 & SMS_DBD)
6703			dbd = 1;
6704		else
6705			header_len += sizeof(struct scsi_mode_block_descr);
6706
6707		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6708		page_code = cdb->page & SMS_PAGE_CODE;
6709		subpage = cdb->subpage;
6710		alloc_len = cdb->length;
6711		break;
6712	}
6713	case MODE_SENSE_10: {
6714		struct scsi_mode_sense_10 *cdb;
6715
6716		cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6717
6718		header_len = sizeof(struct scsi_mode_hdr_10);
6719
6720		if (cdb->byte2 & SMS_DBD)
6721			dbd = 1;
6722		else
6723			header_len += sizeof(struct scsi_mode_block_descr);
6724		if (cdb->byte2 & SMS10_LLBAA)
6725			llba = 1;
6726		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6727		page_code = cdb->page & SMS_PAGE_CODE;
6728		subpage = cdb->subpage;
6729		alloc_len = scsi_2btoul(cdb->length);
6730		break;
6731	}
6732	default:
6733		ctl_set_invalid_opcode(ctsio);
6734		ctl_done((union ctl_io *)ctsio);
6735		return (CTL_RETVAL_COMPLETE);
6736		break; /* NOTREACHED */
6737	}
6738
6739	/*
6740	 * We have to make a first pass through to calculate the size of
6741	 * the pages that match the user's query.  Then we allocate enough
6742	 * memory to hold it, and actually copy the data into the buffer.
6743	 */
6744	switch (page_code) {
6745	case SMS_ALL_PAGES_PAGE: {
6746		int i;
6747
6748		page_len = 0;
6749
6750		/*
6751		 * At the moment, values other than 0 and 0xff here are
6752		 * reserved according to SPC-3.
6753		 */
6754		if ((subpage != SMS_SUBPAGE_PAGE_0)
6755		 && (subpage != SMS_SUBPAGE_ALL)) {
6756			ctl_set_invalid_field(ctsio,
6757					      /*sks_valid*/ 1,
6758					      /*command*/ 1,
6759					      /*field*/ 3,
6760					      /*bit_valid*/ 0,
6761					      /*bit*/ 0);
6762			ctl_done((union ctl_io *)ctsio);
6763			return (CTL_RETVAL_COMPLETE);
6764		}
6765
6766		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6767			if ((control_dev != 0)
6768			 && (lun->mode_pages.index[i].page_flags &
6769			     CTL_PAGE_FLAG_DISK_ONLY))
6770				continue;
6771
6772			/*
6773			 * We don't use this subpage if the user didn't
6774			 * request all subpages.
6775			 */
6776			if ((lun->mode_pages.index[i].subpage != 0)
6777			 && (subpage == SMS_SUBPAGE_PAGE_0))
6778				continue;
6779
6780#if 0
6781			printf("found page %#x len %d\n",
6782			       lun->mode_pages.index[i].page_code &
6783			       SMPH_PC_MASK,
6784			       lun->mode_pages.index[i].page_len);
6785#endif
6786			page_len += lun->mode_pages.index[i].page_len;
6787		}
6788		break;
6789	}
6790	default: {
6791		int i;
6792
6793		page_len = 0;
6794
6795		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6796			/* Look for the right page code */
6797			if ((lun->mode_pages.index[i].page_code &
6798			     SMPH_PC_MASK) != page_code)
6799				continue;
6800
6801			/* Look for the right subpage or the subpage wildcard*/
6802			if ((lun->mode_pages.index[i].subpage != subpage)
6803			 && (subpage != SMS_SUBPAGE_ALL))
6804				continue;
6805
6806			/* Make sure the page is supported for this dev type */
6807			if ((control_dev != 0)
6808			 && (lun->mode_pages.index[i].page_flags &
6809			     CTL_PAGE_FLAG_DISK_ONLY))
6810				continue;
6811
6812#if 0
6813			printf("found page %#x len %d\n",
6814			       lun->mode_pages.index[i].page_code &
6815			       SMPH_PC_MASK,
6816			       lun->mode_pages.index[i].page_len);
6817#endif
6818
6819			page_len += lun->mode_pages.index[i].page_len;
6820		}
6821
6822		if (page_len == 0) {
6823			ctl_set_invalid_field(ctsio,
6824					      /*sks_valid*/ 1,
6825					      /*command*/ 1,
6826					      /*field*/ 2,
6827					      /*bit_valid*/ 1,
6828					      /*bit*/ 5);
6829			ctl_done((union ctl_io *)ctsio);
6830			return (CTL_RETVAL_COMPLETE);
6831		}
6832		break;
6833	}
6834	}
6835
6836	total_len = header_len + page_len;
6837#if 0
6838	printf("header_len = %d, page_len = %d, total_len = %d\n",
6839	       header_len, page_len, total_len);
6840#endif
6841
6842	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6843	ctsio->kern_sg_entries = 0;
6844	ctsio->kern_data_resid = 0;
6845	ctsio->kern_rel_offset = 0;
6846	if (total_len < alloc_len) {
6847		ctsio->residual = alloc_len - total_len;
6848		ctsio->kern_data_len = total_len;
6849		ctsio->kern_total_len = total_len;
6850	} else {
6851		ctsio->residual = 0;
6852		ctsio->kern_data_len = alloc_len;
6853		ctsio->kern_total_len = alloc_len;
6854	}
6855
6856	switch (ctsio->cdb[0]) {
6857	case MODE_SENSE_6: {
6858		struct scsi_mode_hdr_6 *header;
6859
6860		header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6861
6862		header->datalen = ctl_min(total_len - 1, 254);
6863
6864		if (dbd)
6865			header->block_descr_len = 0;
6866		else
6867			header->block_descr_len =
6868				sizeof(struct scsi_mode_block_descr);
6869		block_desc = (struct scsi_mode_block_descr *)&header[1];
6870		break;
6871	}
6872	case MODE_SENSE_10: {
6873		struct scsi_mode_hdr_10 *header;
6874		int datalen;
6875
6876		header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6877
6878		datalen = ctl_min(total_len - 2, 65533);
6879		scsi_ulto2b(datalen, header->datalen);
6880		if (dbd)
6881			scsi_ulto2b(0, header->block_descr_len);
6882		else
6883			scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
6884				    header->block_descr_len);
6885		block_desc = (struct scsi_mode_block_descr *)&header[1];
6886		break;
6887	}
6888	default:
6889		panic("invalid CDB type %#x", ctsio->cdb[0]);
6890		break; /* NOTREACHED */
6891	}
6892
6893	/*
6894	 * If we've got a disk, use its blocksize in the block
6895	 * descriptor.  Otherwise, just set it to 0.
6896	 */
6897	if (dbd == 0) {
6898		if (control_dev != 0)
6899			scsi_ulto3b(lun->be_lun->blocksize,
6900				    block_desc->block_len);
6901		else
6902			scsi_ulto3b(0, block_desc->block_len);
6903	}
6904
6905	switch (page_code) {
6906	case SMS_ALL_PAGES_PAGE: {
6907		int i, data_used;
6908
6909		data_used = header_len;
6910		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6911			struct ctl_page_index *page_index;
6912
6913			page_index = &lun->mode_pages.index[i];
6914
6915			if ((control_dev != 0)
6916			 && (page_index->page_flags &
6917			    CTL_PAGE_FLAG_DISK_ONLY))
6918				continue;
6919
6920			/*
6921			 * We don't use this subpage if the user didn't
6922			 * request all subpages.  We already checked (above)
6923			 * to make sure the user only specified a subpage
6924			 * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
6925			 */
6926			if ((page_index->subpage != 0)
6927			 && (subpage == SMS_SUBPAGE_PAGE_0))
6928				continue;
6929
6930			/*
6931			 * Call the handler, if it exists, to update the
6932			 * page to the latest values.
6933			 */
6934			if (page_index->sense_handler != NULL)
6935				page_index->sense_handler(ctsio, page_index,pc);
6936
6937			memcpy(ctsio->kern_data_ptr + data_used,
6938			       page_index->page_data +
6939			       (page_index->page_len * pc),
6940			       page_index->page_len);
6941			data_used += page_index->page_len;
6942		}
6943		break;
6944	}
6945	default: {
6946		int i, data_used;
6947
6948		data_used = header_len;
6949
6950		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6951			struct ctl_page_index *page_index;
6952
6953			page_index = &lun->mode_pages.index[i];
6954
6955			/* Look for the right page code */
6956			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6957				continue;
6958
6959			/* Look for the right subpage or the subpage wildcard*/
6960			if ((page_index->subpage != subpage)
6961			 && (subpage != SMS_SUBPAGE_ALL))
6962				continue;
6963
6964			/* Make sure the page is supported for this dev type */
6965			if ((control_dev != 0)
6966			 && (page_index->page_flags &
6967			     CTL_PAGE_FLAG_DISK_ONLY))
6968				continue;
6969
6970			/*
6971			 * Call the handler, if it exists, to update the
6972			 * page to the latest values.
6973			 */
6974			if (page_index->sense_handler != NULL)
6975				page_index->sense_handler(ctsio, page_index,pc);
6976
6977			memcpy(ctsio->kern_data_ptr + data_used,
6978			       page_index->page_data +
6979			       (page_index->page_len * pc),
6980			       page_index->page_len);
6981			data_used += page_index->page_len;
6982		}
6983		break;
6984	}
6985	}
6986
6987	ctsio->scsi_status = SCSI_STATUS_OK;
6988
6989	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6990	ctsio->be_move_done = ctl_config_move_done;
6991	ctl_datamove((union ctl_io *)ctsio);
6992
6993	return (CTL_RETVAL_COMPLETE);
6994}
6995
6996int
6997ctl_read_capacity(struct ctl_scsiio *ctsio)
6998{
6999	struct scsi_read_capacity *cdb;
7000	struct scsi_read_capacity_data *data;
7001	struct ctl_lun *lun;
7002	uint32_t lba;
7003
7004	CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
7005
7006	cdb = (struct scsi_read_capacity *)ctsio->cdb;
7007
7008	lba = scsi_4btoul(cdb->addr);
7009	if (((cdb->pmi & SRC_PMI) == 0)
7010	 && (lba != 0)) {
7011		ctl_set_invalid_field(/*ctsio*/ ctsio,
7012				      /*sks_valid*/ 1,
7013				      /*command*/ 1,
7014				      /*field*/ 2,
7015				      /*bit_valid*/ 0,
7016				      /*bit*/ 0);
7017		ctl_done((union ctl_io *)ctsio);
7018		return (CTL_RETVAL_COMPLETE);
7019	}
7020
7021	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7022
7023	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7024	data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
7025	ctsio->residual = 0;
7026	ctsio->kern_data_len = sizeof(*data);
7027	ctsio->kern_total_len = sizeof(*data);
7028	ctsio->kern_data_resid = 0;
7029	ctsio->kern_rel_offset = 0;
7030	ctsio->kern_sg_entries = 0;
7031
7032	/*
7033	 * If the maximum LBA is greater than 0xfffffffe, the user must
7034	 * issue a SERVICE ACTION IN (16) command, with the read capacity
7035	 * serivce action set.
7036	 */
7037	if (lun->be_lun->maxlba > 0xfffffffe)
7038		scsi_ulto4b(0xffffffff, data->addr);
7039	else
7040		scsi_ulto4b(lun->be_lun->maxlba, data->addr);
7041
7042	/*
7043	 * XXX KDM this may not be 512 bytes...
7044	 */
7045	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7046
7047	ctsio->scsi_status = SCSI_STATUS_OK;
7048
7049	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7050	ctsio->be_move_done = ctl_config_move_done;
7051	ctl_datamove((union ctl_io *)ctsio);
7052
7053	return (CTL_RETVAL_COMPLETE);
7054}
7055
7056static int
7057ctl_read_capacity_16(struct ctl_scsiio *ctsio)
7058{
7059	struct scsi_read_capacity_16 *cdb;
7060	struct scsi_read_capacity_data_long *data;
7061	struct ctl_lun *lun;
7062	uint64_t lba;
7063	uint32_t alloc_len;
7064
7065	CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
7066
7067	cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
7068
7069	alloc_len = scsi_4btoul(cdb->alloc_len);
7070	lba = scsi_8btou64(cdb->addr);
7071
7072	if ((cdb->reladr & SRC16_PMI)
7073	 && (lba != 0)) {
7074		ctl_set_invalid_field(/*ctsio*/ ctsio,
7075				      /*sks_valid*/ 1,
7076				      /*command*/ 1,
7077				      /*field*/ 2,
7078				      /*bit_valid*/ 0,
7079				      /*bit*/ 0);
7080		ctl_done((union ctl_io *)ctsio);
7081		return (CTL_RETVAL_COMPLETE);
7082	}
7083
7084	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7085
7086	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7087	data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
7088
7089	if (sizeof(*data) < alloc_len) {
7090		ctsio->residual = alloc_len - sizeof(*data);
7091		ctsio->kern_data_len = sizeof(*data);
7092		ctsio->kern_total_len = sizeof(*data);
7093	} else {
7094		ctsio->residual = 0;
7095		ctsio->kern_data_len = alloc_len;
7096		ctsio->kern_total_len = alloc_len;
7097	}
7098	ctsio->kern_data_resid = 0;
7099	ctsio->kern_rel_offset = 0;
7100	ctsio->kern_sg_entries = 0;
7101
7102	scsi_u64to8b(lun->be_lun->maxlba, data->addr);
7103	/* XXX KDM this may not be 512 bytes... */
7104	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7105	data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
7106	scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
7107	if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
7108		data->lalba_lbp[0] |= SRC16_LBPME;
7109
7110	ctsio->scsi_status = SCSI_STATUS_OK;
7111
7112	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7113	ctsio->be_move_done = ctl_config_move_done;
7114	ctl_datamove((union ctl_io *)ctsio);
7115
7116	return (CTL_RETVAL_COMPLETE);
7117}
7118
7119int
7120ctl_service_action_in(struct ctl_scsiio *ctsio)
7121{
7122	struct scsi_service_action_in *cdb;
7123	int retval;
7124
7125	CTL_DEBUG_PRINT(("ctl_service_action_in\n"));
7126
7127	cdb = (struct scsi_service_action_in *)ctsio->cdb;
7128
7129	retval = CTL_RETVAL_COMPLETE;
7130
7131	switch (cdb->service_action) {
7132	case SRC16_SERVICE_ACTION:
7133		retval = ctl_read_capacity_16(ctsio);
7134		break;
7135	default:
7136		ctl_set_invalid_field(/*ctsio*/ ctsio,
7137				      /*sks_valid*/ 1,
7138				      /*command*/ 1,
7139				      /*field*/ 1,
7140				      /*bit_valid*/ 1,
7141				      /*bit*/ 4);
7142		ctl_done((union ctl_io *)ctsio);
7143		break;
7144	}
7145
7146	return (retval);
7147}
7148
7149int
7150ctl_maintenance_in(struct ctl_scsiio *ctsio)
7151{
7152	struct scsi_maintenance_in *cdb;
7153	int retval;
7154	int alloc_len, total_len = 0;
7155	int num_target_port_groups, single;
7156	struct ctl_lun *lun;
7157	struct ctl_softc *softc;
7158	struct scsi_target_group_data *rtg_ptr;
7159	struct scsi_target_port_group_descriptor *tpg_desc_ptr1, *tpg_desc_ptr2;
7160	struct scsi_target_port_descriptor  *tp_desc_ptr1_1, *tp_desc_ptr1_2,
7161	                                    *tp_desc_ptr2_1, *tp_desc_ptr2_2;
7162
7163	CTL_DEBUG_PRINT(("ctl_maintenance_in\n"));
7164
7165	cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7166	softc = control_softc;
7167	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7168
7169	retval = CTL_RETVAL_COMPLETE;
7170
7171	if ((cdb->byte2 & SERVICE_ACTION_MASK) != SA_RPRT_TRGT_GRP) {
7172		ctl_set_invalid_field(/*ctsio*/ ctsio,
7173				      /*sks_valid*/ 1,
7174				      /*command*/ 1,
7175				      /*field*/ 1,
7176				      /*bit_valid*/ 1,
7177				      /*bit*/ 4);
7178		ctl_done((union ctl_io *)ctsio);
7179		return(retval);
7180	}
7181
7182	single = ctl_is_single;
7183	if (single)
7184        	num_target_port_groups = NUM_TARGET_PORT_GROUPS - 1;
7185	else
7186        	num_target_port_groups = NUM_TARGET_PORT_GROUPS;
7187
7188	total_len = sizeof(struct scsi_target_group_data) +
7189		sizeof(struct scsi_target_port_group_descriptor) *
7190		num_target_port_groups +
7191		sizeof(struct scsi_target_port_descriptor) *
7192		NUM_PORTS_PER_GRP * num_target_port_groups;
7193
7194	alloc_len = scsi_4btoul(cdb->length);
7195
7196	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7197
7198	ctsio->kern_sg_entries = 0;
7199
7200	if (total_len < alloc_len) {
7201		ctsio->residual = alloc_len - total_len;
7202		ctsio->kern_data_len = total_len;
7203		ctsio->kern_total_len = total_len;
7204	} else {
7205		ctsio->residual = 0;
7206		ctsio->kern_data_len = alloc_len;
7207		ctsio->kern_total_len = alloc_len;
7208	}
7209	ctsio->kern_data_resid = 0;
7210	ctsio->kern_rel_offset = 0;
7211
7212	rtg_ptr = (struct scsi_target_group_data *)ctsio->kern_data_ptr;
7213
7214	tpg_desc_ptr1 = &rtg_ptr->groups[0];
7215	tp_desc_ptr1_1 = &tpg_desc_ptr1->descriptors[0];
7216	tp_desc_ptr1_2 = (struct scsi_target_port_descriptor *)
7217	        &tp_desc_ptr1_1->desc_list[0];
7218
7219	if (single == 0) {
7220		tpg_desc_ptr2 = (struct scsi_target_port_group_descriptor *)
7221	                &tp_desc_ptr1_2->desc_list[0];
7222		tp_desc_ptr2_1 = &tpg_desc_ptr2->descriptors[0];
7223		tp_desc_ptr2_2 = (struct scsi_target_port_descriptor *)
7224	        	&tp_desc_ptr2_1->desc_list[0];
7225        } else {
7226		tpg_desc_ptr2 = NULL;
7227		tp_desc_ptr2_1 = NULL;
7228		tp_desc_ptr2_2 = NULL;
7229	}
7230
7231	scsi_ulto4b(total_len - 4, rtg_ptr->length);
7232	if (single == 0) {
7233        	if (ctsio->io_hdr.nexus.targ_port < CTL_MAX_PORTS) {
7234			if (lun->flags & CTL_LUN_PRIMARY_SC) {
7235				tpg_desc_ptr1->pref_state = TPG_PRIMARY;
7236				tpg_desc_ptr2->pref_state =
7237					TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7238			} else {
7239				tpg_desc_ptr1->pref_state =
7240					TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7241				tpg_desc_ptr2->pref_state = TPG_PRIMARY;
7242			}
7243		} else {
7244			if (lun->flags & CTL_LUN_PRIMARY_SC) {
7245				tpg_desc_ptr1->pref_state =
7246					TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7247				tpg_desc_ptr2->pref_state = TPG_PRIMARY;
7248			} else {
7249				tpg_desc_ptr1->pref_state = TPG_PRIMARY;
7250				tpg_desc_ptr2->pref_state =
7251					TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7252			}
7253		}
7254	} else {
7255		tpg_desc_ptr1->pref_state = TPG_PRIMARY;
7256	}
7257	tpg_desc_ptr1->support = 0;
7258	tpg_desc_ptr1->target_port_group[1] = 1;
7259	tpg_desc_ptr1->status = TPG_IMPLICIT;
7260	tpg_desc_ptr1->target_port_count= NUM_PORTS_PER_GRP;
7261
7262	if (single == 0) {
7263		tpg_desc_ptr2->support = 0;
7264		tpg_desc_ptr2->target_port_group[1] = 2;
7265		tpg_desc_ptr2->status = TPG_IMPLICIT;
7266		tpg_desc_ptr2->target_port_count = NUM_PORTS_PER_GRP;
7267
7268		tp_desc_ptr1_1->relative_target_port_identifier[1] = 1;
7269		tp_desc_ptr1_2->relative_target_port_identifier[1] = 2;
7270
7271		tp_desc_ptr2_1->relative_target_port_identifier[1] = 9;
7272		tp_desc_ptr2_2->relative_target_port_identifier[1] = 10;
7273	} else {
7274        	if (ctsio->io_hdr.nexus.targ_port < CTL_MAX_PORTS) {
7275			tp_desc_ptr1_1->relative_target_port_identifier[1] = 1;
7276			tp_desc_ptr1_2->relative_target_port_identifier[1] = 2;
7277		} else {
7278			tp_desc_ptr1_1->relative_target_port_identifier[1] = 9;
7279			tp_desc_ptr1_2->relative_target_port_identifier[1] = 10;
7280		}
7281	}
7282
7283	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7284	ctsio->be_move_done = ctl_config_move_done;
7285
7286	CTL_DEBUG_PRINT(("buf = %x %x %x %x %x %x %x %x\n",
7287			 ctsio->kern_data_ptr[0], ctsio->kern_data_ptr[1],
7288			 ctsio->kern_data_ptr[2], ctsio->kern_data_ptr[3],
7289			 ctsio->kern_data_ptr[4], ctsio->kern_data_ptr[5],
7290			 ctsio->kern_data_ptr[6], ctsio->kern_data_ptr[7]));
7291
7292	ctl_datamove((union ctl_io *)ctsio);
7293	return(retval);
7294}
7295
7296int
7297ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7298{
7299	struct scsi_per_res_in *cdb;
7300	int alloc_len, total_len = 0;
7301	/* struct scsi_per_res_in_rsrv in_data; */
7302	struct ctl_lun *lun;
7303	struct ctl_softc *softc;
7304
7305	CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7306
7307	softc = control_softc;
7308
7309	cdb = (struct scsi_per_res_in *)ctsio->cdb;
7310
7311	alloc_len = scsi_2btoul(cdb->length);
7312
7313	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7314
7315retry:
7316	mtx_lock(&lun->lun_lock);
7317	switch (cdb->action) {
7318	case SPRI_RK: /* read keys */
7319		total_len = sizeof(struct scsi_per_res_in_keys) +
7320			lun->pr_key_count *
7321			sizeof(struct scsi_per_res_key);
7322		break;
7323	case SPRI_RR: /* read reservation */
7324		if (lun->flags & CTL_LUN_PR_RESERVED)
7325			total_len = sizeof(struct scsi_per_res_in_rsrv);
7326		else
7327			total_len = sizeof(struct scsi_per_res_in_header);
7328		break;
7329	case SPRI_RC: /* report capabilities */
7330		total_len = sizeof(struct scsi_per_res_cap);
7331		break;
7332	case SPRI_RS: /* read full status */
7333	default:
7334		mtx_unlock(&lun->lun_lock);
7335		ctl_set_invalid_field(ctsio,
7336				      /*sks_valid*/ 1,
7337				      /*command*/ 1,
7338				      /*field*/ 1,
7339				      /*bit_valid*/ 1,
7340				      /*bit*/ 0);
7341		ctl_done((union ctl_io *)ctsio);
7342		return (CTL_RETVAL_COMPLETE);
7343		break; /* NOTREACHED */
7344	}
7345	mtx_unlock(&lun->lun_lock);
7346
7347	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7348
7349	if (total_len < alloc_len) {
7350		ctsio->residual = alloc_len - total_len;
7351		ctsio->kern_data_len = total_len;
7352		ctsio->kern_total_len = total_len;
7353	} else {
7354		ctsio->residual = 0;
7355		ctsio->kern_data_len = alloc_len;
7356		ctsio->kern_total_len = alloc_len;
7357	}
7358
7359	ctsio->kern_data_resid = 0;
7360	ctsio->kern_rel_offset = 0;
7361	ctsio->kern_sg_entries = 0;
7362
7363	mtx_lock(&lun->lun_lock);
7364	switch (cdb->action) {
7365	case SPRI_RK: { // read keys
7366        struct scsi_per_res_in_keys *res_keys;
7367		int i, key_count;
7368
7369		res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7370
7371		/*
7372		 * We had to drop the lock to allocate our buffer, which
7373		 * leaves time for someone to come in with another
7374		 * persistent reservation.  (That is unlikely, though,
7375		 * since this should be the only persistent reservation
7376		 * command active right now.)
7377		 */
7378		if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7379		    (lun->pr_key_count *
7380		     sizeof(struct scsi_per_res_key)))){
7381			mtx_unlock(&lun->lun_lock);
7382			free(ctsio->kern_data_ptr, M_CTL);
7383			printf("%s: reservation length changed, retrying\n",
7384			       __func__);
7385			goto retry;
7386		}
7387
7388		scsi_ulto4b(lun->PRGeneration, res_keys->header.generation);
7389
7390		scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7391			     lun->pr_key_count, res_keys->header.length);
7392
7393		for (i = 0, key_count = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7394			if (!lun->per_res[i].registered)
7395				continue;
7396
7397			/*
7398			 * We used lun->pr_key_count to calculate the
7399			 * size to allocate.  If it turns out the number of
7400			 * initiators with the registered flag set is
7401			 * larger than that (i.e. they haven't been kept in
7402			 * sync), we've got a problem.
7403			 */
7404			if (key_count >= lun->pr_key_count) {
7405#ifdef NEEDTOPORT
7406				csevent_log(CSC_CTL | CSC_SHELF_SW |
7407					    CTL_PR_ERROR,
7408					    csevent_LogType_Fault,
7409					    csevent_AlertLevel_Yellow,
7410					    csevent_FRU_ShelfController,
7411					    csevent_FRU_Firmware,
7412				        csevent_FRU_Unknown,
7413					    "registered keys %d >= key "
7414					    "count %d", key_count,
7415					    lun->pr_key_count);
7416#endif
7417				key_count++;
7418				continue;
7419			}
7420			memcpy(res_keys->keys[key_count].key,
7421			       lun->per_res[i].res_key.key,
7422			       ctl_min(sizeof(res_keys->keys[key_count].key),
7423			       sizeof(lun->per_res[i].res_key)));
7424			key_count++;
7425		}
7426		break;
7427	}
7428	case SPRI_RR: { // read reservation
7429		struct scsi_per_res_in_rsrv *res;
7430		int tmp_len, header_only;
7431
7432		res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7433
7434		scsi_ulto4b(lun->PRGeneration, res->header.generation);
7435
7436		if (lun->flags & CTL_LUN_PR_RESERVED)
7437		{
7438			tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7439			scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7440				    res->header.length);
7441			header_only = 0;
7442		} else {
7443			tmp_len = sizeof(struct scsi_per_res_in_header);
7444			scsi_ulto4b(0, res->header.length);
7445			header_only = 1;
7446		}
7447
7448		/*
7449		 * We had to drop the lock to allocate our buffer, which
7450		 * leaves time for someone to come in with another
7451		 * persistent reservation.  (That is unlikely, though,
7452		 * since this should be the only persistent reservation
7453		 * command active right now.)
7454		 */
7455		if (tmp_len != total_len) {
7456			mtx_unlock(&lun->lun_lock);
7457			free(ctsio->kern_data_ptr, M_CTL);
7458			printf("%s: reservation status changed, retrying\n",
7459			       __func__);
7460			goto retry;
7461		}
7462
7463		/*
7464		 * No reservation held, so we're done.
7465		 */
7466		if (header_only != 0)
7467			break;
7468
7469		/*
7470		 * If the registration is an All Registrants type, the key
7471		 * is 0, since it doesn't really matter.
7472		 */
7473		if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7474			memcpy(res->data.reservation,
7475			       &lun->per_res[lun->pr_res_idx].res_key,
7476			       sizeof(struct scsi_per_res_key));
7477		}
7478		res->data.scopetype = lun->res_type;
7479		break;
7480	}
7481	case SPRI_RC:     //report capabilities
7482	{
7483		struct scsi_per_res_cap *res_cap;
7484		uint16_t type_mask;
7485
7486		res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7487		scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7488		res_cap->flags2 |= SPRI_TMV | SPRI_ALLOW_3;
7489		type_mask = SPRI_TM_WR_EX_AR |
7490			    SPRI_TM_EX_AC_RO |
7491			    SPRI_TM_WR_EX_RO |
7492			    SPRI_TM_EX_AC |
7493			    SPRI_TM_WR_EX |
7494			    SPRI_TM_EX_AC_AR;
7495		scsi_ulto2b(type_mask, res_cap->type_mask);
7496		break;
7497	}
7498	case SPRI_RS: //read full status
7499	default:
7500		/*
7501		 * This is a bug, because we just checked for this above,
7502		 * and should have returned an error.
7503		 */
7504		panic("Invalid PR type %x", cdb->action);
7505		break; /* NOTREACHED */
7506	}
7507	mtx_unlock(&lun->lun_lock);
7508
7509	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7510	ctsio->be_move_done = ctl_config_move_done;
7511
7512	CTL_DEBUG_PRINT(("buf = %x %x %x %x %x %x %x %x\n",
7513			 ctsio->kern_data_ptr[0], ctsio->kern_data_ptr[1],
7514			 ctsio->kern_data_ptr[2], ctsio->kern_data_ptr[3],
7515			 ctsio->kern_data_ptr[4], ctsio->kern_data_ptr[5],
7516			 ctsio->kern_data_ptr[6], ctsio->kern_data_ptr[7]));
7517
7518	ctl_datamove((union ctl_io *)ctsio);
7519
7520	return (CTL_RETVAL_COMPLETE);
7521}
7522
7523/*
7524 * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
7525 * it should return.
7526 */
7527static int
7528ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
7529		uint64_t sa_res_key, uint8_t type, uint32_t residx,
7530		struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
7531		struct scsi_per_res_out_parms* param)
7532{
7533	union ctl_ha_msg persis_io;
7534	int retval, i;
7535	int isc_retval;
7536
7537	retval = 0;
7538
7539	mtx_lock(&lun->lun_lock);
7540	if (sa_res_key == 0) {
7541		if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
7542			/* validate scope and type */
7543			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7544			     SPR_LU_SCOPE) {
7545				mtx_unlock(&lun->lun_lock);
7546				ctl_set_invalid_field(/*ctsio*/ ctsio,
7547						      /*sks_valid*/ 1,
7548						      /*command*/ 1,
7549						      /*field*/ 2,
7550						      /*bit_valid*/ 1,
7551						      /*bit*/ 4);
7552				ctl_done((union ctl_io *)ctsio);
7553				return (1);
7554			}
7555
7556		        if (type>8 || type==2 || type==4 || type==0) {
7557				mtx_unlock(&lun->lun_lock);
7558				ctl_set_invalid_field(/*ctsio*/ ctsio,
7559       	           				      /*sks_valid*/ 1,
7560						      /*command*/ 1,
7561						      /*field*/ 2,
7562						      /*bit_valid*/ 1,
7563						      /*bit*/ 0);
7564				ctl_done((union ctl_io *)ctsio);
7565				return (1);
7566		        }
7567
7568			/* temporarily unregister this nexus */
7569			lun->per_res[residx].registered = 0;
7570
7571			/*
7572			 * Unregister everybody else and build UA for
7573			 * them
7574			 */
7575			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
7576				if (lun->per_res[i].registered == 0)
7577					continue;
7578
7579				if (!persis_offset
7580				 && i <CTL_MAX_INITIATORS)
7581					lun->pending_sense[i].ua_pending |=
7582						CTL_UA_REG_PREEMPT;
7583				else if (persis_offset
7584				      && i >= persis_offset)
7585					lun->pending_sense[i-persis_offset
7586						].ua_pending |=
7587						CTL_UA_REG_PREEMPT;
7588				lun->per_res[i].registered = 0;
7589				memset(&lun->per_res[i].res_key, 0,
7590				       sizeof(struct scsi_per_res_key));
7591			}
7592			lun->per_res[residx].registered = 1;
7593			lun->pr_key_count = 1;
7594			lun->res_type = type;
7595			if (lun->res_type != SPR_TYPE_WR_EX_AR
7596			 && lun->res_type != SPR_TYPE_EX_AC_AR)
7597				lun->pr_res_idx = residx;
7598
7599			/* send msg to other side */
7600			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7601			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7602			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7603			persis_io.pr.pr_info.residx = lun->pr_res_idx;
7604			persis_io.pr.pr_info.res_type = type;
7605			memcpy(persis_io.pr.pr_info.sa_res_key,
7606			       param->serv_act_res_key,
7607			       sizeof(param->serv_act_res_key));
7608			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
7609			     &persis_io, sizeof(persis_io), 0)) >
7610			     CTL_HA_STATUS_SUCCESS) {
7611				printf("CTL:Persis Out error returned "
7612				       "from ctl_ha_msg_send %d\n",
7613				       isc_retval);
7614			}
7615		} else {
7616			/* not all registrants */
7617			mtx_unlock(&lun->lun_lock);
7618			free(ctsio->kern_data_ptr, M_CTL);
7619			ctl_set_invalid_field(ctsio,
7620					      /*sks_valid*/ 1,
7621					      /*command*/ 0,
7622					      /*field*/ 8,
7623					      /*bit_valid*/ 0,
7624					      /*bit*/ 0);
7625			ctl_done((union ctl_io *)ctsio);
7626			return (1);
7627		}
7628	} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
7629		|| !(lun->flags & CTL_LUN_PR_RESERVED)) {
7630		int found = 0;
7631
7632		if (res_key == sa_res_key) {
7633			/* special case */
7634			/*
7635			 * The spec implies this is not good but doesn't
7636			 * say what to do. There are two choices either
7637			 * generate a res conflict or check condition
7638			 * with illegal field in parameter data. Since
7639			 * that is what is done when the sa_res_key is
7640			 * zero I'll take that approach since this has
7641			 * to do with the sa_res_key.
7642			 */
7643			mtx_unlock(&lun->lun_lock);
7644			free(ctsio->kern_data_ptr, M_CTL);
7645			ctl_set_invalid_field(ctsio,
7646					      /*sks_valid*/ 1,
7647					      /*command*/ 0,
7648					      /*field*/ 8,
7649					      /*bit_valid*/ 0,
7650					      /*bit*/ 0);
7651			ctl_done((union ctl_io *)ctsio);
7652			return (1);
7653		}
7654
7655		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
7656			if (lun->per_res[i].registered
7657			 && memcmp(param->serv_act_res_key,
7658			    lun->per_res[i].res_key.key,
7659			    sizeof(struct scsi_per_res_key)) != 0)
7660				continue;
7661
7662			found = 1;
7663			lun->per_res[i].registered = 0;
7664			memset(&lun->per_res[i].res_key, 0,
7665			       sizeof(struct scsi_per_res_key));
7666			lun->pr_key_count--;
7667
7668			if (!persis_offset
7669			 && i < CTL_MAX_INITIATORS)
7670				lun->pending_sense[i].ua_pending |=
7671					CTL_UA_REG_PREEMPT;
7672			else if (persis_offset
7673			      && i >= persis_offset)
7674				lun->pending_sense[i-persis_offset].ua_pending|=
7675					CTL_UA_REG_PREEMPT;
7676		}
7677		if (!found) {
7678			mtx_unlock(&lun->lun_lock);
7679			free(ctsio->kern_data_ptr, M_CTL);
7680			ctl_set_reservation_conflict(ctsio);
7681			ctl_done((union ctl_io *)ctsio);
7682			return (CTL_RETVAL_COMPLETE);
7683		}
7684		/* send msg to other side */
7685		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7686		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7687		persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7688		persis_io.pr.pr_info.residx = lun->pr_res_idx;
7689		persis_io.pr.pr_info.res_type = type;
7690		memcpy(persis_io.pr.pr_info.sa_res_key,
7691		       param->serv_act_res_key,
7692		       sizeof(param->serv_act_res_key));
7693		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
7694		     &persis_io, sizeof(persis_io), 0)) >
7695		     CTL_HA_STATUS_SUCCESS) {
7696			printf("CTL:Persis Out error returned from "
7697			       "ctl_ha_msg_send %d\n", isc_retval);
7698		}
7699	} else {
7700		/* Reserved but not all registrants */
7701		/* sa_res_key is res holder */
7702		if (memcmp(param->serv_act_res_key,
7703                   lun->per_res[lun->pr_res_idx].res_key.key,
7704                   sizeof(struct scsi_per_res_key)) == 0) {
7705			/* validate scope and type */
7706			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7707			     SPR_LU_SCOPE) {
7708				mtx_unlock(&lun->lun_lock);
7709				ctl_set_invalid_field(/*ctsio*/ ctsio,
7710						      /*sks_valid*/ 1,
7711						      /*command*/ 1,
7712						      /*field*/ 2,
7713						      /*bit_valid*/ 1,
7714						      /*bit*/ 4);
7715				ctl_done((union ctl_io *)ctsio);
7716				return (1);
7717			}
7718
7719			if (type>8 || type==2 || type==4 || type==0) {
7720				mtx_unlock(&lun->lun_lock);
7721				ctl_set_invalid_field(/*ctsio*/ ctsio,
7722						      /*sks_valid*/ 1,
7723						      /*command*/ 1,
7724						      /*field*/ 2,
7725						      /*bit_valid*/ 1,
7726						      /*bit*/ 0);
7727				ctl_done((union ctl_io *)ctsio);
7728				return (1);
7729			}
7730
7731			/*
7732			 * Do the following:
7733			 * if sa_res_key != res_key remove all
7734			 * registrants w/sa_res_key and generate UA
7735			 * for these registrants(Registrations
7736			 * Preempted) if it wasn't an exclusive
7737			 * reservation generate UA(Reservations
7738			 * Preempted) for all other registered nexuses
7739			 * if the type has changed. Establish the new
7740			 * reservation and holder. If res_key and
7741			 * sa_res_key are the same do the above
7742			 * except don't unregister the res holder.
7743			 */
7744
7745			/*
7746			 * Temporarily unregister so it won't get
7747			 * removed or UA generated
7748			 */
7749			lun->per_res[residx].registered = 0;
7750			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
7751				if (lun->per_res[i].registered == 0)
7752					continue;
7753
7754				if (memcmp(param->serv_act_res_key,
7755				    lun->per_res[i].res_key.key,
7756				    sizeof(struct scsi_per_res_key)) == 0) {
7757					lun->per_res[i].registered = 0;
7758					memset(&lun->per_res[i].res_key,
7759					       0,
7760					       sizeof(struct scsi_per_res_key));
7761					lun->pr_key_count--;
7762
7763					if (!persis_offset
7764					 && i < CTL_MAX_INITIATORS)
7765						lun->pending_sense[i
7766							].ua_pending |=
7767							CTL_UA_REG_PREEMPT;
7768					else if (persis_offset
7769					      && i >= persis_offset)
7770						lun->pending_sense[
7771						  i-persis_offset].ua_pending |=
7772						  CTL_UA_REG_PREEMPT;
7773				} else if (type != lun->res_type
7774					&& (lun->res_type == SPR_TYPE_WR_EX_RO
7775					 || lun->res_type ==SPR_TYPE_EX_AC_RO)){
7776						if (!persis_offset
7777						 && i < CTL_MAX_INITIATORS)
7778							lun->pending_sense[i
7779							].ua_pending |=
7780							CTL_UA_RES_RELEASE;
7781						else if (persis_offset
7782						      && i >= persis_offset)
7783							lun->pending_sense[
7784							i-persis_offset
7785							].ua_pending |=
7786							CTL_UA_RES_RELEASE;
7787				}
7788			}
7789			lun->per_res[residx].registered = 1;
7790			lun->res_type = type;
7791			if (lun->res_type != SPR_TYPE_WR_EX_AR
7792			 && lun->res_type != SPR_TYPE_EX_AC_AR)
7793				lun->pr_res_idx = residx;
7794			else
7795				lun->pr_res_idx =
7796					CTL_PR_ALL_REGISTRANTS;
7797
7798			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7799			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7800			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7801			persis_io.pr.pr_info.residx = lun->pr_res_idx;
7802			persis_io.pr.pr_info.res_type = type;
7803			memcpy(persis_io.pr.pr_info.sa_res_key,
7804			       param->serv_act_res_key,
7805			       sizeof(param->serv_act_res_key));
7806			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
7807			     &persis_io, sizeof(persis_io), 0)) >
7808			     CTL_HA_STATUS_SUCCESS) {
7809				printf("CTL:Persis Out error returned "
7810				       "from ctl_ha_msg_send %d\n",
7811				       isc_retval);
7812			}
7813		} else {
7814			/*
7815			 * sa_res_key is not the res holder just
7816			 * remove registrants
7817			 */
7818			int found=0;
7819
7820			for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
7821				if (memcmp(param->serv_act_res_key,
7822				    lun->per_res[i].res_key.key,
7823				    sizeof(struct scsi_per_res_key)) != 0)
7824					continue;
7825
7826				found = 1;
7827				lun->per_res[i].registered = 0;
7828				memset(&lun->per_res[i].res_key, 0,
7829				       sizeof(struct scsi_per_res_key));
7830				lun->pr_key_count--;
7831
7832				if (!persis_offset
7833				 && i < CTL_MAX_INITIATORS)
7834					lun->pending_sense[i].ua_pending |=
7835						CTL_UA_REG_PREEMPT;
7836				else if (persis_offset
7837				      && i >= persis_offset)
7838					lun->pending_sense[
7839						i-persis_offset].ua_pending |=
7840						CTL_UA_REG_PREEMPT;
7841			}
7842
7843			if (!found) {
7844				mtx_unlock(&lun->lun_lock);
7845				free(ctsio->kern_data_ptr, M_CTL);
7846				ctl_set_reservation_conflict(ctsio);
7847				ctl_done((union ctl_io *)ctsio);
7848		        	return (1);
7849			}
7850			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7851			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7852			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7853			persis_io.pr.pr_info.residx = lun->pr_res_idx;
7854			persis_io.pr.pr_info.res_type = type;
7855			memcpy(persis_io.pr.pr_info.sa_res_key,
7856			       param->serv_act_res_key,
7857			       sizeof(param->serv_act_res_key));
7858			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
7859			     &persis_io, sizeof(persis_io), 0)) >
7860			     CTL_HA_STATUS_SUCCESS) {
7861				printf("CTL:Persis Out error returned "
7862				       "from ctl_ha_msg_send %d\n",
7863				isc_retval);
7864			}
7865		}
7866	}
7867
7868	lun->PRGeneration++;
7869	mtx_unlock(&lun->lun_lock);
7870
7871	return (retval);
7872}
7873
7874static void
7875ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
7876{
7877	int i;
7878
7879	if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
7880	 || lun->pr_res_idx == CTL_PR_NO_RESERVATION
7881	 || memcmp(&lun->per_res[lun->pr_res_idx].res_key,
7882		   msg->pr.pr_info.sa_res_key,
7883		   sizeof(struct scsi_per_res_key)) != 0) {
7884		uint64_t sa_res_key;
7885		sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
7886
7887		if (sa_res_key == 0) {
7888			/* temporarily unregister this nexus */
7889			lun->per_res[msg->pr.pr_info.residx].registered = 0;
7890
7891			/*
7892			 * Unregister everybody else and build UA for
7893			 * them
7894			 */
7895			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
7896				if (lun->per_res[i].registered == 0)
7897					continue;
7898
7899				if (!persis_offset
7900				 && i < CTL_MAX_INITIATORS)
7901					lun->pending_sense[i].ua_pending |=
7902						CTL_UA_REG_PREEMPT;
7903				else if (persis_offset && i >= persis_offset)
7904					lun->pending_sense[i -
7905						persis_offset].ua_pending |=
7906						CTL_UA_REG_PREEMPT;
7907				lun->per_res[i].registered = 0;
7908				memset(&lun->per_res[i].res_key, 0,
7909				       sizeof(struct scsi_per_res_key));
7910			}
7911
7912			lun->per_res[msg->pr.pr_info.residx].registered = 1;
7913			lun->pr_key_count = 1;
7914			lun->res_type = msg->pr.pr_info.res_type;
7915			if (lun->res_type != SPR_TYPE_WR_EX_AR
7916			 && lun->res_type != SPR_TYPE_EX_AC_AR)
7917				lun->pr_res_idx = msg->pr.pr_info.residx;
7918		} else {
7919		        for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
7920				if (memcmp(msg->pr.pr_info.sa_res_key,
7921		                   lun->per_res[i].res_key.key,
7922		                   sizeof(struct scsi_per_res_key)) != 0)
7923					continue;
7924
7925				lun->per_res[i].registered = 0;
7926				memset(&lun->per_res[i].res_key, 0,
7927				       sizeof(struct scsi_per_res_key));
7928				lun->pr_key_count--;
7929
7930				if (!persis_offset
7931				 && i < persis_offset)
7932					lun->pending_sense[i].ua_pending |=
7933						CTL_UA_REG_PREEMPT;
7934				else if (persis_offset
7935				      && i >= persis_offset)
7936					lun->pending_sense[i -
7937						persis_offset].ua_pending |=
7938						CTL_UA_REG_PREEMPT;
7939			}
7940		}
7941	} else {
7942		/*
7943		 * Temporarily unregister so it won't get removed
7944		 * or UA generated
7945		 */
7946		lun->per_res[msg->pr.pr_info.residx].registered = 0;
7947		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
7948			if (lun->per_res[i].registered == 0)
7949				continue;
7950
7951			if (memcmp(msg->pr.pr_info.sa_res_key,
7952	                   lun->per_res[i].res_key.key,
7953	                   sizeof(struct scsi_per_res_key)) == 0) {
7954				lun->per_res[i].registered = 0;
7955				memset(&lun->per_res[i].res_key, 0,
7956				       sizeof(struct scsi_per_res_key));
7957				lun->pr_key_count--;
7958				if (!persis_offset
7959				 && i < CTL_MAX_INITIATORS)
7960					lun->pending_sense[i].ua_pending |=
7961						CTL_UA_REG_PREEMPT;
7962				else if (persis_offset
7963				      && i >= persis_offset)
7964					lun->pending_sense[i -
7965						persis_offset].ua_pending |=
7966						CTL_UA_REG_PREEMPT;
7967			} else if (msg->pr.pr_info.res_type != lun->res_type
7968				&& (lun->res_type == SPR_TYPE_WR_EX_RO
7969				 || lun->res_type == SPR_TYPE_EX_AC_RO)) {
7970					if (!persis_offset
7971					 && i < persis_offset)
7972						lun->pending_sense[i
7973							].ua_pending |=
7974							CTL_UA_RES_RELEASE;
7975					else if (persis_offset
7976					      && i >= persis_offset)
7977					lun->pending_sense[i -
7978						persis_offset].ua_pending |=
7979						CTL_UA_RES_RELEASE;
7980			}
7981		}
7982		lun->per_res[msg->pr.pr_info.residx].registered = 1;
7983		lun->res_type = msg->pr.pr_info.res_type;
7984		if (lun->res_type != SPR_TYPE_WR_EX_AR
7985		 && lun->res_type != SPR_TYPE_EX_AC_AR)
7986			lun->pr_res_idx = msg->pr.pr_info.residx;
7987		else
7988			lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
7989	}
7990	lun->PRGeneration++;
7991
7992}
7993
7994
7995int
7996ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
7997{
7998	int retval;
7999	int isc_retval;
8000	u_int32_t param_len;
8001	struct scsi_per_res_out *cdb;
8002	struct ctl_lun *lun;
8003	struct scsi_per_res_out_parms* param;
8004	struct ctl_softc *softc;
8005	uint32_t residx;
8006	uint64_t res_key, sa_res_key;
8007	uint8_t type;
8008	union ctl_ha_msg persis_io;
8009	int    i;
8010
8011	CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8012
8013	retval = CTL_RETVAL_COMPLETE;
8014
8015	softc = control_softc;
8016
8017	cdb = (struct scsi_per_res_out *)ctsio->cdb;
8018	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8019
8020	/*
8021	 * We only support whole-LUN scope.  The scope & type are ignored for
8022	 * register, register and ignore existing key and clear.
8023	 * We sometimes ignore scope and type on preempts too!!
8024	 * Verify reservation type here as well.
8025	 */
8026	type = cdb->scope_type & SPR_TYPE_MASK;
8027	if ((cdb->action == SPRO_RESERVE)
8028	 || (cdb->action == SPRO_RELEASE)) {
8029		if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8030			ctl_set_invalid_field(/*ctsio*/ ctsio,
8031					      /*sks_valid*/ 1,
8032					      /*command*/ 1,
8033					      /*field*/ 2,
8034					      /*bit_valid*/ 1,
8035					      /*bit*/ 4);
8036			ctl_done((union ctl_io *)ctsio);
8037			return (CTL_RETVAL_COMPLETE);
8038		}
8039
8040		if (type>8 || type==2 || type==4 || type==0) {
8041			ctl_set_invalid_field(/*ctsio*/ ctsio,
8042					      /*sks_valid*/ 1,
8043					      /*command*/ 1,
8044					      /*field*/ 2,
8045					      /*bit_valid*/ 1,
8046					      /*bit*/ 0);
8047			ctl_done((union ctl_io *)ctsio);
8048			return (CTL_RETVAL_COMPLETE);
8049		}
8050	}
8051
8052	switch (cdb->action & SPRO_ACTION_MASK) {
8053	case SPRO_REGISTER:
8054	case SPRO_RESERVE:
8055	case SPRO_RELEASE:
8056	case SPRO_CLEAR:
8057	case SPRO_PREEMPT:
8058	case SPRO_REG_IGNO:
8059		break;
8060	case SPRO_REG_MOVE:
8061	case SPRO_PRE_ABO:
8062	default:
8063		ctl_set_invalid_field(/*ctsio*/ ctsio,
8064				      /*sks_valid*/ 1,
8065				      /*command*/ 1,
8066				      /*field*/ 1,
8067				      /*bit_valid*/ 1,
8068				      /*bit*/ 0);
8069		ctl_done((union ctl_io *)ctsio);
8070		return (CTL_RETVAL_COMPLETE);
8071		break; /* NOTREACHED */
8072	}
8073
8074	param_len = scsi_4btoul(cdb->length);
8075
8076	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8077		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8078		ctsio->kern_data_len = param_len;
8079		ctsio->kern_total_len = param_len;
8080		ctsio->kern_data_resid = 0;
8081		ctsio->kern_rel_offset = 0;
8082		ctsio->kern_sg_entries = 0;
8083		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8084		ctsio->be_move_done = ctl_config_move_done;
8085		ctl_datamove((union ctl_io *)ctsio);
8086
8087		return (CTL_RETVAL_COMPLETE);
8088	}
8089
8090	param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8091
8092	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
8093	res_key = scsi_8btou64(param->res_key.key);
8094	sa_res_key = scsi_8btou64(param->serv_act_res_key);
8095
8096	/*
8097	 * Validate the reservation key here except for SPRO_REG_IGNO
8098	 * This must be done for all other service actions
8099	 */
8100	if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8101		mtx_lock(&lun->lun_lock);
8102		if (lun->per_res[residx].registered) {
8103		    if (memcmp(param->res_key.key,
8104			       lun->per_res[residx].res_key.key,
8105			       ctl_min(sizeof(param->res_key),
8106			       sizeof(lun->per_res[residx].res_key))) != 0) {
8107				/*
8108				 * The current key passed in doesn't match
8109				 * the one the initiator previously
8110				 * registered.
8111				 */
8112				mtx_unlock(&lun->lun_lock);
8113				free(ctsio->kern_data_ptr, M_CTL);
8114				ctl_set_reservation_conflict(ctsio);
8115				ctl_done((union ctl_io *)ctsio);
8116				return (CTL_RETVAL_COMPLETE);
8117			}
8118		} else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8119			/*
8120			 * We are not registered
8121			 */
8122			mtx_unlock(&lun->lun_lock);
8123			free(ctsio->kern_data_ptr, M_CTL);
8124			ctl_set_reservation_conflict(ctsio);
8125			ctl_done((union ctl_io *)ctsio);
8126			return (CTL_RETVAL_COMPLETE);
8127		} else if (res_key != 0) {
8128			/*
8129			 * We are not registered and trying to register but
8130			 * the register key isn't zero.
8131			 */
8132			mtx_unlock(&lun->lun_lock);
8133			free(ctsio->kern_data_ptr, M_CTL);
8134			ctl_set_reservation_conflict(ctsio);
8135			ctl_done((union ctl_io *)ctsio);
8136			return (CTL_RETVAL_COMPLETE);
8137		}
8138		mtx_unlock(&lun->lun_lock);
8139	}
8140
8141	switch (cdb->action & SPRO_ACTION_MASK) {
8142	case SPRO_REGISTER:
8143	case SPRO_REG_IGNO: {
8144
8145#if 0
8146		printf("Registration received\n");
8147#endif
8148
8149		/*
8150		 * We don't support any of these options, as we report in
8151		 * the read capabilities request (see
8152		 * ctl_persistent_reserve_in(), above).
8153		 */
8154		if ((param->flags & SPR_SPEC_I_PT)
8155		 || (param->flags & SPR_ALL_TG_PT)
8156		 || (param->flags & SPR_APTPL)) {
8157			int bit_ptr;
8158
8159			if (param->flags & SPR_APTPL)
8160				bit_ptr = 0;
8161			else if (param->flags & SPR_ALL_TG_PT)
8162				bit_ptr = 2;
8163			else /* SPR_SPEC_I_PT */
8164				bit_ptr = 3;
8165
8166			free(ctsio->kern_data_ptr, M_CTL);
8167			ctl_set_invalid_field(ctsio,
8168					      /*sks_valid*/ 1,
8169					      /*command*/ 0,
8170					      /*field*/ 20,
8171					      /*bit_valid*/ 1,
8172					      /*bit*/ bit_ptr);
8173			ctl_done((union ctl_io *)ctsio);
8174			return (CTL_RETVAL_COMPLETE);
8175		}
8176
8177		mtx_lock(&lun->lun_lock);
8178
8179		/*
8180		 * The initiator wants to clear the
8181		 * key/unregister.
8182		 */
8183		if (sa_res_key == 0) {
8184			if ((res_key == 0
8185			  && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8186			 || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8187			  && !lun->per_res[residx].registered)) {
8188				mtx_unlock(&lun->lun_lock);
8189				goto done;
8190			}
8191
8192			lun->per_res[residx].registered = 0;
8193			memset(&lun->per_res[residx].res_key,
8194			       0, sizeof(lun->per_res[residx].res_key));
8195			lun->pr_key_count--;
8196
8197			if (residx == lun->pr_res_idx) {
8198				lun->flags &= ~CTL_LUN_PR_RESERVED;
8199				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8200
8201				if ((lun->res_type == SPR_TYPE_WR_EX_RO
8202				  || lun->res_type == SPR_TYPE_EX_AC_RO)
8203				 && lun->pr_key_count) {
8204					/*
8205					 * If the reservation is a registrants
8206					 * only type we need to generate a UA
8207					 * for other registered inits.  The
8208					 * sense code should be RESERVATIONS
8209					 * RELEASED
8210					 */
8211
8212					for (i = 0; i < CTL_MAX_INITIATORS;i++){
8213						if (lun->per_res[
8214						    i+persis_offset].registered
8215						    == 0)
8216							continue;
8217						lun->pending_sense[i
8218							].ua_pending |=
8219							CTL_UA_RES_RELEASE;
8220					}
8221				}
8222				lun->res_type = 0;
8223			} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8224				if (lun->pr_key_count==0) {
8225					lun->flags &= ~CTL_LUN_PR_RESERVED;
8226					lun->res_type = 0;
8227					lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8228				}
8229			}
8230			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8231			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8232			persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8233			persis_io.pr.pr_info.residx = residx;
8234			if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8235			     &persis_io, sizeof(persis_io), 0 )) >
8236			     CTL_HA_STATUS_SUCCESS) {
8237				printf("CTL:Persis Out error returned from "
8238				       "ctl_ha_msg_send %d\n", isc_retval);
8239			}
8240		} else /* sa_res_key != 0 */ {
8241
8242			/*
8243			 * If we aren't registered currently then increment
8244			 * the key count and set the registered flag.
8245			 */
8246			if (!lun->per_res[residx].registered) {
8247				lun->pr_key_count++;
8248				lun->per_res[residx].registered = 1;
8249			}
8250
8251			memcpy(&lun->per_res[residx].res_key,
8252			       param->serv_act_res_key,
8253			       ctl_min(sizeof(param->serv_act_res_key),
8254			       sizeof(lun->per_res[residx].res_key)));
8255
8256			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8257			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8258			persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8259			persis_io.pr.pr_info.residx = residx;
8260			memcpy(persis_io.pr.pr_info.sa_res_key,
8261			       param->serv_act_res_key,
8262			       sizeof(param->serv_act_res_key));
8263			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8264			     &persis_io, sizeof(persis_io), 0)) >
8265			     CTL_HA_STATUS_SUCCESS) {
8266				printf("CTL:Persis Out error returned from "
8267				       "ctl_ha_msg_send %d\n", isc_retval);
8268			}
8269		}
8270		lun->PRGeneration++;
8271		mtx_unlock(&lun->lun_lock);
8272
8273		break;
8274	}
8275	case SPRO_RESERVE:
8276#if 0
8277                printf("Reserve executed type %d\n", type);
8278#endif
8279		mtx_lock(&lun->lun_lock);
8280		if (lun->flags & CTL_LUN_PR_RESERVED) {
8281			/*
8282			 * if this isn't the reservation holder and it's
8283			 * not a "all registrants" type or if the type is
8284			 * different then we have a conflict
8285			 */
8286			if ((lun->pr_res_idx != residx
8287			  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8288			 || lun->res_type != type) {
8289				mtx_unlock(&lun->lun_lock);
8290				free(ctsio->kern_data_ptr, M_CTL);
8291				ctl_set_reservation_conflict(ctsio);
8292				ctl_done((union ctl_io *)ctsio);
8293				return (CTL_RETVAL_COMPLETE);
8294			}
8295			mtx_unlock(&lun->lun_lock);
8296		} else /* create a reservation */ {
8297			/*
8298			 * If it's not an "all registrants" type record
8299			 * reservation holder
8300			 */
8301			if (type != SPR_TYPE_WR_EX_AR
8302			 && type != SPR_TYPE_EX_AC_AR)
8303				lun->pr_res_idx = residx; /* Res holder */
8304			else
8305				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8306
8307			lun->flags |= CTL_LUN_PR_RESERVED;
8308			lun->res_type = type;
8309
8310			mtx_unlock(&lun->lun_lock);
8311
8312			/* send msg to other side */
8313			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8314			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8315			persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8316			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8317			persis_io.pr.pr_info.res_type = type;
8318			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8319			     &persis_io, sizeof(persis_io), 0)) >
8320			     CTL_HA_STATUS_SUCCESS) {
8321				printf("CTL:Persis Out error returned from "
8322				       "ctl_ha_msg_send %d\n", isc_retval);
8323			}
8324		}
8325		break;
8326
8327	case SPRO_RELEASE:
8328		mtx_lock(&lun->lun_lock);
8329		if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8330			/* No reservation exists return good status */
8331			mtx_unlock(&lun->lun_lock);
8332			goto done;
8333		}
8334		/*
8335		 * Is this nexus a reservation holder?
8336		 */
8337		if (lun->pr_res_idx != residx
8338		 && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8339			/*
8340			 * not a res holder return good status but
8341			 * do nothing
8342			 */
8343			mtx_unlock(&lun->lun_lock);
8344			goto done;
8345		}
8346
8347		if (lun->res_type != type) {
8348			mtx_unlock(&lun->lun_lock);
8349			free(ctsio->kern_data_ptr, M_CTL);
8350			ctl_set_illegal_pr_release(ctsio);
8351			ctl_done((union ctl_io *)ctsio);
8352			return (CTL_RETVAL_COMPLETE);
8353		}
8354
8355		/* okay to release */
8356		lun->flags &= ~CTL_LUN_PR_RESERVED;
8357		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8358		lun->res_type = 0;
8359
8360		/*
8361		 * if this isn't an exclusive access
8362		 * res generate UA for all other
8363		 * registrants.
8364		 */
8365		if (type != SPR_TYPE_EX_AC
8366		 && type != SPR_TYPE_WR_EX) {
8367			/*
8368			 * temporarily unregister so we don't generate UA
8369			 */
8370			lun->per_res[residx].registered = 0;
8371
8372			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8373				if (lun->per_res[i+persis_offset].registered
8374				    == 0)
8375					continue;
8376				lun->pending_sense[i].ua_pending |=
8377					CTL_UA_RES_RELEASE;
8378			}
8379
8380			lun->per_res[residx].registered = 1;
8381		}
8382		mtx_unlock(&lun->lun_lock);
8383		/* Send msg to other side */
8384		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8385		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8386		persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8387		if ((isc_retval=ctl_ha_msg_send( CTL_HA_CHAN_CTL, &persis_io,
8388		     sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8389			printf("CTL:Persis Out error returned from "
8390			       "ctl_ha_msg_send %d\n", isc_retval);
8391		}
8392		break;
8393
8394	case SPRO_CLEAR:
8395		/* send msg to other side */
8396
8397		mtx_lock(&lun->lun_lock);
8398		lun->flags &= ~CTL_LUN_PR_RESERVED;
8399		lun->res_type = 0;
8400		lun->pr_key_count = 0;
8401		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8402
8403
8404		memset(&lun->per_res[residx].res_key,
8405		       0, sizeof(lun->per_res[residx].res_key));
8406		lun->per_res[residx].registered = 0;
8407
8408		for (i=0; i < 2*CTL_MAX_INITIATORS; i++)
8409			if (lun->per_res[i].registered) {
8410				if (!persis_offset && i < CTL_MAX_INITIATORS)
8411					lun->pending_sense[i].ua_pending |=
8412						CTL_UA_RES_PREEMPT;
8413				else if (persis_offset && i >= persis_offset)
8414					lun->pending_sense[i-persis_offset
8415					    ].ua_pending |= CTL_UA_RES_PREEMPT;
8416
8417				memset(&lun->per_res[i].res_key,
8418				       0, sizeof(struct scsi_per_res_key));
8419				lun->per_res[i].registered = 0;
8420			}
8421		lun->PRGeneration++;
8422		mtx_unlock(&lun->lun_lock);
8423		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8424		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8425		persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8426		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8427		     sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8428			printf("CTL:Persis Out error returned from "
8429			       "ctl_ha_msg_send %d\n", isc_retval);
8430		}
8431		break;
8432
8433	case SPRO_PREEMPT: {
8434		int nretval;
8435
8436		nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8437					  residx, ctsio, cdb, param);
8438		if (nretval != 0)
8439			return (CTL_RETVAL_COMPLETE);
8440		break;
8441	}
8442	case SPRO_REG_MOVE:
8443	case SPRO_PRE_ABO:
8444	default:
8445		free(ctsio->kern_data_ptr, M_CTL);
8446		ctl_set_invalid_field(/*ctsio*/ ctsio,
8447				      /*sks_valid*/ 1,
8448				      /*command*/ 1,
8449				      /*field*/ 1,
8450				      /*bit_valid*/ 1,
8451				      /*bit*/ 0);
8452		ctl_done((union ctl_io *)ctsio);
8453		return (CTL_RETVAL_COMPLETE);
8454		break; /* NOTREACHED */
8455	}
8456
8457done:
8458	free(ctsio->kern_data_ptr, M_CTL);
8459	ctl_set_success(ctsio);
8460	ctl_done((union ctl_io *)ctsio);
8461
8462	return (retval);
8463}
8464
8465/*
8466 * This routine is for handling a message from the other SC pertaining to
8467 * persistent reserve out. All the error checking will have been done
8468 * so only perorming the action need be done here to keep the two
8469 * in sync.
8470 */
8471static void
8472ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg)
8473{
8474	struct ctl_lun *lun;
8475	struct ctl_softc *softc;
8476	int i;
8477	uint32_t targ_lun;
8478
8479	softc = control_softc;
8480
8481	targ_lun = msg->hdr.nexus.targ_mapped_lun;
8482	lun = softc->ctl_luns[targ_lun];
8483	mtx_lock(&lun->lun_lock);
8484	switch(msg->pr.pr_info.action) {
8485	case CTL_PR_REG_KEY:
8486		if (!lun->per_res[msg->pr.pr_info.residx].registered) {
8487			lun->per_res[msg->pr.pr_info.residx].registered = 1;
8488			lun->pr_key_count++;
8489		}
8490		lun->PRGeneration++;
8491		memcpy(&lun->per_res[msg->pr.pr_info.residx].res_key,
8492		       msg->pr.pr_info.sa_res_key,
8493		       sizeof(struct scsi_per_res_key));
8494		break;
8495
8496	case CTL_PR_UNREG_KEY:
8497		lun->per_res[msg->pr.pr_info.residx].registered = 0;
8498		memset(&lun->per_res[msg->pr.pr_info.residx].res_key,
8499		       0, sizeof(struct scsi_per_res_key));
8500		lun->pr_key_count--;
8501
8502		/* XXX Need to see if the reservation has been released */
8503		/* if so do we need to generate UA? */
8504		if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8505			lun->flags &= ~CTL_LUN_PR_RESERVED;
8506			lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8507
8508			if ((lun->res_type == SPR_TYPE_WR_EX_RO
8509			  || lun->res_type == SPR_TYPE_EX_AC_RO)
8510			 && lun->pr_key_count) {
8511				/*
8512				 * If the reservation is a registrants
8513				 * only type we need to generate a UA
8514				 * for other registered inits.  The
8515				 * sense code should be RESERVATIONS
8516				 * RELEASED
8517				 */
8518
8519				for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8520					if (lun->per_res[i+
8521					    persis_offset].registered == 0)
8522						continue;
8523
8524					lun->pending_sense[i
8525						].ua_pending |=
8526						CTL_UA_RES_RELEASE;
8527				}
8528			}
8529			lun->res_type = 0;
8530		} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8531			if (lun->pr_key_count==0) {
8532				lun->flags &= ~CTL_LUN_PR_RESERVED;
8533				lun->res_type = 0;
8534				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8535			}
8536		}
8537		lun->PRGeneration++;
8538		break;
8539
8540	case CTL_PR_RESERVE:
8541		lun->flags |= CTL_LUN_PR_RESERVED;
8542		lun->res_type = msg->pr.pr_info.res_type;
8543		lun->pr_res_idx = msg->pr.pr_info.residx;
8544
8545		break;
8546
8547	case CTL_PR_RELEASE:
8548		/*
8549		 * if this isn't an exclusive access res generate UA for all
8550		 * other registrants.
8551		 */
8552		if (lun->res_type != SPR_TYPE_EX_AC
8553		 && lun->res_type != SPR_TYPE_WR_EX) {
8554			for (i = 0; i < CTL_MAX_INITIATORS; i++)
8555				if (lun->per_res[i+persis_offset].registered)
8556					lun->pending_sense[i].ua_pending |=
8557						CTL_UA_RES_RELEASE;
8558		}
8559
8560		lun->flags &= ~CTL_LUN_PR_RESERVED;
8561		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8562		lun->res_type = 0;
8563		break;
8564
8565	case CTL_PR_PREEMPT:
8566		ctl_pro_preempt_other(lun, msg);
8567		break;
8568	case CTL_PR_CLEAR:
8569		lun->flags &= ~CTL_LUN_PR_RESERVED;
8570		lun->res_type = 0;
8571		lun->pr_key_count = 0;
8572		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8573
8574		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8575			if (lun->per_res[i].registered == 0)
8576				continue;
8577			if (!persis_offset
8578			 && i < CTL_MAX_INITIATORS)
8579				lun->pending_sense[i].ua_pending |=
8580					CTL_UA_RES_PREEMPT;
8581			else if (persis_offset
8582			      && i >= persis_offset)
8583   				lun->pending_sense[i-persis_offset].ua_pending|=
8584					CTL_UA_RES_PREEMPT;
8585			memset(&lun->per_res[i].res_key, 0,
8586			       sizeof(struct scsi_per_res_key));
8587			lun->per_res[i].registered = 0;
8588		}
8589		lun->PRGeneration++;
8590		break;
8591	}
8592
8593	mtx_unlock(&lun->lun_lock);
8594}
8595
8596int
8597ctl_read_write(struct ctl_scsiio *ctsio)
8598{
8599	struct ctl_lun *lun;
8600	struct ctl_lba_len_flags *lbalen;
8601	uint64_t lba;
8602	uint32_t num_blocks;
8603	int reladdr, fua, dpo, ebp;
8604	int retval;
8605	int isread;
8606
8607	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8608
8609	CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8610
8611	reladdr = 0;
8612	fua = 0;
8613	dpo = 0;
8614	ebp = 0;
8615
8616	retval = CTL_RETVAL_COMPLETE;
8617
8618	isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8619	      || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8620	if (lun->flags & CTL_LUN_PR_RESERVED && isread) {
8621		uint32_t residx;
8622
8623		/*
8624		 * XXX KDM need a lock here.
8625		 */
8626		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
8627		if ((lun->res_type == SPR_TYPE_EX_AC
8628		  && residx != lun->pr_res_idx)
8629		 || ((lun->res_type == SPR_TYPE_EX_AC_RO
8630		   || lun->res_type == SPR_TYPE_EX_AC_AR)
8631		  && !lun->per_res[residx].registered)) {
8632			ctl_set_reservation_conflict(ctsio);
8633			ctl_done((union ctl_io *)ctsio);
8634			return (CTL_RETVAL_COMPLETE);
8635	        }
8636	}
8637
8638	switch (ctsio->cdb[0]) {
8639	case READ_6:
8640	case WRITE_6: {
8641		struct scsi_rw_6 *cdb;
8642
8643		cdb = (struct scsi_rw_6 *)ctsio->cdb;
8644
8645		lba = scsi_3btoul(cdb->addr);
8646		/* only 5 bits are valid in the most significant address byte */
8647		lba &= 0x1fffff;
8648		num_blocks = cdb->length;
8649		/*
8650		 * This is correct according to SBC-2.
8651		 */
8652		if (num_blocks == 0)
8653			num_blocks = 256;
8654		break;
8655	}
8656	case READ_10:
8657	case WRITE_10: {
8658		struct scsi_rw_10 *cdb;
8659
8660		cdb = (struct scsi_rw_10 *)ctsio->cdb;
8661
8662		if (cdb->byte2 & SRW10_RELADDR)
8663			reladdr = 1;
8664		if (cdb->byte2 & SRW10_FUA)
8665			fua = 1;
8666		if (cdb->byte2 & SRW10_DPO)
8667			dpo = 1;
8668
8669		if ((cdb->opcode == WRITE_10)
8670		 && (cdb->byte2 & SRW10_EBP))
8671			ebp = 1;
8672
8673		lba = scsi_4btoul(cdb->addr);
8674		num_blocks = scsi_2btoul(cdb->length);
8675		break;
8676	}
8677	case WRITE_VERIFY_10: {
8678		struct scsi_write_verify_10 *cdb;
8679
8680		cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
8681
8682		/*
8683		 * XXX KDM we should do actual write verify support at some
8684		 * point.  This is obviously fake, we're just translating
8685		 * things to a write.  So we don't even bother checking the
8686		 * BYTCHK field, since we don't do any verification.  If
8687		 * the user asks for it, we'll just pretend we did it.
8688		 */
8689		if (cdb->byte2 & SWV_DPO)
8690			dpo = 1;
8691
8692		lba = scsi_4btoul(cdb->addr);
8693		num_blocks = scsi_2btoul(cdb->length);
8694		break;
8695	}
8696	case READ_12:
8697	case WRITE_12: {
8698		struct scsi_rw_12 *cdb;
8699
8700		cdb = (struct scsi_rw_12 *)ctsio->cdb;
8701
8702		if (cdb->byte2 & SRW12_RELADDR)
8703			reladdr = 1;
8704		if (cdb->byte2 & SRW12_FUA)
8705			fua = 1;
8706		if (cdb->byte2 & SRW12_DPO)
8707			dpo = 1;
8708		lba = scsi_4btoul(cdb->addr);
8709		num_blocks = scsi_4btoul(cdb->length);
8710		break;
8711	}
8712	case WRITE_VERIFY_12: {
8713		struct scsi_write_verify_12 *cdb;
8714
8715		cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
8716
8717		if (cdb->byte2 & SWV_DPO)
8718			dpo = 1;
8719
8720		lba = scsi_4btoul(cdb->addr);
8721		num_blocks = scsi_4btoul(cdb->length);
8722
8723		break;
8724	}
8725	case READ_16:
8726	case WRITE_16: {
8727		struct scsi_rw_16 *cdb;
8728
8729		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8730
8731		if (cdb->byte2 & SRW12_RELADDR)
8732			reladdr = 1;
8733		if (cdb->byte2 & SRW12_FUA)
8734			fua = 1;
8735		if (cdb->byte2 & SRW12_DPO)
8736			dpo = 1;
8737
8738		lba = scsi_8btou64(cdb->addr);
8739		num_blocks = scsi_4btoul(cdb->length);
8740		break;
8741	}
8742	case WRITE_VERIFY_16: {
8743		struct scsi_write_verify_16 *cdb;
8744
8745		cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
8746
8747		if (cdb->byte2 & SWV_DPO)
8748			dpo = 1;
8749
8750		lba = scsi_8btou64(cdb->addr);
8751		num_blocks = scsi_4btoul(cdb->length);
8752		break;
8753	}
8754	default:
8755		/*
8756		 * We got a command we don't support.  This shouldn't
8757		 * happen, commands should be filtered out above us.
8758		 */
8759		ctl_set_invalid_opcode(ctsio);
8760		ctl_done((union ctl_io *)ctsio);
8761
8762		return (CTL_RETVAL_COMPLETE);
8763		break; /* NOTREACHED */
8764	}
8765
8766	/*
8767	 * XXX KDM what do we do with the DPO and FUA bits?  FUA might be
8768	 * interesting for us, but if RAIDCore is in write-back mode,
8769	 * getting it to do write-through for a particular transaction may
8770	 * not be possible.
8771	 */
8772	/*
8773	 * We don't support relative addressing.  That also requires
8774	 * supporting linked commands, which we don't do.
8775	 */
8776	if (reladdr != 0) {
8777		ctl_set_invalid_field(ctsio,
8778				      /*sks_valid*/ 1,
8779				      /*command*/ 1,
8780				      /*field*/ 1,
8781				      /*bit_valid*/ 1,
8782				      /*bit*/ 0);
8783		ctl_done((union ctl_io *)ctsio);
8784		return (CTL_RETVAL_COMPLETE);
8785	}
8786
8787	/*
8788	 * The first check is to make sure we're in bounds, the second
8789	 * check is to catch wrap-around problems.  If the lba + num blocks
8790	 * is less than the lba, then we've wrapped around and the block
8791	 * range is invalid anyway.
8792	 */
8793	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8794	 || ((lba + num_blocks) < lba)) {
8795		ctl_set_lba_out_of_range(ctsio);
8796		ctl_done((union ctl_io *)ctsio);
8797		return (CTL_RETVAL_COMPLETE);
8798	}
8799
8800	/*
8801	 * According to SBC-3, a transfer length of 0 is not an error.
8802	 * Note that this cannot happen with WRITE(6) or READ(6), since 0
8803	 * translates to 256 blocks for those commands.
8804	 */
8805	if (num_blocks == 0) {
8806		ctl_set_success(ctsio);
8807		ctl_done((union ctl_io *)ctsio);
8808		return (CTL_RETVAL_COMPLETE);
8809	}
8810
8811	lbalen = (struct ctl_lba_len_flags *)
8812	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8813	lbalen->lba = lba;
8814	lbalen->len = num_blocks;
8815	lbalen->flags = isread ? CTL_LLF_READ : CTL_LLF_WRITE;
8816
8817	ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
8818	ctsio->kern_rel_offset = 0;
8819
8820	CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
8821
8822	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8823
8824	return (retval);
8825}
8826
8827static int
8828ctl_cnw_cont(union ctl_io *io)
8829{
8830	struct ctl_scsiio *ctsio;
8831	struct ctl_lun *lun;
8832	struct ctl_lba_len_flags *lbalen;
8833	int retval;
8834
8835	ctsio = &io->scsiio;
8836	ctsio->io_hdr.status = CTL_STATUS_NONE;
8837	ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
8838	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8839	lbalen = (struct ctl_lba_len_flags *)
8840	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8841	lbalen->flags = CTL_LLF_WRITE;
8842
8843	CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
8844	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8845	return (retval);
8846}
8847
8848int
8849ctl_cnw(struct ctl_scsiio *ctsio)
8850{
8851	struct ctl_lun *lun;
8852	struct ctl_lba_len_flags *lbalen;
8853	uint64_t lba;
8854	uint32_t num_blocks;
8855	int fua, dpo;
8856	int retval;
8857
8858	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8859
8860	CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
8861
8862	fua = 0;
8863	dpo = 0;
8864
8865	retval = CTL_RETVAL_COMPLETE;
8866
8867	switch (ctsio->cdb[0]) {
8868	case COMPARE_AND_WRITE: {
8869		struct scsi_compare_and_write *cdb;
8870
8871		cdb = (struct scsi_compare_and_write *)ctsio->cdb;
8872
8873		if (cdb->byte2 & SRW10_FUA)
8874			fua = 1;
8875		if (cdb->byte2 & SRW10_DPO)
8876			dpo = 1;
8877		lba = scsi_8btou64(cdb->addr);
8878		num_blocks = cdb->length;
8879		break;
8880	}
8881	default:
8882		/*
8883		 * We got a command we don't support.  This shouldn't
8884		 * happen, commands should be filtered out above us.
8885		 */
8886		ctl_set_invalid_opcode(ctsio);
8887		ctl_done((union ctl_io *)ctsio);
8888
8889		return (CTL_RETVAL_COMPLETE);
8890		break; /* NOTREACHED */
8891	}
8892
8893	/*
8894	 * XXX KDM what do we do with the DPO and FUA bits?  FUA might be
8895	 * interesting for us, but if RAIDCore is in write-back mode,
8896	 * getting it to do write-through for a particular transaction may
8897	 * not be possible.
8898	 */
8899
8900	/*
8901	 * The first check is to make sure we're in bounds, the second
8902	 * check is to catch wrap-around problems.  If the lba + num blocks
8903	 * is less than the lba, then we've wrapped around and the block
8904	 * range is invalid anyway.
8905	 */
8906	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8907	 || ((lba + num_blocks) < lba)) {
8908		ctl_set_lba_out_of_range(ctsio);
8909		ctl_done((union ctl_io *)ctsio);
8910		return (CTL_RETVAL_COMPLETE);
8911	}
8912
8913	/*
8914	 * According to SBC-3, a transfer length of 0 is not an error.
8915	 */
8916	if (num_blocks == 0) {
8917		ctl_set_success(ctsio);
8918		ctl_done((union ctl_io *)ctsio);
8919		return (CTL_RETVAL_COMPLETE);
8920	}
8921
8922	ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
8923	ctsio->kern_rel_offset = 0;
8924
8925	/*
8926	 * Set the IO_CONT flag, so that if this I/O gets passed to
8927	 * ctl_data_submit_done(), it'll get passed back to
8928	 * ctl_ctl_cnw_cont() for further processing.
8929	 */
8930	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
8931	ctsio->io_cont = ctl_cnw_cont;
8932
8933	lbalen = (struct ctl_lba_len_flags *)
8934	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8935	lbalen->lba = lba;
8936	lbalen->len = num_blocks;
8937	lbalen->flags = CTL_LLF_COMPARE;
8938
8939	CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
8940	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8941	return (retval);
8942}
8943
8944int
8945ctl_verify(struct ctl_scsiio *ctsio)
8946{
8947	struct ctl_lun *lun;
8948	struct ctl_lba_len_flags *lbalen;
8949	uint64_t lba;
8950	uint32_t num_blocks;
8951	int bytchk, dpo;
8952	int retval;
8953
8954	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8955
8956	CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
8957
8958	bytchk = 0;
8959	dpo = 0;
8960	retval = CTL_RETVAL_COMPLETE;
8961
8962	switch (ctsio->cdb[0]) {
8963	case VERIFY_10: {
8964		struct scsi_verify_10 *cdb;
8965
8966		cdb = (struct scsi_verify_10 *)ctsio->cdb;
8967		if (cdb->byte2 & SVFY_BYTCHK)
8968			bytchk = 1;
8969		if (cdb->byte2 & SVFY_DPO)
8970			dpo = 1;
8971		lba = scsi_4btoul(cdb->addr);
8972		num_blocks = scsi_2btoul(cdb->length);
8973		break;
8974	}
8975	case VERIFY_12: {
8976		struct scsi_verify_12 *cdb;
8977
8978		cdb = (struct scsi_verify_12 *)ctsio->cdb;
8979		if (cdb->byte2 & SVFY_BYTCHK)
8980			bytchk = 1;
8981		if (cdb->byte2 & SVFY_DPO)
8982			dpo = 1;
8983		lba = scsi_4btoul(cdb->addr);
8984		num_blocks = scsi_4btoul(cdb->length);
8985		break;
8986	}
8987	case VERIFY_16: {
8988		struct scsi_rw_16 *cdb;
8989
8990		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8991		if (cdb->byte2 & SVFY_BYTCHK)
8992			bytchk = 1;
8993		if (cdb->byte2 & SVFY_DPO)
8994			dpo = 1;
8995		lba = scsi_8btou64(cdb->addr);
8996		num_blocks = scsi_4btoul(cdb->length);
8997		break;
8998	}
8999	default:
9000		/*
9001		 * We got a command we don't support.  This shouldn't
9002		 * happen, commands should be filtered out above us.
9003		 */
9004		ctl_set_invalid_opcode(ctsio);
9005		ctl_done((union ctl_io *)ctsio);
9006		return (CTL_RETVAL_COMPLETE);
9007	}
9008
9009	/*
9010	 * The first check is to make sure we're in bounds, the second
9011	 * check is to catch wrap-around problems.  If the lba + num blocks
9012	 * is less than the lba, then we've wrapped around and the block
9013	 * range is invalid anyway.
9014	 */
9015	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9016	 || ((lba + num_blocks) < lba)) {
9017		ctl_set_lba_out_of_range(ctsio);
9018		ctl_done((union ctl_io *)ctsio);
9019		return (CTL_RETVAL_COMPLETE);
9020	}
9021
9022	/*
9023	 * According to SBC-3, a transfer length of 0 is not an error.
9024	 */
9025	if (num_blocks == 0) {
9026		ctl_set_success(ctsio);
9027		ctl_done((union ctl_io *)ctsio);
9028		return (CTL_RETVAL_COMPLETE);
9029	}
9030
9031	lbalen = (struct ctl_lba_len_flags *)
9032	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9033	lbalen->lba = lba;
9034	lbalen->len = num_blocks;
9035	if (bytchk) {
9036		lbalen->flags = CTL_LLF_COMPARE;
9037		ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9038	} else {
9039		lbalen->flags = CTL_LLF_VERIFY;
9040		ctsio->kern_total_len = 0;
9041	}
9042	ctsio->kern_rel_offset = 0;
9043
9044	CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9045	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9046	return (retval);
9047}
9048
9049int
9050ctl_report_luns(struct ctl_scsiio *ctsio)
9051{
9052	struct scsi_report_luns *cdb;
9053	struct scsi_report_luns_data *lun_data;
9054	struct ctl_lun *lun, *request_lun;
9055	int num_luns, retval;
9056	uint32_t alloc_len, lun_datalen;
9057	int num_filled, well_known;
9058	uint32_t initidx, targ_lun_id, lun_id;
9059
9060	retval = CTL_RETVAL_COMPLETE;
9061	well_known = 0;
9062
9063	cdb = (struct scsi_report_luns *)ctsio->cdb;
9064
9065	CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9066
9067	mtx_lock(&control_softc->ctl_lock);
9068	num_luns = control_softc->num_luns;
9069	mtx_unlock(&control_softc->ctl_lock);
9070
9071	switch (cdb->select_report) {
9072	case RPL_REPORT_DEFAULT:
9073	case RPL_REPORT_ALL:
9074		break;
9075	case RPL_REPORT_WELLKNOWN:
9076		well_known = 1;
9077		num_luns = 0;
9078		break;
9079	default:
9080		ctl_set_invalid_field(ctsio,
9081				      /*sks_valid*/ 1,
9082				      /*command*/ 1,
9083				      /*field*/ 2,
9084				      /*bit_valid*/ 0,
9085				      /*bit*/ 0);
9086		ctl_done((union ctl_io *)ctsio);
9087		return (retval);
9088		break; /* NOTREACHED */
9089	}
9090
9091	alloc_len = scsi_4btoul(cdb->length);
9092	/*
9093	 * The initiator has to allocate at least 16 bytes for this request,
9094	 * so he can at least get the header and the first LUN.  Otherwise
9095	 * we reject the request (per SPC-3 rev 14, section 6.21).
9096	 */
9097	if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9098	    sizeof(struct scsi_report_luns_lundata))) {
9099		ctl_set_invalid_field(ctsio,
9100				      /*sks_valid*/ 1,
9101				      /*command*/ 1,
9102				      /*field*/ 6,
9103				      /*bit_valid*/ 0,
9104				      /*bit*/ 0);
9105		ctl_done((union ctl_io *)ctsio);
9106		return (retval);
9107	}
9108
9109	request_lun = (struct ctl_lun *)
9110		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9111
9112	lun_datalen = sizeof(*lun_data) +
9113		(num_luns * sizeof(struct scsi_report_luns_lundata));
9114
9115	ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9116	lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9117	ctsio->kern_sg_entries = 0;
9118
9119	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9120
9121	mtx_lock(&control_softc->ctl_lock);
9122	for (targ_lun_id = 0, num_filled = 0; targ_lun_id < CTL_MAX_LUNS && num_filled < num_luns; targ_lun_id++) {
9123		lun_id = targ_lun_id;
9124		if (ctsio->io_hdr.nexus.lun_map_fn != NULL)
9125			lun_id = ctsio->io_hdr.nexus.lun_map_fn(ctsio->io_hdr.nexus.lun_map_arg, lun_id);
9126		if (lun_id >= CTL_MAX_LUNS)
9127			continue;
9128		lun = control_softc->ctl_luns[lun_id];
9129		if (lun == NULL)
9130			continue;
9131
9132		if (targ_lun_id <= 0xff) {
9133			/*
9134			 * Peripheral addressing method, bus number 0.
9135			 */
9136			lun_data->luns[num_filled].lundata[0] =
9137				RPL_LUNDATA_ATYP_PERIPH;
9138			lun_data->luns[num_filled].lundata[1] = targ_lun_id;
9139			num_filled++;
9140		} else if (targ_lun_id <= 0x3fff) {
9141			/*
9142			 * Flat addressing method.
9143			 */
9144			lun_data->luns[num_filled].lundata[0] =
9145				RPL_LUNDATA_ATYP_FLAT |
9146				(targ_lun_id & RPL_LUNDATA_FLAT_LUN_MASK);
9147#ifdef OLDCTLHEADERS
9148				(SRLD_ADDR_FLAT << SRLD_ADDR_SHIFT) |
9149				(targ_lun_id & SRLD_BUS_LUN_MASK);
9150#endif
9151			lun_data->luns[num_filled].lundata[1] =
9152#ifdef OLDCTLHEADERS
9153				targ_lun_id >> SRLD_BUS_LUN_BITS;
9154#endif
9155				targ_lun_id >> RPL_LUNDATA_FLAT_LUN_BITS;
9156			num_filled++;
9157		} else {
9158			printf("ctl_report_luns: bogus LUN number %jd, "
9159			       "skipping\n", (intmax_t)targ_lun_id);
9160		}
9161		/*
9162		 * According to SPC-3, rev 14 section 6.21:
9163		 *
9164		 * "The execution of a REPORT LUNS command to any valid and
9165		 * installed logical unit shall clear the REPORTED LUNS DATA
9166		 * HAS CHANGED unit attention condition for all logical
9167		 * units of that target with respect to the requesting
9168		 * initiator. A valid and installed logical unit is one
9169		 * having a PERIPHERAL QUALIFIER of 000b in the standard
9170		 * INQUIRY data (see 6.4.2)."
9171		 *
9172		 * If request_lun is NULL, the LUN this report luns command
9173		 * was issued to is either disabled or doesn't exist. In that
9174		 * case, we shouldn't clear any pending lun change unit
9175		 * attention.
9176		 */
9177		if (request_lun != NULL) {
9178			mtx_lock(&lun->lun_lock);
9179			lun->pending_sense[initidx].ua_pending &=
9180				~CTL_UA_LUN_CHANGE;
9181			mtx_unlock(&lun->lun_lock);
9182		}
9183	}
9184	mtx_unlock(&control_softc->ctl_lock);
9185
9186	/*
9187	 * It's quite possible that we've returned fewer LUNs than we allocated
9188	 * space for.  Trim it.
9189	 */
9190	lun_datalen = sizeof(*lun_data) +
9191		(num_filled * sizeof(struct scsi_report_luns_lundata));
9192
9193	if (lun_datalen < alloc_len) {
9194		ctsio->residual = alloc_len - lun_datalen;
9195		ctsio->kern_data_len = lun_datalen;
9196		ctsio->kern_total_len = lun_datalen;
9197	} else {
9198		ctsio->residual = 0;
9199		ctsio->kern_data_len = alloc_len;
9200		ctsio->kern_total_len = alloc_len;
9201	}
9202	ctsio->kern_data_resid = 0;
9203	ctsio->kern_rel_offset = 0;
9204	ctsio->kern_sg_entries = 0;
9205
9206	/*
9207	 * We set this to the actual data length, regardless of how much
9208	 * space we actually have to return results.  If the user looks at
9209	 * this value, he'll know whether or not he allocated enough space
9210	 * and reissue the command if necessary.  We don't support well
9211	 * known logical units, so if the user asks for that, return none.
9212	 */
9213	scsi_ulto4b(lun_datalen - 8, lun_data->length);
9214
9215	/*
9216	 * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9217	 * this request.
9218	 */
9219	ctsio->scsi_status = SCSI_STATUS_OK;
9220
9221	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9222	ctsio->be_move_done = ctl_config_move_done;
9223	ctl_datamove((union ctl_io *)ctsio);
9224
9225	return (retval);
9226}
9227
9228int
9229ctl_request_sense(struct ctl_scsiio *ctsio)
9230{
9231	struct scsi_request_sense *cdb;
9232	struct scsi_sense_data *sense_ptr;
9233	struct ctl_lun *lun;
9234	uint32_t initidx;
9235	int have_error;
9236	scsi_sense_data_type sense_format;
9237
9238	cdb = (struct scsi_request_sense *)ctsio->cdb;
9239
9240	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9241
9242	CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9243
9244	/*
9245	 * Determine which sense format the user wants.
9246	 */
9247	if (cdb->byte2 & SRS_DESC)
9248		sense_format = SSD_TYPE_DESC;
9249	else
9250		sense_format = SSD_TYPE_FIXED;
9251
9252	ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9253	sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9254	ctsio->kern_sg_entries = 0;
9255
9256	/*
9257	 * struct scsi_sense_data, which is currently set to 256 bytes, is
9258	 * larger than the largest allowed value for the length field in the
9259	 * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9260	 */
9261	ctsio->residual = 0;
9262	ctsio->kern_data_len = cdb->length;
9263	ctsio->kern_total_len = cdb->length;
9264
9265	ctsio->kern_data_resid = 0;
9266	ctsio->kern_rel_offset = 0;
9267	ctsio->kern_sg_entries = 0;
9268
9269	/*
9270	 * If we don't have a LUN, we don't have any pending sense.
9271	 */
9272	if (lun == NULL)
9273		goto no_sense;
9274
9275	have_error = 0;
9276	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9277	/*
9278	 * Check for pending sense, and then for pending unit attentions.
9279	 * Pending sense gets returned first, then pending unit attentions.
9280	 */
9281	mtx_lock(&lun->lun_lock);
9282	if (ctl_is_set(lun->have_ca, initidx)) {
9283		scsi_sense_data_type stored_format;
9284
9285		/*
9286		 * Check to see which sense format was used for the stored
9287		 * sense data.
9288		 */
9289		stored_format = scsi_sense_type(
9290		    &lun->pending_sense[initidx].sense);
9291
9292		/*
9293		 * If the user requested a different sense format than the
9294		 * one we stored, then we need to convert it to the other
9295		 * format.  If we're going from descriptor to fixed format
9296		 * sense data, we may lose things in translation, depending
9297		 * on what options were used.
9298		 *
9299		 * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9300		 * for some reason we'll just copy it out as-is.
9301		 */
9302		if ((stored_format == SSD_TYPE_FIXED)
9303		 && (sense_format == SSD_TYPE_DESC))
9304			ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9305			    &lun->pending_sense[initidx].sense,
9306			    (struct scsi_sense_data_desc *)sense_ptr);
9307		else if ((stored_format == SSD_TYPE_DESC)
9308		      && (sense_format == SSD_TYPE_FIXED))
9309			ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9310			    &lun->pending_sense[initidx].sense,
9311			    (struct scsi_sense_data_fixed *)sense_ptr);
9312		else
9313			memcpy(sense_ptr, &lun->pending_sense[initidx].sense,
9314			       ctl_min(sizeof(*sense_ptr),
9315			       sizeof(lun->pending_sense[initidx].sense)));
9316
9317		ctl_clear_mask(lun->have_ca, initidx);
9318		have_error = 1;
9319	} else if (lun->pending_sense[initidx].ua_pending != CTL_UA_NONE) {
9320		ctl_ua_type ua_type;
9321
9322		ua_type = ctl_build_ua(lun->pending_sense[initidx].ua_pending,
9323				       sense_ptr, sense_format);
9324		if (ua_type != CTL_UA_NONE) {
9325			have_error = 1;
9326			/* We're reporting this UA, so clear it */
9327			lun->pending_sense[initidx].ua_pending &= ~ua_type;
9328		}
9329	}
9330	mtx_unlock(&lun->lun_lock);
9331
9332	/*
9333	 * We already have a pending error, return it.
9334	 */
9335	if (have_error != 0) {
9336		/*
9337		 * We report the SCSI status as OK, since the status of the
9338		 * request sense command itself is OK.
9339		 */
9340		ctsio->scsi_status = SCSI_STATUS_OK;
9341
9342		/*
9343		 * We report 0 for the sense length, because we aren't doing
9344		 * autosense in this case.  We're reporting sense as
9345		 * parameter data.
9346		 */
9347		ctsio->sense_len = 0;
9348		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9349		ctsio->be_move_done = ctl_config_move_done;
9350		ctl_datamove((union ctl_io *)ctsio);
9351
9352		return (CTL_RETVAL_COMPLETE);
9353	}
9354
9355no_sense:
9356
9357	/*
9358	 * No sense information to report, so we report that everything is
9359	 * okay.
9360	 */
9361	ctl_set_sense_data(sense_ptr,
9362			   lun,
9363			   sense_format,
9364			   /*current_error*/ 1,
9365			   /*sense_key*/ SSD_KEY_NO_SENSE,
9366			   /*asc*/ 0x00,
9367			   /*ascq*/ 0x00,
9368			   SSD_ELEM_NONE);
9369
9370	ctsio->scsi_status = SCSI_STATUS_OK;
9371
9372	/*
9373	 * We report 0 for the sense length, because we aren't doing
9374	 * autosense in this case.  We're reporting sense as parameter data.
9375	 */
9376	ctsio->sense_len = 0;
9377	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9378	ctsio->be_move_done = ctl_config_move_done;
9379	ctl_datamove((union ctl_io *)ctsio);
9380
9381	return (CTL_RETVAL_COMPLETE);
9382}
9383
9384int
9385ctl_tur(struct ctl_scsiio *ctsio)
9386{
9387	struct ctl_lun *lun;
9388
9389	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9390
9391	CTL_DEBUG_PRINT(("ctl_tur\n"));
9392
9393	if (lun == NULL)
9394		return (EINVAL);
9395
9396	ctsio->scsi_status = SCSI_STATUS_OK;
9397	ctsio->io_hdr.status = CTL_SUCCESS;
9398
9399	ctl_done((union ctl_io *)ctsio);
9400
9401	return (CTL_RETVAL_COMPLETE);
9402}
9403
9404#ifdef notyet
9405static int
9406ctl_cmddt_inquiry(struct ctl_scsiio *ctsio)
9407{
9408
9409}
9410#endif
9411
9412static int
9413ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9414{
9415	struct scsi_vpd_supported_pages *pages;
9416	int sup_page_size;
9417	struct ctl_lun *lun;
9418
9419	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9420
9421	sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9422	    SCSI_EVPD_NUM_SUPPORTED_PAGES;
9423	ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9424	pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9425	ctsio->kern_sg_entries = 0;
9426
9427	if (sup_page_size < alloc_len) {
9428		ctsio->residual = alloc_len - sup_page_size;
9429		ctsio->kern_data_len = sup_page_size;
9430		ctsio->kern_total_len = sup_page_size;
9431	} else {
9432		ctsio->residual = 0;
9433		ctsio->kern_data_len = alloc_len;
9434		ctsio->kern_total_len = alloc_len;
9435	}
9436	ctsio->kern_data_resid = 0;
9437	ctsio->kern_rel_offset = 0;
9438	ctsio->kern_sg_entries = 0;
9439
9440	/*
9441	 * The control device is always connected.  The disk device, on the
9442	 * other hand, may not be online all the time.  Need to change this
9443	 * to figure out whether the disk device is actually online or not.
9444	 */
9445	if (lun != NULL)
9446		pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9447				lun->be_lun->lun_type;
9448	else
9449		pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9450
9451	pages->length = SCSI_EVPD_NUM_SUPPORTED_PAGES;
9452	/* Supported VPD pages */
9453	pages->page_list[0] = SVPD_SUPPORTED_PAGES;
9454	/* Serial Number */
9455	pages->page_list[1] = SVPD_UNIT_SERIAL_NUMBER;
9456	/* Device Identification */
9457	pages->page_list[2] = SVPD_DEVICE_ID;
9458	/* Block limits */
9459	pages->page_list[3] = SVPD_BLOCK_LIMITS;
9460	/* Logical Block Provisioning */
9461	pages->page_list[4] = SVPD_LBP;
9462
9463	ctsio->scsi_status = SCSI_STATUS_OK;
9464
9465	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9466	ctsio->be_move_done = ctl_config_move_done;
9467	ctl_datamove((union ctl_io *)ctsio);
9468
9469	return (CTL_RETVAL_COMPLETE);
9470}
9471
9472static int
9473ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9474{
9475	struct scsi_vpd_unit_serial_number *sn_ptr;
9476	struct ctl_lun *lun;
9477
9478	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9479
9480	ctsio->kern_data_ptr = malloc(sizeof(*sn_ptr), M_CTL, M_WAITOK | M_ZERO);
9481	sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9482	ctsio->kern_sg_entries = 0;
9483
9484	if (sizeof(*sn_ptr) < alloc_len) {
9485		ctsio->residual = alloc_len - sizeof(*sn_ptr);
9486		ctsio->kern_data_len = sizeof(*sn_ptr);
9487		ctsio->kern_total_len = sizeof(*sn_ptr);
9488	} else {
9489		ctsio->residual = 0;
9490		ctsio->kern_data_len = alloc_len;
9491		ctsio->kern_total_len = alloc_len;
9492	}
9493	ctsio->kern_data_resid = 0;
9494	ctsio->kern_rel_offset = 0;
9495	ctsio->kern_sg_entries = 0;
9496
9497	/*
9498	 * The control device is always connected.  The disk device, on the
9499	 * other hand, may not be online all the time.  Need to change this
9500	 * to figure out whether the disk device is actually online or not.
9501	 */
9502	if (lun != NULL)
9503		sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9504				  lun->be_lun->lun_type;
9505	else
9506		sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9507
9508	sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9509	sn_ptr->length = ctl_min(sizeof(*sn_ptr) - 4, CTL_SN_LEN);
9510	/*
9511	 * If we don't have a LUN, we just leave the serial number as
9512	 * all spaces.
9513	 */
9514	memset(sn_ptr->serial_num, 0x20, sizeof(sn_ptr->serial_num));
9515	if (lun != NULL) {
9516		strncpy((char *)sn_ptr->serial_num,
9517			(char *)lun->be_lun->serial_num, CTL_SN_LEN);
9518	}
9519	ctsio->scsi_status = SCSI_STATUS_OK;
9520
9521	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9522	ctsio->be_move_done = ctl_config_move_done;
9523	ctl_datamove((union ctl_io *)ctsio);
9524
9525	return (CTL_RETVAL_COMPLETE);
9526}
9527
9528
9529static int
9530ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9531{
9532	struct scsi_vpd_device_id *devid_ptr;
9533	struct scsi_vpd_id_descriptor *desc, *desc1;
9534	struct scsi_vpd_id_descriptor *desc2, *desc3; /* for types 4h and 5h */
9535	struct scsi_vpd_id_t10 *t10id;
9536	struct ctl_softc *ctl_softc;
9537	struct ctl_lun *lun;
9538	struct ctl_frontend *fe;
9539	char *val;
9540	int data_len, devid_len;
9541
9542	ctl_softc = control_softc;
9543
9544	fe = ctl_softc->ctl_ports[ctl_port_idx(ctsio->io_hdr.nexus.targ_port)];
9545
9546	if (fe->devid != NULL)
9547		return ((fe->devid)(ctsio, alloc_len));
9548
9549	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9550
9551	if (lun == NULL) {
9552		devid_len = CTL_DEVID_MIN_LEN;
9553	} else {
9554		devid_len = max(CTL_DEVID_MIN_LEN,
9555		    strnlen(lun->be_lun->device_id, CTL_DEVID_LEN));
9556	}
9557
9558	data_len = sizeof(struct scsi_vpd_device_id) +
9559		sizeof(struct scsi_vpd_id_descriptor) +
9560		sizeof(struct scsi_vpd_id_t10) + devid_len +
9561		sizeof(struct scsi_vpd_id_descriptor) + CTL_WWPN_LEN +
9562		sizeof(struct scsi_vpd_id_descriptor) +
9563		sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9564		sizeof(struct scsi_vpd_id_descriptor) +
9565		sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9566
9567	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9568	devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9569	ctsio->kern_sg_entries = 0;
9570
9571	if (data_len < alloc_len) {
9572		ctsio->residual = alloc_len - data_len;
9573		ctsio->kern_data_len = data_len;
9574		ctsio->kern_total_len = data_len;
9575	} else {
9576		ctsio->residual = 0;
9577		ctsio->kern_data_len = alloc_len;
9578		ctsio->kern_total_len = alloc_len;
9579	}
9580	ctsio->kern_data_resid = 0;
9581	ctsio->kern_rel_offset = 0;
9582	ctsio->kern_sg_entries = 0;
9583
9584	desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
9585	t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
9586	desc1 = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9587		sizeof(struct scsi_vpd_id_t10) + devid_len);
9588	desc2 = (struct scsi_vpd_id_descriptor *)(&desc1->identifier[0] +
9589	          CTL_WWPN_LEN);
9590	desc3 = (struct scsi_vpd_id_descriptor *)(&desc2->identifier[0] +
9591	         sizeof(struct scsi_vpd_id_rel_trgt_port_id));
9592
9593	/*
9594	 * The control device is always connected.  The disk device, on the
9595	 * other hand, may not be online all the time.
9596	 */
9597	if (lun != NULL)
9598		devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9599				     lun->be_lun->lun_type;
9600	else
9601		devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9602
9603	devid_ptr->page_code = SVPD_DEVICE_ID;
9604
9605	scsi_ulto2b(data_len - 4, devid_ptr->length);
9606
9607	/*
9608	 * For Fibre channel,
9609	 */
9610	if (fe->port_type == CTL_PORT_FC)
9611	{
9612		desc->proto_codeset = (SCSI_PROTO_FC << 4) |
9613				      SVPD_ID_CODESET_ASCII;
9614        	desc1->proto_codeset = (SCSI_PROTO_FC << 4) |
9615		              SVPD_ID_CODESET_BINARY;
9616	}
9617	else
9618	{
9619		desc->proto_codeset = (SCSI_PROTO_SPI << 4) |
9620				      SVPD_ID_CODESET_ASCII;
9621        	desc1->proto_codeset = (SCSI_PROTO_SPI << 4) |
9622		              SVPD_ID_CODESET_BINARY;
9623	}
9624	desc2->proto_codeset = desc3->proto_codeset = desc1->proto_codeset;
9625
9626	/*
9627	 * We're using a LUN association here.  i.e., this device ID is a
9628	 * per-LUN identifier.
9629	 */
9630	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
9631	desc->length = sizeof(*t10id) + devid_len;
9632	if (lun == NULL || (val = ctl_get_opt(lun->be_lun, "vendor")) == NULL) {
9633		strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
9634	} else {
9635		memset(t10id->vendor, ' ', sizeof(t10id->vendor));
9636		strncpy(t10id->vendor, val,
9637		    min(sizeof(t10id->vendor), strlen(val)));
9638	}
9639
9640	/*
9641	 * desc1 is for the WWPN which is a port asscociation.
9642	 */
9643	desc1->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT | SVPD_ID_TYPE_NAA;
9644	desc1->length = CTL_WWPN_LEN;
9645	/* XXX Call Reggie's get_WWNN func here then add port # to the end */
9646	/* For testing just create the WWPN */
9647#if 0
9648	ddb_GetWWNN((char *)desc1->identifier);
9649
9650	/* NOTE: if the port is 0 or 8 we don't want to subtract 1 */
9651	/* This is so Copancontrol will return something sane */
9652	if (ctsio->io_hdr.nexus.targ_port!=0 &&
9653	    ctsio->io_hdr.nexus.targ_port!=8)
9654		desc1->identifier[7] += ctsio->io_hdr.nexus.targ_port-1;
9655	else
9656		desc1->identifier[7] += ctsio->io_hdr.nexus.targ_port;
9657#endif
9658
9659	be64enc(desc1->identifier, fe->wwpn);
9660
9661	/*
9662	 * desc2 is for the Relative Target Port(type 4h) identifier
9663	 */
9664	desc2->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT
9665	                 | SVPD_ID_TYPE_RELTARG;
9666	desc2->length = 4;
9667//#if 0
9668	/* NOTE: if the port is 0 or 8 we don't want to subtract 1 */
9669	/* This is so Copancontrol will return something sane */
9670	if (ctsio->io_hdr.nexus.targ_port!=0 &&
9671	    ctsio->io_hdr.nexus.targ_port!=8)
9672		desc2->identifier[3] = ctsio->io_hdr.nexus.targ_port - 1;
9673	else
9674	        desc2->identifier[3] = ctsio->io_hdr.nexus.targ_port;
9675//#endif
9676
9677	/*
9678	 * desc3 is for the Target Port Group(type 5h) identifier
9679	 */
9680	desc3->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT
9681	                 | SVPD_ID_TYPE_TPORTGRP;
9682	desc3->length = 4;
9683	if (ctsio->io_hdr.nexus.targ_port < CTL_MAX_PORTS || ctl_is_single)
9684		desc3->identifier[3] = 1;
9685	else
9686		desc3->identifier[3] = 2;
9687
9688	/*
9689	 * If we've actually got a backend, copy the device id from the
9690	 * per-LUN data.  Otherwise, set it to all spaces.
9691	 */
9692	if (lun != NULL) {
9693		/*
9694		 * Copy the backend's LUN ID.
9695		 */
9696		strncpy((char *)t10id->vendor_spec_id,
9697			(char *)lun->be_lun->device_id, devid_len);
9698	} else {
9699		/*
9700		 * No backend, set this to spaces.
9701		 */
9702		memset(t10id->vendor_spec_id, 0x20, devid_len);
9703	}
9704
9705	ctsio->scsi_status = SCSI_STATUS_OK;
9706
9707	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9708	ctsio->be_move_done = ctl_config_move_done;
9709	ctl_datamove((union ctl_io *)ctsio);
9710
9711	return (CTL_RETVAL_COMPLETE);
9712}
9713
9714static int
9715ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
9716{
9717	struct scsi_vpd_block_limits *bl_ptr;
9718	struct ctl_lun *lun;
9719	int bs;
9720
9721	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9722	bs = lun->be_lun->blocksize;
9723
9724	ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
9725	bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
9726	ctsio->kern_sg_entries = 0;
9727
9728	if (sizeof(*bl_ptr) < alloc_len) {
9729		ctsio->residual = alloc_len - sizeof(*bl_ptr);
9730		ctsio->kern_data_len = sizeof(*bl_ptr);
9731		ctsio->kern_total_len = sizeof(*bl_ptr);
9732	} else {
9733		ctsio->residual = 0;
9734		ctsio->kern_data_len = alloc_len;
9735		ctsio->kern_total_len = alloc_len;
9736	}
9737	ctsio->kern_data_resid = 0;
9738	ctsio->kern_rel_offset = 0;
9739	ctsio->kern_sg_entries = 0;
9740
9741	/*
9742	 * The control device is always connected.  The disk device, on the
9743	 * other hand, may not be online all the time.  Need to change this
9744	 * to figure out whether the disk device is actually online or not.
9745	 */
9746	if (lun != NULL)
9747		bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9748				  lun->be_lun->lun_type;
9749	else
9750		bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9751
9752	bl_ptr->page_code = SVPD_BLOCK_LIMITS;
9753	scsi_ulto2b(sizeof(*bl_ptr), bl_ptr->page_length);
9754	bl_ptr->max_cmp_write_len = 0xff;
9755	scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
9756	scsi_ulto4b(MAXPHYS / bs, bl_ptr->opt_txfer_len);
9757	if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9758		scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_lba_cnt);
9759		scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_blk_cnt);
9760	}
9761	scsi_u64to8b(UINT64_MAX, bl_ptr->max_write_same_length);
9762
9763	ctsio->scsi_status = SCSI_STATUS_OK;
9764	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9765	ctsio->be_move_done = ctl_config_move_done;
9766	ctl_datamove((union ctl_io *)ctsio);
9767
9768	return (CTL_RETVAL_COMPLETE);
9769}
9770
9771static int
9772ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
9773{
9774	struct scsi_vpd_logical_block_prov *lbp_ptr;
9775	struct ctl_lun *lun;
9776	int bs;
9777
9778	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9779	bs = lun->be_lun->blocksize;
9780
9781	ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
9782	lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
9783	ctsio->kern_sg_entries = 0;
9784
9785	if (sizeof(*lbp_ptr) < alloc_len) {
9786		ctsio->residual = alloc_len - sizeof(*lbp_ptr);
9787		ctsio->kern_data_len = sizeof(*lbp_ptr);
9788		ctsio->kern_total_len = sizeof(*lbp_ptr);
9789	} else {
9790		ctsio->residual = 0;
9791		ctsio->kern_data_len = alloc_len;
9792		ctsio->kern_total_len = alloc_len;
9793	}
9794	ctsio->kern_data_resid = 0;
9795	ctsio->kern_rel_offset = 0;
9796	ctsio->kern_sg_entries = 0;
9797
9798	/*
9799	 * The control device is always connected.  The disk device, on the
9800	 * other hand, may not be online all the time.  Need to change this
9801	 * to figure out whether the disk device is actually online or not.
9802	 */
9803	if (lun != NULL)
9804		lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9805				  lun->be_lun->lun_type;
9806	else
9807		lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9808
9809	lbp_ptr->page_code = SVPD_LBP;
9810	if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
9811		lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 | SVPD_LBP_WS10;
9812
9813	ctsio->scsi_status = SCSI_STATUS_OK;
9814	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9815	ctsio->be_move_done = ctl_config_move_done;
9816	ctl_datamove((union ctl_io *)ctsio);
9817
9818	return (CTL_RETVAL_COMPLETE);
9819}
9820
9821static int
9822ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
9823{
9824	struct scsi_inquiry *cdb;
9825	struct ctl_lun *lun;
9826	int alloc_len, retval;
9827
9828	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9829	cdb = (struct scsi_inquiry *)ctsio->cdb;
9830
9831	retval = CTL_RETVAL_COMPLETE;
9832
9833	alloc_len = scsi_2btoul(cdb->length);
9834
9835	switch (cdb->page_code) {
9836	case SVPD_SUPPORTED_PAGES:
9837		retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
9838		break;
9839	case SVPD_UNIT_SERIAL_NUMBER:
9840		retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
9841		break;
9842	case SVPD_DEVICE_ID:
9843		retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
9844		break;
9845	case SVPD_BLOCK_LIMITS:
9846		retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
9847		break;
9848	case SVPD_LBP:
9849		retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
9850		break;
9851	default:
9852		ctl_set_invalid_field(ctsio,
9853				      /*sks_valid*/ 1,
9854				      /*command*/ 1,
9855				      /*field*/ 2,
9856				      /*bit_valid*/ 0,
9857				      /*bit*/ 0);
9858		ctl_done((union ctl_io *)ctsio);
9859		retval = CTL_RETVAL_COMPLETE;
9860		break;
9861	}
9862
9863	return (retval);
9864}
9865
9866static int
9867ctl_inquiry_std(struct ctl_scsiio *ctsio)
9868{
9869	struct scsi_inquiry_data *inq_ptr;
9870	struct scsi_inquiry *cdb;
9871	struct ctl_softc *ctl_softc;
9872	struct ctl_lun *lun;
9873	char *val;
9874	uint32_t alloc_len;
9875	int is_fc;
9876
9877	ctl_softc = control_softc;
9878
9879	/*
9880	 * Figure out whether we're talking to a Fibre Channel port or not.
9881	 * We treat the ioctl front end, and any SCSI adapters, as packetized
9882	 * SCSI front ends.
9883	 */
9884	if (ctl_softc->ctl_ports[ctl_port_idx(ctsio->io_hdr.nexus.targ_port)]->port_type !=
9885	    CTL_PORT_FC)
9886		is_fc = 0;
9887	else
9888		is_fc = 1;
9889
9890	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9891	cdb = (struct scsi_inquiry *)ctsio->cdb;
9892	alloc_len = scsi_2btoul(cdb->length);
9893
9894	/*
9895	 * We malloc the full inquiry data size here and fill it
9896	 * in.  If the user only asks for less, we'll give him
9897	 * that much.
9898	 */
9899	ctsio->kern_data_ptr = malloc(sizeof(*inq_ptr), M_CTL, M_WAITOK | M_ZERO);
9900	inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
9901	ctsio->kern_sg_entries = 0;
9902	ctsio->kern_data_resid = 0;
9903	ctsio->kern_rel_offset = 0;
9904
9905	if (sizeof(*inq_ptr) < alloc_len) {
9906		ctsio->residual = alloc_len - sizeof(*inq_ptr);
9907		ctsio->kern_data_len = sizeof(*inq_ptr);
9908		ctsio->kern_total_len = sizeof(*inq_ptr);
9909	} else {
9910		ctsio->residual = 0;
9911		ctsio->kern_data_len = alloc_len;
9912		ctsio->kern_total_len = alloc_len;
9913	}
9914
9915	/*
9916	 * If we have a LUN configured, report it as connected.  Otherwise,
9917	 * report that it is offline or no device is supported, depending
9918	 * on the value of inquiry_pq_no_lun.
9919	 *
9920	 * According to the spec (SPC-4 r34), the peripheral qualifier
9921	 * SID_QUAL_LU_OFFLINE (001b) is used in the following scenario:
9922	 *
9923	 * "A peripheral device having the specified peripheral device type
9924	 * is not connected to this logical unit. However, the device
9925	 * server is capable of supporting the specified peripheral device
9926	 * type on this logical unit."
9927	 *
9928	 * According to the same spec, the peripheral qualifier
9929	 * SID_QUAL_BAD_LU (011b) is used in this scenario:
9930	 *
9931	 * "The device server is not capable of supporting a peripheral
9932	 * device on this logical unit. For this peripheral qualifier the
9933	 * peripheral device type shall be set to 1Fh. All other peripheral
9934	 * device type values are reserved for this peripheral qualifier."
9935	 *
9936	 * Given the text, it would seem that we probably want to report that
9937	 * the LUN is offline here.  There is no LUN connected, but we can
9938	 * support a LUN at the given LUN number.
9939	 *
9940	 * In the real world, though, it sounds like things are a little
9941	 * different:
9942	 *
9943	 * - Linux, when presented with a LUN with the offline peripheral
9944	 *   qualifier, will create an sg driver instance for it.  So when
9945	 *   you attach it to CTL, you wind up with a ton of sg driver
9946	 *   instances.  (One for every LUN that Linux bothered to probe.)
9947	 *   Linux does this despite the fact that it issues a REPORT LUNs
9948	 *   to LUN 0 to get the inventory of supported LUNs.
9949	 *
9950	 * - There is other anecdotal evidence (from Emulex folks) about
9951	 *   arrays that use the offline peripheral qualifier for LUNs that
9952	 *   are on the "passive" path in an active/passive array.
9953	 *
9954	 * So the solution is provide a hopefully reasonable default
9955	 * (return bad/no LUN) and allow the user to change the behavior
9956	 * with a tunable/sysctl variable.
9957	 */
9958	if (lun != NULL)
9959		inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9960				  lun->be_lun->lun_type;
9961	else if (ctl_softc->inquiry_pq_no_lun == 0)
9962		inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9963	else
9964		inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
9965
9966	/* RMB in byte 2 is 0 */
9967	inq_ptr->version = SCSI_REV_SPC3;
9968
9969	/*
9970	 * According to SAM-3, even if a device only supports a single
9971	 * level of LUN addressing, it should still set the HISUP bit:
9972	 *
9973	 * 4.9.1 Logical unit numbers overview
9974	 *
9975	 * All logical unit number formats described in this standard are
9976	 * hierarchical in structure even when only a single level in that
9977	 * hierarchy is used. The HISUP bit shall be set to one in the
9978	 * standard INQUIRY data (see SPC-2) when any logical unit number
9979	 * format described in this standard is used.  Non-hierarchical
9980	 * formats are outside the scope of this standard.
9981	 *
9982	 * Therefore we set the HiSup bit here.
9983	 *
9984	 * The reponse format is 2, per SPC-3.
9985	 */
9986	inq_ptr->response_format = SID_HiSup | 2;
9987
9988	inq_ptr->additional_length = sizeof(*inq_ptr) - 4;
9989	CTL_DEBUG_PRINT(("additional_length = %d\n",
9990			 inq_ptr->additional_length));
9991
9992	inq_ptr->spc3_flags = SPC3_SID_TPGS_IMPLICIT;
9993	/* 16 bit addressing */
9994	if (is_fc == 0)
9995		inq_ptr->spc2_flags = SPC2_SID_ADDR16;
9996	/* XXX set the SID_MultiP bit here if we're actually going to
9997	   respond on multiple ports */
9998	inq_ptr->spc2_flags |= SPC2_SID_MultiP;
9999
10000	/* 16 bit data bus, synchronous transfers */
10001	/* XXX these flags don't apply for FC */
10002	if (is_fc == 0)
10003		inq_ptr->flags = SID_WBus16 | SID_Sync;
10004	/*
10005	 * XXX KDM do we want to support tagged queueing on the control
10006	 * device at all?
10007	 */
10008	if ((lun == NULL)
10009	 || (lun->be_lun->lun_type != T_PROCESSOR))
10010		inq_ptr->flags |= SID_CmdQue;
10011	/*
10012	 * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10013	 * We have 8 bytes for the vendor name, and 16 bytes for the device
10014	 * name and 4 bytes for the revision.
10015	 */
10016	if (lun == NULL || (val = ctl_get_opt(lun->be_lun, "vendor")) == NULL) {
10017		strcpy(inq_ptr->vendor, CTL_VENDOR);
10018	} else {
10019		memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10020		strncpy(inq_ptr->vendor, val,
10021		    min(sizeof(inq_ptr->vendor), strlen(val)));
10022	}
10023	if (lun == NULL) {
10024		strcpy(inq_ptr->product, CTL_DIRECT_PRODUCT);
10025	} else if ((val = ctl_get_opt(lun->be_lun, "product")) == NULL) {
10026		switch (lun->be_lun->lun_type) {
10027		case T_DIRECT:
10028			strcpy(inq_ptr->product, CTL_DIRECT_PRODUCT);
10029			break;
10030		case T_PROCESSOR:
10031			strcpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT);
10032			break;
10033		default:
10034			strcpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT);
10035			break;
10036		}
10037	} else {
10038		memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10039		strncpy(inq_ptr->product, val,
10040		    min(sizeof(inq_ptr->product), strlen(val)));
10041	}
10042
10043	/*
10044	 * XXX make this a macro somewhere so it automatically gets
10045	 * incremented when we make changes.
10046	 */
10047	if (lun == NULL || (val = ctl_get_opt(lun->be_lun, "revision")) == NULL) {
10048		strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10049	} else {
10050		memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10051		strncpy(inq_ptr->revision, val,
10052		    min(sizeof(inq_ptr->revision), strlen(val)));
10053	}
10054
10055	/*
10056	 * For parallel SCSI, we support double transition and single
10057	 * transition clocking.  We also support QAS (Quick Arbitration
10058	 * and Selection) and Information Unit transfers on both the
10059	 * control and array devices.
10060	 */
10061	if (is_fc == 0)
10062		inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10063				    SID_SPI_IUS;
10064
10065	/* SAM-3 */
10066	scsi_ulto2b(0x0060, inq_ptr->version1);
10067	/* SPC-3 (no version claimed) XXX should we claim a version? */
10068	scsi_ulto2b(0x0300, inq_ptr->version2);
10069	if (is_fc) {
10070		/* FCP-2 ANSI INCITS.350:2003 */
10071		scsi_ulto2b(0x0917, inq_ptr->version3);
10072	} else {
10073		/* SPI-4 ANSI INCITS.362:200x */
10074		scsi_ulto2b(0x0B56, inq_ptr->version3);
10075	}
10076
10077	if (lun == NULL) {
10078		/* SBC-2 (no version claimed) XXX should we claim a version? */
10079		scsi_ulto2b(0x0320, inq_ptr->version4);
10080	} else {
10081		switch (lun->be_lun->lun_type) {
10082		case T_DIRECT:
10083			/*
10084			 * SBC-2 (no version claimed) XXX should we claim a
10085			 * version?
10086			 */
10087			scsi_ulto2b(0x0320, inq_ptr->version4);
10088			break;
10089		case T_PROCESSOR:
10090		default:
10091			break;
10092		}
10093	}
10094
10095	ctsio->scsi_status = SCSI_STATUS_OK;
10096	if (ctsio->kern_data_len > 0) {
10097		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10098		ctsio->be_move_done = ctl_config_move_done;
10099		ctl_datamove((union ctl_io *)ctsio);
10100	} else {
10101		ctsio->io_hdr.status = CTL_SUCCESS;
10102		ctl_done((union ctl_io *)ctsio);
10103	}
10104
10105	return (CTL_RETVAL_COMPLETE);
10106}
10107
10108int
10109ctl_inquiry(struct ctl_scsiio *ctsio)
10110{
10111	struct scsi_inquiry *cdb;
10112	int retval;
10113
10114	cdb = (struct scsi_inquiry *)ctsio->cdb;
10115
10116	retval = 0;
10117
10118	CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10119
10120	/*
10121	 * Right now, we don't support the CmdDt inquiry information.
10122	 * This would be nice to support in the future.  When we do
10123	 * support it, we should change this test so that it checks to make
10124	 * sure SI_EVPD and SI_CMDDT aren't both set at the same time.
10125	 */
10126#ifdef notyet
10127	if (((cdb->byte2 & SI_EVPD)
10128	 && (cdb->byte2 & SI_CMDDT)))
10129#endif
10130	if (cdb->byte2 & SI_CMDDT) {
10131		/*
10132		 * Point to the SI_CMDDT bit.  We might change this
10133		 * when we support SI_CMDDT, but since both bits would be
10134		 * "wrong", this should probably just stay as-is then.
10135		 */
10136		ctl_set_invalid_field(ctsio,
10137				      /*sks_valid*/ 1,
10138				      /*command*/ 1,
10139				      /*field*/ 1,
10140				      /*bit_valid*/ 1,
10141				      /*bit*/ 1);
10142		ctl_done((union ctl_io *)ctsio);
10143		return (CTL_RETVAL_COMPLETE);
10144	}
10145	if (cdb->byte2 & SI_EVPD)
10146		retval = ctl_inquiry_evpd(ctsio);
10147#ifdef notyet
10148	else if (cdb->byte2 & SI_CMDDT)
10149		retval = ctl_inquiry_cmddt(ctsio);
10150#endif
10151	else
10152		retval = ctl_inquiry_std(ctsio);
10153
10154	return (retval);
10155}
10156
10157/*
10158 * For known CDB types, parse the LBA and length.
10159 */
10160static int
10161ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint32_t *len)
10162{
10163	if (io->io_hdr.io_type != CTL_IO_SCSI)
10164		return (1);
10165
10166	switch (io->scsiio.cdb[0]) {
10167	case COMPARE_AND_WRITE: {
10168		struct scsi_compare_and_write *cdb;
10169
10170		cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10171
10172		*lba = scsi_8btou64(cdb->addr);
10173		*len = cdb->length;
10174		break;
10175	}
10176	case READ_6:
10177	case WRITE_6: {
10178		struct scsi_rw_6 *cdb;
10179
10180		cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10181
10182		*lba = scsi_3btoul(cdb->addr);
10183		/* only 5 bits are valid in the most significant address byte */
10184		*lba &= 0x1fffff;
10185		*len = cdb->length;
10186		break;
10187	}
10188	case READ_10:
10189	case WRITE_10: {
10190		struct scsi_rw_10 *cdb;
10191
10192		cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10193
10194		*lba = scsi_4btoul(cdb->addr);
10195		*len = scsi_2btoul(cdb->length);
10196		break;
10197	}
10198	case WRITE_VERIFY_10: {
10199		struct scsi_write_verify_10 *cdb;
10200
10201		cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10202
10203		*lba = scsi_4btoul(cdb->addr);
10204		*len = scsi_2btoul(cdb->length);
10205		break;
10206	}
10207	case READ_12:
10208	case WRITE_12: {
10209		struct scsi_rw_12 *cdb;
10210
10211		cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10212
10213		*lba = scsi_4btoul(cdb->addr);
10214		*len = scsi_4btoul(cdb->length);
10215		break;
10216	}
10217	case WRITE_VERIFY_12: {
10218		struct scsi_write_verify_12 *cdb;
10219
10220		cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10221
10222		*lba = scsi_4btoul(cdb->addr);
10223		*len = scsi_4btoul(cdb->length);
10224		break;
10225	}
10226	case READ_16:
10227	case WRITE_16: {
10228		struct scsi_rw_16 *cdb;
10229
10230		cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10231
10232		*lba = scsi_8btou64(cdb->addr);
10233		*len = scsi_4btoul(cdb->length);
10234		break;
10235	}
10236	case WRITE_VERIFY_16: {
10237		struct scsi_write_verify_16 *cdb;
10238
10239		cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10240
10241
10242		*lba = scsi_8btou64(cdb->addr);
10243		*len = scsi_4btoul(cdb->length);
10244		break;
10245	}
10246	case WRITE_SAME_10: {
10247		struct scsi_write_same_10 *cdb;
10248
10249		cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10250
10251		*lba = scsi_4btoul(cdb->addr);
10252		*len = scsi_2btoul(cdb->length);
10253		break;
10254	}
10255	case WRITE_SAME_16: {
10256		struct scsi_write_same_16 *cdb;
10257
10258		cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10259
10260		*lba = scsi_8btou64(cdb->addr);
10261		*len = scsi_4btoul(cdb->length);
10262		break;
10263	}
10264	case VERIFY_10: {
10265		struct scsi_verify_10 *cdb;
10266
10267		cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10268
10269		*lba = scsi_4btoul(cdb->addr);
10270		*len = scsi_2btoul(cdb->length);
10271		break;
10272	}
10273	case VERIFY_12: {
10274		struct scsi_verify_12 *cdb;
10275
10276		cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10277
10278		*lba = scsi_4btoul(cdb->addr);
10279		*len = scsi_4btoul(cdb->length);
10280		break;
10281	}
10282	case VERIFY_16: {
10283		struct scsi_verify_16 *cdb;
10284
10285		cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10286
10287		*lba = scsi_8btou64(cdb->addr);
10288		*len = scsi_4btoul(cdb->length);
10289		break;
10290	}
10291	default:
10292		return (1);
10293		break; /* NOTREACHED */
10294	}
10295
10296	return (0);
10297}
10298
10299static ctl_action
10300ctl_extent_check_lba(uint64_t lba1, uint32_t len1, uint64_t lba2, uint32_t len2)
10301{
10302	uint64_t endlba1, endlba2;
10303
10304	endlba1 = lba1 + len1 - 1;
10305	endlba2 = lba2 + len2 - 1;
10306
10307	if ((endlba1 < lba2)
10308	 || (endlba2 < lba1))
10309		return (CTL_ACTION_PASS);
10310	else
10311		return (CTL_ACTION_BLOCK);
10312}
10313
10314static ctl_action
10315ctl_extent_check(union ctl_io *io1, union ctl_io *io2)
10316{
10317	uint64_t lba1, lba2;
10318	uint32_t len1, len2;
10319	int retval;
10320
10321	retval = ctl_get_lba_len(io1, &lba1, &len1);
10322	if (retval != 0)
10323		return (CTL_ACTION_ERROR);
10324
10325	retval = ctl_get_lba_len(io2, &lba2, &len2);
10326	if (retval != 0)
10327		return (CTL_ACTION_ERROR);
10328
10329	return (ctl_extent_check_lba(lba1, len1, lba2, len2));
10330}
10331
10332static ctl_action
10333ctl_check_for_blockage(union ctl_io *pending_io, union ctl_io *ooa_io)
10334{
10335	struct ctl_cmd_entry *pending_entry, *ooa_entry;
10336	ctl_serialize_action *serialize_row;
10337
10338	/*
10339	 * The initiator attempted multiple untagged commands at the same
10340	 * time.  Can't do that.
10341	 */
10342	if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10343	 && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10344	 && ((pending_io->io_hdr.nexus.targ_port ==
10345	      ooa_io->io_hdr.nexus.targ_port)
10346	  && (pending_io->io_hdr.nexus.initid.id ==
10347	      ooa_io->io_hdr.nexus.initid.id))
10348	 && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
10349		return (CTL_ACTION_OVERLAP);
10350
10351	/*
10352	 * The initiator attempted to send multiple tagged commands with
10353	 * the same ID.  (It's fine if different initiators have the same
10354	 * tag ID.)
10355	 *
10356	 * Even if all of those conditions are true, we don't kill the I/O
10357	 * if the command ahead of us has been aborted.  We won't end up
10358	 * sending it to the FETD, and it's perfectly legal to resend a
10359	 * command with the same tag number as long as the previous
10360	 * instance of this tag number has been aborted somehow.
10361	 */
10362	if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10363	 && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10364	 && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
10365	 && ((pending_io->io_hdr.nexus.targ_port ==
10366	      ooa_io->io_hdr.nexus.targ_port)
10367	  && (pending_io->io_hdr.nexus.initid.id ==
10368	      ooa_io->io_hdr.nexus.initid.id))
10369	 && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
10370		return (CTL_ACTION_OVERLAP_TAG);
10371
10372	/*
10373	 * If we get a head of queue tag, SAM-3 says that we should
10374	 * immediately execute it.
10375	 *
10376	 * What happens if this command would normally block for some other
10377	 * reason?  e.g. a request sense with a head of queue tag
10378	 * immediately after a write.  Normally that would block, but this
10379	 * will result in its getting executed immediately...
10380	 *
10381	 * We currently return "pass" instead of "skip", so we'll end up
10382	 * going through the rest of the queue to check for overlapped tags.
10383	 *
10384	 * XXX KDM check for other types of blockage first??
10385	 */
10386	if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10387		return (CTL_ACTION_PASS);
10388
10389	/*
10390	 * Ordered tags have to block until all items ahead of them
10391	 * have completed.  If we get called with an ordered tag, we always
10392	 * block, if something else is ahead of us in the queue.
10393	 */
10394	if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
10395		return (CTL_ACTION_BLOCK);
10396
10397	/*
10398	 * Simple tags get blocked until all head of queue and ordered tags
10399	 * ahead of them have completed.  I'm lumping untagged commands in
10400	 * with simple tags here.  XXX KDM is that the right thing to do?
10401	 */
10402	if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10403	  || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
10404	 && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10405	  || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
10406		return (CTL_ACTION_BLOCK);
10407
10408	pending_entry = &ctl_cmd_table[pending_io->scsiio.cdb[0]];
10409	ooa_entry = &ctl_cmd_table[ooa_io->scsiio.cdb[0]];
10410
10411	serialize_row = ctl_serialize_table[ooa_entry->seridx];
10412
10413	switch (serialize_row[pending_entry->seridx]) {
10414	case CTL_SER_BLOCK:
10415		return (CTL_ACTION_BLOCK);
10416		break; /* NOTREACHED */
10417	case CTL_SER_EXTENT:
10418		return (ctl_extent_check(pending_io, ooa_io));
10419		break; /* NOTREACHED */
10420	case CTL_SER_PASS:
10421		return (CTL_ACTION_PASS);
10422		break; /* NOTREACHED */
10423	case CTL_SER_SKIP:
10424		return (CTL_ACTION_SKIP);
10425		break;
10426	default:
10427		panic("invalid serialization value %d",
10428		      serialize_row[pending_entry->seridx]);
10429		break; /* NOTREACHED */
10430	}
10431
10432	return (CTL_ACTION_ERROR);
10433}
10434
10435/*
10436 * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
10437 * Assumptions:
10438 * - pending_io is generally either incoming, or on the blocked queue
10439 * - starting I/O is the I/O we want to start the check with.
10440 */
10441static ctl_action
10442ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
10443	      union ctl_io *starting_io)
10444{
10445	union ctl_io *ooa_io;
10446	ctl_action action;
10447
10448	mtx_assert(&lun->lun_lock, MA_OWNED);
10449
10450	/*
10451	 * Run back along the OOA queue, starting with the current
10452	 * blocked I/O and going through every I/O before it on the
10453	 * queue.  If starting_io is NULL, we'll just end up returning
10454	 * CTL_ACTION_PASS.
10455	 */
10456	for (ooa_io = starting_io; ooa_io != NULL;
10457	     ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
10458	     ooa_links)){
10459
10460		/*
10461		 * This routine just checks to see whether
10462		 * cur_blocked is blocked by ooa_io, which is ahead
10463		 * of it in the queue.  It doesn't queue/dequeue
10464		 * cur_blocked.
10465		 */
10466		action = ctl_check_for_blockage(pending_io, ooa_io);
10467		switch (action) {
10468		case CTL_ACTION_BLOCK:
10469		case CTL_ACTION_OVERLAP:
10470		case CTL_ACTION_OVERLAP_TAG:
10471		case CTL_ACTION_SKIP:
10472		case CTL_ACTION_ERROR:
10473			return (action);
10474			break; /* NOTREACHED */
10475		case CTL_ACTION_PASS:
10476			break;
10477		default:
10478			panic("invalid action %d", action);
10479			break;  /* NOTREACHED */
10480		}
10481	}
10482
10483	return (CTL_ACTION_PASS);
10484}
10485
10486/*
10487 * Assumptions:
10488 * - An I/O has just completed, and has been removed from the per-LUN OOA
10489 *   queue, so some items on the blocked queue may now be unblocked.
10490 */
10491static int
10492ctl_check_blocked(struct ctl_lun *lun)
10493{
10494	union ctl_io *cur_blocked, *next_blocked;
10495
10496	mtx_assert(&lun->lun_lock, MA_OWNED);
10497
10498	/*
10499	 * Run forward from the head of the blocked queue, checking each
10500	 * entry against the I/Os prior to it on the OOA queue to see if
10501	 * there is still any blockage.
10502	 *
10503	 * We cannot use the TAILQ_FOREACH() macro, because it can't deal
10504	 * with our removing a variable on it while it is traversing the
10505	 * list.
10506	 */
10507	for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
10508	     cur_blocked != NULL; cur_blocked = next_blocked) {
10509		union ctl_io *prev_ooa;
10510		ctl_action action;
10511
10512		next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
10513							  blocked_links);
10514
10515		prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
10516						      ctl_ooaq, ooa_links);
10517
10518		/*
10519		 * If cur_blocked happens to be the first item in the OOA
10520		 * queue now, prev_ooa will be NULL, and the action
10521		 * returned will just be CTL_ACTION_PASS.
10522		 */
10523		action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
10524
10525		switch (action) {
10526		case CTL_ACTION_BLOCK:
10527			/* Nothing to do here, still blocked */
10528			break;
10529		case CTL_ACTION_OVERLAP:
10530		case CTL_ACTION_OVERLAP_TAG:
10531			/*
10532			 * This shouldn't happen!  In theory we've already
10533			 * checked this command for overlap...
10534			 */
10535			break;
10536		case CTL_ACTION_PASS:
10537		case CTL_ACTION_SKIP: {
10538			struct ctl_softc *softc;
10539			struct ctl_cmd_entry *entry;
10540			uint32_t initidx;
10541			uint8_t opcode;
10542			int isc_retval;
10543
10544			/*
10545			 * The skip case shouldn't happen, this transaction
10546			 * should have never made it onto the blocked queue.
10547			 */
10548			/*
10549			 * This I/O is no longer blocked, we can remove it
10550			 * from the blocked queue.  Since this is a TAILQ
10551			 * (doubly linked list), we can do O(1) removals
10552			 * from any place on the list.
10553			 */
10554			TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
10555				     blocked_links);
10556			cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
10557
10558			if (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC){
10559				/*
10560				 * Need to send IO back to original side to
10561				 * run
10562				 */
10563				union ctl_ha_msg msg_info;
10564
10565				msg_info.hdr.original_sc =
10566					cur_blocked->io_hdr.original_sc;
10567				msg_info.hdr.serializing_sc = cur_blocked;
10568				msg_info.hdr.msg_type = CTL_MSG_R2R;
10569				if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
10570				     &msg_info, sizeof(msg_info), 0)) >
10571				     CTL_HA_STATUS_SUCCESS) {
10572					printf("CTL:Check Blocked error from "
10573					       "ctl_ha_msg_send %d\n",
10574					       isc_retval);
10575				}
10576				break;
10577			}
10578			opcode = cur_blocked->scsiio.cdb[0];
10579			entry = &ctl_cmd_table[opcode];
10580			softc = control_softc;
10581
10582			initidx = ctl_get_initindex(&cur_blocked->io_hdr.nexus);
10583
10584			/*
10585			 * Check this I/O for LUN state changes that may
10586			 * have happened while this command was blocked.
10587			 * The LUN state may have been changed by a command
10588			 * ahead of us in the queue, so we need to re-check
10589			 * for any states that can be caused by SCSI
10590			 * commands.
10591			 */
10592			if (ctl_scsiio_lun_check(softc, lun, entry,
10593						 &cur_blocked->scsiio) == 0) {
10594				cur_blocked->io_hdr.flags |=
10595				                      CTL_FLAG_IS_WAS_ON_RTR;
10596				ctl_enqueue_rtr(cur_blocked);
10597			} else
10598				ctl_done(cur_blocked);
10599			break;
10600		}
10601		default:
10602			/*
10603			 * This probably shouldn't happen -- we shouldn't
10604			 * get CTL_ACTION_ERROR, or anything else.
10605			 */
10606			break;
10607		}
10608	}
10609
10610	return (CTL_RETVAL_COMPLETE);
10611}
10612
10613/*
10614 * This routine (with one exception) checks LUN flags that can be set by
10615 * commands ahead of us in the OOA queue.  These flags have to be checked
10616 * when a command initially comes in, and when we pull a command off the
10617 * blocked queue and are preparing to execute it.  The reason we have to
10618 * check these flags for commands on the blocked queue is that the LUN
10619 * state may have been changed by a command ahead of us while we're on the
10620 * blocked queue.
10621 *
10622 * Ordering is somewhat important with these checks, so please pay
10623 * careful attention to the placement of any new checks.
10624 */
10625static int
10626ctl_scsiio_lun_check(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
10627		     struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
10628{
10629	int retval;
10630
10631	retval = 0;
10632
10633	mtx_assert(&lun->lun_lock, MA_OWNED);
10634
10635	/*
10636	 * If this shelf is a secondary shelf controller, we have to reject
10637	 * any media access commands.
10638	 */
10639#if 0
10640	/* No longer needed for HA */
10641	if (((ctl_softc->flags & CTL_FLAG_MASTER_SHELF) == 0)
10642	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_SECONDARY) == 0)) {
10643		ctl_set_lun_standby(ctsio);
10644		retval = 1;
10645		goto bailout;
10646	}
10647#endif
10648
10649	/*
10650	 * Check for a reservation conflict.  If this command isn't allowed
10651	 * even on reserved LUNs, and if this initiator isn't the one who
10652	 * reserved us, reject the command with a reservation conflict.
10653	 */
10654	if ((lun->flags & CTL_LUN_RESERVED)
10655	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
10656		if ((ctsio->io_hdr.nexus.initid.id != lun->rsv_nexus.initid.id)
10657		 || (ctsio->io_hdr.nexus.targ_port != lun->rsv_nexus.targ_port)
10658		 || (ctsio->io_hdr.nexus.targ_target.id !=
10659		     lun->rsv_nexus.targ_target.id)) {
10660			ctsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
10661			ctsio->io_hdr.status = CTL_SCSI_ERROR;
10662			retval = 1;
10663			goto bailout;
10664		}
10665	}
10666
10667	if ( (lun->flags & CTL_LUN_PR_RESERVED)
10668	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV) == 0)) {
10669		uint32_t residx;
10670
10671		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
10672		/*
10673		 * if we aren't registered or it's a res holder type
10674		 * reservation and this isn't the res holder then set a
10675		 * conflict.
10676		 * NOTE: Commands which might be allowed on write exclusive
10677		 * type reservations are checked in the particular command
10678		 * for a conflict. Read and SSU are the only ones.
10679		 */
10680		if (!lun->per_res[residx].registered
10681		 || (residx != lun->pr_res_idx && lun->res_type < 4)) {
10682			ctsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
10683			ctsio->io_hdr.status = CTL_SCSI_ERROR;
10684			retval = 1;
10685			goto bailout;
10686		}
10687
10688	}
10689
10690	if ((lun->flags & CTL_LUN_OFFLINE)
10691	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_OFFLINE) == 0)) {
10692		ctl_set_lun_not_ready(ctsio);
10693		retval = 1;
10694		goto bailout;
10695	}
10696
10697	/*
10698	 * If the LUN is stopped, see if this particular command is allowed
10699	 * for a stopped lun.  Otherwise, reject it with 0x04,0x02.
10700	 */
10701	if ((lun->flags & CTL_LUN_STOPPED)
10702	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_STOPPED) == 0)) {
10703		/* "Logical unit not ready, initializing cmd. required" */
10704		ctl_set_lun_stopped(ctsio);
10705		retval = 1;
10706		goto bailout;
10707	}
10708
10709	if ((lun->flags & CTL_LUN_INOPERABLE)
10710	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_INOPERABLE) == 0)) {
10711		/* "Medium format corrupted" */
10712		ctl_set_medium_format_corrupted(ctsio);
10713		retval = 1;
10714		goto bailout;
10715	}
10716
10717bailout:
10718	return (retval);
10719
10720}
10721
10722static void
10723ctl_failover_io(union ctl_io *io, int have_lock)
10724{
10725	ctl_set_busy(&io->scsiio);
10726	ctl_done(io);
10727}
10728
10729static void
10730ctl_failover(void)
10731{
10732	struct ctl_lun *lun;
10733	struct ctl_softc *ctl_softc;
10734	union ctl_io *next_io, *pending_io;
10735	union ctl_io *io;
10736	int lun_idx;
10737	int i;
10738
10739	ctl_softc = control_softc;
10740
10741	mtx_lock(&ctl_softc->ctl_lock);
10742	/*
10743	 * Remove any cmds from the other SC from the rtr queue.  These
10744	 * will obviously only be for LUNs for which we're the primary.
10745	 * We can't send status or get/send data for these commands.
10746	 * Since they haven't been executed yet, we can just remove them.
10747	 * We'll either abort them or delete them below, depending on
10748	 * which HA mode we're in.
10749	 */
10750#ifdef notyet
10751	mtx_lock(&ctl_softc->queue_lock);
10752	for (io = (union ctl_io *)STAILQ_FIRST(&ctl_softc->rtr_queue);
10753	     io != NULL; io = next_io) {
10754		next_io = (union ctl_io *)STAILQ_NEXT(&io->io_hdr, links);
10755		if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
10756			STAILQ_REMOVE(&ctl_softc->rtr_queue, &io->io_hdr,
10757				      ctl_io_hdr, links);
10758	}
10759	mtx_unlock(&ctl_softc->queue_lock);
10760#endif
10761
10762	for (lun_idx=0; lun_idx < ctl_softc->num_luns; lun_idx++) {
10763		lun = ctl_softc->ctl_luns[lun_idx];
10764		if (lun==NULL)
10765			continue;
10766
10767		/*
10768		 * Processor LUNs are primary on both sides.
10769		 * XXX will this always be true?
10770		 */
10771		if (lun->be_lun->lun_type == T_PROCESSOR)
10772			continue;
10773
10774		if ((lun->flags & CTL_LUN_PRIMARY_SC)
10775		 && (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
10776			printf("FAILOVER: primary lun %d\n", lun_idx);
10777		        /*
10778			 * Remove all commands from the other SC. First from the
10779			 * blocked queue then from the ooa queue. Once we have
10780			 * removed them. Call ctl_check_blocked to see if there
10781			 * is anything that can run.
10782			 */
10783			for (io = (union ctl_io *)TAILQ_FIRST(
10784			     &lun->blocked_queue); io != NULL; io = next_io) {
10785
10786		        	next_io = (union ctl_io *)TAILQ_NEXT(
10787				    &io->io_hdr, blocked_links);
10788
10789				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
10790					TAILQ_REMOVE(&lun->blocked_queue,
10791						     &io->io_hdr,blocked_links);
10792					io->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
10793					TAILQ_REMOVE(&lun->ooa_queue,
10794						     &io->io_hdr, ooa_links);
10795
10796					ctl_free_io(io);
10797				}
10798			}
10799
10800			for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
10801	     		     io != NULL; io = next_io) {
10802
10803		        	next_io = (union ctl_io *)TAILQ_NEXT(
10804				    &io->io_hdr, ooa_links);
10805
10806				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
10807
10808					TAILQ_REMOVE(&lun->ooa_queue,
10809						&io->io_hdr,
10810					     	ooa_links);
10811
10812					ctl_free_io(io);
10813				}
10814			}
10815			ctl_check_blocked(lun);
10816		} else if ((lun->flags & CTL_LUN_PRIMARY_SC)
10817			&& (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
10818
10819			printf("FAILOVER: primary lun %d\n", lun_idx);
10820			/*
10821			 * Abort all commands from the other SC.  We can't
10822			 * send status back for them now.  These should get
10823			 * cleaned up when they are completed or come out
10824			 * for a datamove operation.
10825			 */
10826			for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
10827	     		     io != NULL; io = next_io) {
10828		        	next_io = (union ctl_io *)TAILQ_NEXT(
10829					&io->io_hdr, ooa_links);
10830
10831				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
10832					io->io_hdr.flags |= CTL_FLAG_ABORT;
10833			}
10834		} else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
10835			&& (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
10836
10837			printf("FAILOVER: secondary lun %d\n", lun_idx);
10838
10839			lun->flags |= CTL_LUN_PRIMARY_SC;
10840
10841			/*
10842			 * We send all I/O that was sent to this controller
10843			 * and redirected to the other side back with
10844			 * busy status, and have the initiator retry it.
10845			 * Figuring out how much data has been transferred,
10846			 * etc. and picking up where we left off would be
10847			 * very tricky.
10848			 *
10849			 * XXX KDM need to remove I/O from the blocked
10850			 * queue as well!
10851			 */
10852			for (pending_io = (union ctl_io *)TAILQ_FIRST(
10853			     &lun->ooa_queue); pending_io != NULL;
10854			     pending_io = next_io) {
10855
10856				next_io =  (union ctl_io *)TAILQ_NEXT(
10857					&pending_io->io_hdr, ooa_links);
10858
10859				pending_io->io_hdr.flags &=
10860					~CTL_FLAG_SENT_2OTHER_SC;
10861
10862				if (pending_io->io_hdr.flags &
10863				    CTL_FLAG_IO_ACTIVE) {
10864					pending_io->io_hdr.flags |=
10865						CTL_FLAG_FAILOVER;
10866				} else {
10867					ctl_set_busy(&pending_io->scsiio);
10868					ctl_done(pending_io);
10869				}
10870			}
10871
10872			/*
10873			 * Build Unit Attention
10874			 */
10875			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
10876				lun->pending_sense[i].ua_pending |=
10877				                     CTL_UA_ASYM_ACC_CHANGE;
10878			}
10879		} else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
10880			&& (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
10881			printf("FAILOVER: secondary lun %d\n", lun_idx);
10882			/*
10883			 * if the first io on the OOA is not on the RtR queue
10884			 * add it.
10885			 */
10886			lun->flags |= CTL_LUN_PRIMARY_SC;
10887
10888			pending_io = (union ctl_io *)TAILQ_FIRST(
10889			    &lun->ooa_queue);
10890			if (pending_io==NULL) {
10891				printf("Nothing on OOA queue\n");
10892				continue;
10893			}
10894
10895			pending_io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
10896			if ((pending_io->io_hdr.flags &
10897			     CTL_FLAG_IS_WAS_ON_RTR) == 0) {
10898				pending_io->io_hdr.flags |=
10899				    CTL_FLAG_IS_WAS_ON_RTR;
10900				ctl_enqueue_rtr(pending_io);
10901			}
10902#if 0
10903			else
10904			{
10905				printf("Tag 0x%04x is running\n",
10906				      pending_io->scsiio.tag_num);
10907			}
10908#endif
10909
10910			next_io = (union ctl_io *)TAILQ_NEXT(
10911			    &pending_io->io_hdr, ooa_links);
10912			for (pending_io=next_io; pending_io != NULL;
10913			     pending_io = next_io) {
10914				pending_io->io_hdr.flags &=
10915				    ~CTL_FLAG_SENT_2OTHER_SC;
10916				next_io = (union ctl_io *)TAILQ_NEXT(
10917					&pending_io->io_hdr, ooa_links);
10918				if (pending_io->io_hdr.flags &
10919				    CTL_FLAG_IS_WAS_ON_RTR) {
10920#if 0
10921				        printf("Tag 0x%04x is running\n",
10922				      		pending_io->scsiio.tag_num);
10923#endif
10924					continue;
10925				}
10926
10927				switch (ctl_check_ooa(lun, pending_io,
10928			            (union ctl_io *)TAILQ_PREV(
10929				    &pending_io->io_hdr, ctl_ooaq,
10930				    ooa_links))) {
10931
10932				case CTL_ACTION_BLOCK:
10933					TAILQ_INSERT_TAIL(&lun->blocked_queue,
10934							  &pending_io->io_hdr,
10935							  blocked_links);
10936					pending_io->io_hdr.flags |=
10937					    CTL_FLAG_BLOCKED;
10938					break;
10939				case CTL_ACTION_PASS:
10940				case CTL_ACTION_SKIP:
10941					pending_io->io_hdr.flags |=
10942					    CTL_FLAG_IS_WAS_ON_RTR;
10943					ctl_enqueue_rtr(pending_io);
10944					break;
10945				case CTL_ACTION_OVERLAP:
10946					ctl_set_overlapped_cmd(
10947					    (struct ctl_scsiio *)pending_io);
10948					ctl_done(pending_io);
10949					break;
10950				case CTL_ACTION_OVERLAP_TAG:
10951					ctl_set_overlapped_tag(
10952					    (struct ctl_scsiio *)pending_io,
10953					    pending_io->scsiio.tag_num & 0xff);
10954					ctl_done(pending_io);
10955					break;
10956				case CTL_ACTION_ERROR:
10957				default:
10958					ctl_set_internal_failure(
10959						(struct ctl_scsiio *)pending_io,
10960						0,  // sks_valid
10961						0); //retry count
10962					ctl_done(pending_io);
10963					break;
10964				}
10965			}
10966
10967			/*
10968			 * Build Unit Attention
10969			 */
10970			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
10971				lun->pending_sense[i].ua_pending |=
10972				                     CTL_UA_ASYM_ACC_CHANGE;
10973			}
10974		} else {
10975			panic("Unhandled HA mode failover, LUN flags = %#x, "
10976			      "ha_mode = #%x", lun->flags, ctl_softc->ha_mode);
10977		}
10978	}
10979	ctl_pause_rtr = 0;
10980	mtx_unlock(&ctl_softc->ctl_lock);
10981}
10982
10983static int
10984ctl_scsiio_precheck(struct ctl_softc *ctl_softc, struct ctl_scsiio *ctsio)
10985{
10986	struct ctl_lun *lun;
10987	struct ctl_cmd_entry *entry;
10988	uint8_t opcode;
10989	uint32_t initidx, targ_lun;
10990	int retval;
10991
10992	retval = 0;
10993
10994	lun = NULL;
10995
10996	opcode = ctsio->cdb[0];
10997
10998	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
10999	if ((targ_lun < CTL_MAX_LUNS)
11000	 && (ctl_softc->ctl_luns[targ_lun] != NULL)) {
11001		lun = ctl_softc->ctl_luns[targ_lun];
11002		/*
11003		 * If the LUN is invalid, pretend that it doesn't exist.
11004		 * It will go away as soon as all pending I/O has been
11005		 * completed.
11006		 */
11007		if (lun->flags & CTL_LUN_DISABLED) {
11008			lun = NULL;
11009		} else {
11010			ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
11011			ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr =
11012				lun->be_lun;
11013			if (lun->be_lun->lun_type == T_PROCESSOR) {
11014				ctsio->io_hdr.flags |= CTL_FLAG_CONTROL_DEV;
11015			}
11016		}
11017	} else {
11018		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11019		ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11020	}
11021
11022	entry = &ctl_cmd_table[opcode];
11023
11024	ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11025	ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11026
11027	/*
11028	 * Check to see whether we can send this command to LUNs that don't
11029	 * exist.  This should pretty much only be the case for inquiry
11030	 * and request sense.  Further checks, below, really require having
11031	 * a LUN, so we can't really check the command anymore.  Just put
11032	 * it on the rtr queue.
11033	 */
11034	if (lun == NULL) {
11035		if (entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) {
11036			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11037			ctl_enqueue_rtr((union ctl_io *)ctsio);
11038			return (retval);
11039		}
11040
11041		ctl_set_unsupported_lun(ctsio);
11042		ctl_done((union ctl_io *)ctsio);
11043		CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11044		return (retval);
11045	} else {
11046		mtx_lock(&lun->lun_lock);
11047
11048		/*
11049		 * Every I/O goes into the OOA queue for a particular LUN, and
11050		 * stays there until completion.
11051		 */
11052		TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
11053
11054		/*
11055		 * Make sure we support this particular command on this LUN.
11056		 * e.g., we don't support writes to the control LUN.
11057		 */
11058		switch (lun->be_lun->lun_type) {
11059		case T_PROCESSOR:
11060		 	if (((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0)
11061			 && ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS)
11062			      == 0)) {
11063				mtx_unlock(&lun->lun_lock);
11064				ctl_set_invalid_opcode(ctsio);
11065				ctl_done((union ctl_io *)ctsio);
11066				return (retval);
11067			}
11068			break;
11069		case T_DIRECT:
11070			if (((entry->flags & CTL_CMD_FLAG_OK_ON_SLUN) == 0)
11071			 && ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS)
11072			      == 0)){
11073				mtx_unlock(&lun->lun_lock);
11074				ctl_set_invalid_opcode(ctsio);
11075				ctl_done((union ctl_io *)ctsio);
11076				return (retval);
11077			}
11078			break;
11079		default:
11080			mtx_unlock(&lun->lun_lock);
11081			panic("Unsupported CTL LUN type %d\n",
11082			      lun->be_lun->lun_type);
11083		}
11084	}
11085
11086	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11087
11088	/*
11089	 * If we've got a request sense, it'll clear the contingent
11090	 * allegiance condition.  Otherwise, if we have a CA condition for
11091	 * this initiator, clear it, because it sent down a command other
11092	 * than request sense.
11093	 */
11094	if ((opcode != REQUEST_SENSE)
11095	 && (ctl_is_set(lun->have_ca, initidx)))
11096		ctl_clear_mask(lun->have_ca, initidx);
11097
11098	/*
11099	 * If the command has this flag set, it handles its own unit
11100	 * attention reporting, we shouldn't do anything.  Otherwise we
11101	 * check for any pending unit attentions, and send them back to the
11102	 * initiator.  We only do this when a command initially comes in,
11103	 * not when we pull it off the blocked queue.
11104	 *
11105	 * According to SAM-3, section 5.3.2, the order that things get
11106	 * presented back to the host is basically unit attentions caused
11107	 * by some sort of reset event, busy status, reservation conflicts
11108	 * or task set full, and finally any other status.
11109	 *
11110	 * One issue here is that some of the unit attentions we report
11111	 * don't fall into the "reset" category (e.g. "reported luns data
11112	 * has changed").  So reporting it here, before the reservation
11113	 * check, may be technically wrong.  I guess the only thing to do
11114	 * would be to check for and report the reset events here, and then
11115	 * check for the other unit attention types after we check for a
11116	 * reservation conflict.
11117	 *
11118	 * XXX KDM need to fix this
11119	 */
11120	if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11121		ctl_ua_type ua_type;
11122
11123		ua_type = lun->pending_sense[initidx].ua_pending;
11124		if (ua_type != CTL_UA_NONE) {
11125			scsi_sense_data_type sense_format;
11126
11127			if (lun != NULL)
11128				sense_format = (lun->flags &
11129				    CTL_LUN_SENSE_DESC) ? SSD_TYPE_DESC :
11130				    SSD_TYPE_FIXED;
11131			else
11132				sense_format = SSD_TYPE_FIXED;
11133
11134			ua_type = ctl_build_ua(ua_type, &ctsio->sense_data,
11135					       sense_format);
11136			if (ua_type != CTL_UA_NONE) {
11137				ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11138				ctsio->io_hdr.status = CTL_SCSI_ERROR |
11139						       CTL_AUTOSENSE;
11140				ctsio->sense_len = SSD_FULL_SIZE;
11141				lun->pending_sense[initidx].ua_pending &=
11142					~ua_type;
11143				mtx_unlock(&lun->lun_lock);
11144				ctl_done((union ctl_io *)ctsio);
11145				return (retval);
11146			}
11147		}
11148	}
11149
11150
11151	if (ctl_scsiio_lun_check(ctl_softc, lun, entry, ctsio) != 0) {
11152		mtx_unlock(&lun->lun_lock);
11153		ctl_done((union ctl_io *)ctsio);
11154		return (retval);
11155	}
11156
11157	/*
11158	 * XXX CHD this is where we want to send IO to other side if
11159	 * this LUN is secondary on this SC. We will need to make a copy
11160	 * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11161	 * the copy we send as FROM_OTHER.
11162	 * We also need to stuff the address of the original IO so we can
11163	 * find it easily. Something similar will need be done on the other
11164	 * side so when we are done we can find the copy.
11165	 */
11166	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11167		union ctl_ha_msg msg_info;
11168		int isc_retval;
11169
11170		ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11171
11172		msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11173		msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11174#if 0
11175		printf("1. ctsio %p\n", ctsio);
11176#endif
11177		msg_info.hdr.serializing_sc = NULL;
11178		msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11179		msg_info.scsi.tag_num = ctsio->tag_num;
11180		msg_info.scsi.tag_type = ctsio->tag_type;
11181		memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11182
11183		ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11184
11185		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11186		    (void *)&msg_info, sizeof(msg_info), 0)) >
11187		    CTL_HA_STATUS_SUCCESS) {
11188			printf("CTL:precheck, ctl_ha_msg_send returned %d\n",
11189			       isc_retval);
11190			printf("CTL:opcode is %x\n",opcode);
11191		} else {
11192#if 0
11193			printf("CTL:Precheck sent msg, opcode is %x\n",opcode);
11194#endif
11195		}
11196
11197		/*
11198		 * XXX KDM this I/O is off the incoming queue, but hasn't
11199		 * been inserted on any other queue.  We may need to come
11200		 * up with a holding queue while we wait for serialization
11201		 * so that we have an idea of what we're waiting for from
11202		 * the other side.
11203		 */
11204		mtx_unlock(&lun->lun_lock);
11205		return (retval);
11206	}
11207
11208	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11209			      (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11210			      ctl_ooaq, ooa_links))) {
11211	case CTL_ACTION_BLOCK:
11212		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11213		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11214				  blocked_links);
11215		mtx_unlock(&lun->lun_lock);
11216		return (retval);
11217	case CTL_ACTION_PASS:
11218	case CTL_ACTION_SKIP:
11219		ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11220		mtx_unlock(&lun->lun_lock);
11221		ctl_enqueue_rtr((union ctl_io *)ctsio);
11222		break;
11223	case CTL_ACTION_OVERLAP:
11224		mtx_unlock(&lun->lun_lock);
11225		ctl_set_overlapped_cmd(ctsio);
11226		ctl_done((union ctl_io *)ctsio);
11227		break;
11228	case CTL_ACTION_OVERLAP_TAG:
11229		mtx_unlock(&lun->lun_lock);
11230		ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11231		ctl_done((union ctl_io *)ctsio);
11232		break;
11233	case CTL_ACTION_ERROR:
11234	default:
11235		mtx_unlock(&lun->lun_lock);
11236		ctl_set_internal_failure(ctsio,
11237					 /*sks_valid*/ 0,
11238					 /*retry_count*/ 0);
11239		ctl_done((union ctl_io *)ctsio);
11240		break;
11241	}
11242	return (retval);
11243}
11244
11245static int
11246ctl_scsiio(struct ctl_scsiio *ctsio)
11247{
11248	int retval;
11249	struct ctl_cmd_entry *entry;
11250
11251	retval = CTL_RETVAL_COMPLETE;
11252
11253	CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11254
11255	entry = &ctl_cmd_table[ctsio->cdb[0]];
11256
11257	/*
11258	 * If this I/O has been aborted, just send it straight to
11259	 * ctl_done() without executing it.
11260	 */
11261	if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11262		ctl_done((union ctl_io *)ctsio);
11263		goto bailout;
11264	}
11265
11266	/*
11267	 * All the checks should have been handled by ctl_scsiio_precheck().
11268	 * We should be clear now to just execute the I/O.
11269	 */
11270	retval = entry->execute(ctsio);
11271
11272bailout:
11273	return (retval);
11274}
11275
11276/*
11277 * Since we only implement one target right now, a bus reset simply resets
11278 * our single target.
11279 */
11280static int
11281ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io)
11282{
11283	return(ctl_target_reset(ctl_softc, io, CTL_UA_BUS_RESET));
11284}
11285
11286static int
11287ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
11288		 ctl_ua_type ua_type)
11289{
11290	struct ctl_lun *lun;
11291	int retval;
11292
11293	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11294		union ctl_ha_msg msg_info;
11295
11296		io->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11297		msg_info.hdr.nexus = io->io_hdr.nexus;
11298		if (ua_type==CTL_UA_TARG_RESET)
11299			msg_info.task.task_action = CTL_TASK_TARGET_RESET;
11300		else
11301			msg_info.task.task_action = CTL_TASK_BUS_RESET;
11302		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11303		msg_info.hdr.original_sc = NULL;
11304		msg_info.hdr.serializing_sc = NULL;
11305		if (CTL_HA_STATUS_SUCCESS != ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11306		    (void *)&msg_info, sizeof(msg_info), 0)) {
11307		}
11308	}
11309	retval = 0;
11310
11311	mtx_lock(&ctl_softc->ctl_lock);
11312	STAILQ_FOREACH(lun, &ctl_softc->lun_list, links)
11313		retval += ctl_lun_reset(lun, io, ua_type);
11314	mtx_unlock(&ctl_softc->ctl_lock);
11315
11316	return (retval);
11317}
11318
11319/*
11320 * The LUN should always be set.  The I/O is optional, and is used to
11321 * distinguish between I/Os sent by this initiator, and by other
11322 * initiators.  We set unit attention for initiators other than this one.
11323 * SAM-3 is vague on this point.  It does say that a unit attention should
11324 * be established for other initiators when a LUN is reset (see section
11325 * 5.7.3), but it doesn't specifically say that the unit attention should
11326 * be established for this particular initiator when a LUN is reset.  Here
11327 * is the relevant text, from SAM-3 rev 8:
11328 *
11329 * 5.7.2 When a SCSI initiator port aborts its own tasks
11330 *
11331 * When a SCSI initiator port causes its own task(s) to be aborted, no
11332 * notification that the task(s) have been aborted shall be returned to
11333 * the SCSI initiator port other than the completion response for the
11334 * command or task management function action that caused the task(s) to
11335 * be aborted and notification(s) associated with related effects of the
11336 * action (e.g., a reset unit attention condition).
11337 *
11338 * XXX KDM for now, we're setting unit attention for all initiators.
11339 */
11340static int
11341ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
11342{
11343	union ctl_io *xio;
11344#if 0
11345	uint32_t initindex;
11346#endif
11347	int i;
11348
11349	mtx_lock(&lun->lun_lock);
11350	/*
11351	 * Run through the OOA queue and abort each I/O.
11352	 */
11353#if 0
11354	TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
11355#endif
11356	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11357	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11358		xio->io_hdr.flags |= CTL_FLAG_ABORT;
11359	}
11360
11361	/*
11362	 * This version sets unit attention for every
11363	 */
11364#if 0
11365	initindex = ctl_get_initindex(&io->io_hdr.nexus);
11366	for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11367		if (initindex == i)
11368			continue;
11369		lun->pending_sense[i].ua_pending |= ua_type;
11370	}
11371#endif
11372
11373	/*
11374	 * A reset (any kind, really) clears reservations established with
11375	 * RESERVE/RELEASE.  It does not clear reservations established
11376	 * with PERSISTENT RESERVE OUT, but we don't support that at the
11377	 * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
11378	 * reservations made with the RESERVE/RELEASE commands, because
11379	 * those commands are obsolete in SPC-3.
11380	 */
11381	lun->flags &= ~CTL_LUN_RESERVED;
11382
11383	for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11384		ctl_clear_mask(lun->have_ca, i);
11385		lun->pending_sense[i].ua_pending |= ua_type;
11386	}
11387	mtx_unlock(&lun->lun_lock);
11388
11389	return (0);
11390}
11391
11392static int
11393ctl_abort_task(union ctl_io *io)
11394{
11395	union ctl_io *xio;
11396	struct ctl_lun *lun;
11397	struct ctl_softc *ctl_softc;
11398#if 0
11399	struct sbuf sb;
11400	char printbuf[128];
11401#endif
11402	int found;
11403	uint32_t targ_lun;
11404
11405	ctl_softc = control_softc;
11406	found = 0;
11407
11408	/*
11409	 * Look up the LUN.
11410	 */
11411	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11412	mtx_lock(&ctl_softc->ctl_lock);
11413	if ((targ_lun < CTL_MAX_LUNS)
11414	 && (ctl_softc->ctl_luns[targ_lun] != NULL))
11415		lun = ctl_softc->ctl_luns[targ_lun];
11416	else {
11417		mtx_unlock(&ctl_softc->ctl_lock);
11418		goto bailout;
11419	}
11420
11421#if 0
11422	printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
11423	       lun->lun, io->taskio.tag_num, io->taskio.tag_type);
11424#endif
11425
11426	mtx_lock(&lun->lun_lock);
11427	mtx_unlock(&ctl_softc->ctl_lock);
11428	/*
11429	 * Run through the OOA queue and attempt to find the given I/O.
11430	 * The target port, initiator ID, tag type and tag number have to
11431	 * match the values that we got from the initiator.  If we have an
11432	 * untagged command to abort, simply abort the first untagged command
11433	 * we come to.  We only allow one untagged command at a time of course.
11434	 */
11435#if 0
11436	TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
11437#endif
11438	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11439	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11440#if 0
11441		sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
11442
11443		sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
11444			    lun->lun, xio->scsiio.tag_num,
11445			    xio->scsiio.tag_type,
11446			    (xio->io_hdr.blocked_links.tqe_prev
11447			    == NULL) ? "" : " BLOCKED",
11448			    (xio->io_hdr.flags &
11449			    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
11450			    (xio->io_hdr.flags &
11451			    CTL_FLAG_ABORT) ? " ABORT" : "",
11452			    (xio->io_hdr.flags &
11453			    CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
11454		ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
11455		sbuf_finish(&sb);
11456		printf("%s\n", sbuf_data(&sb));
11457#endif
11458
11459		if ((xio->io_hdr.nexus.targ_port == io->io_hdr.nexus.targ_port)
11460		 && (xio->io_hdr.nexus.initid.id ==
11461		     io->io_hdr.nexus.initid.id)) {
11462			/*
11463			 * If the abort says that the task is untagged, the
11464			 * task in the queue must be untagged.  Otherwise,
11465			 * we just check to see whether the tag numbers
11466			 * match.  This is because the QLogic firmware
11467			 * doesn't pass back the tag type in an abort
11468			 * request.
11469			 */
11470#if 0
11471			if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
11472			  && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
11473			 || (xio->scsiio.tag_num == io->taskio.tag_num)) {
11474#endif
11475			/*
11476			 * XXX KDM we've got problems with FC, because it
11477			 * doesn't send down a tag type with aborts.  So we
11478			 * can only really go by the tag number...
11479			 * This may cause problems with parallel SCSI.
11480			 * Need to figure that out!!
11481			 */
11482			if (xio->scsiio.tag_num == io->taskio.tag_num) {
11483				xio->io_hdr.flags |= CTL_FLAG_ABORT;
11484				found = 1;
11485				if ((io->io_hdr.flags &
11486				     CTL_FLAG_FROM_OTHER_SC) == 0 &&
11487				    !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11488					union ctl_ha_msg msg_info;
11489
11490					io->io_hdr.flags |=
11491					                CTL_FLAG_SENT_2OTHER_SC;
11492					msg_info.hdr.nexus = io->io_hdr.nexus;
11493					msg_info.task.task_action =
11494						CTL_TASK_ABORT_TASK;
11495					msg_info.task.tag_num =
11496						io->taskio.tag_num;
11497					msg_info.task.tag_type =
11498						io->taskio.tag_type;
11499					msg_info.hdr.msg_type =
11500						CTL_MSG_MANAGE_TASKS;
11501					msg_info.hdr.original_sc = NULL;
11502					msg_info.hdr.serializing_sc = NULL;
11503#if 0
11504					printf("Sent Abort to other side\n");
11505#endif
11506					if (CTL_HA_STATUS_SUCCESS !=
11507					        ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11508		    				(void *)&msg_info,
11509						sizeof(msg_info), 0)) {
11510					}
11511				}
11512#if 0
11513				printf("ctl_abort_task: found I/O to abort\n");
11514#endif
11515				break;
11516			}
11517		}
11518	}
11519	mtx_unlock(&lun->lun_lock);
11520
11521bailout:
11522
11523	if (found == 0) {
11524		/*
11525		 * This isn't really an error.  It's entirely possible for
11526		 * the abort and command completion to cross on the wire.
11527		 * This is more of an informative/diagnostic error.
11528		 */
11529#if 0
11530		printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
11531		       "%d:%d:%d:%d tag %d type %d\n",
11532		       io->io_hdr.nexus.initid.id,
11533		       io->io_hdr.nexus.targ_port,
11534		       io->io_hdr.nexus.targ_target.id,
11535		       io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
11536		       io->taskio.tag_type);
11537#endif
11538		return (1);
11539	} else
11540		return (0);
11541}
11542
11543static void
11544ctl_run_task(union ctl_io *io)
11545{
11546	struct ctl_softc *ctl_softc;
11547	int retval;
11548	const char *task_desc;
11549
11550	CTL_DEBUG_PRINT(("ctl_run_task\n"));
11551
11552	ctl_softc = control_softc;
11553	retval = 0;
11554
11555	KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
11556	    ("ctl_run_task: Unextected io_type %d\n",
11557	     io->io_hdr.io_type));
11558
11559	task_desc = ctl_scsi_task_string(&io->taskio);
11560	if (task_desc != NULL) {
11561#ifdef NEEDTOPORT
11562		csevent_log(CSC_CTL | CSC_SHELF_SW |
11563			    CTL_TASK_REPORT,
11564			    csevent_LogType_Trace,
11565			    csevent_Severity_Information,
11566			    csevent_AlertLevel_Green,
11567			    csevent_FRU_Firmware,
11568			    csevent_FRU_Unknown,
11569			    "CTL: received task: %s",task_desc);
11570#endif
11571	} else {
11572#ifdef NEEDTOPORT
11573		csevent_log(CSC_CTL | CSC_SHELF_SW |
11574			    CTL_TASK_REPORT,
11575			    csevent_LogType_Trace,
11576			    csevent_Severity_Information,
11577			    csevent_AlertLevel_Green,
11578			    csevent_FRU_Firmware,
11579			    csevent_FRU_Unknown,
11580			    "CTL: received unknown task "
11581			    "type: %d (%#x)",
11582			    io->taskio.task_action,
11583			    io->taskio.task_action);
11584#endif
11585	}
11586	switch (io->taskio.task_action) {
11587	case CTL_TASK_ABORT_TASK:
11588		retval = ctl_abort_task(io);
11589		break;
11590	case CTL_TASK_ABORT_TASK_SET:
11591		break;
11592	case CTL_TASK_CLEAR_ACA:
11593		break;
11594	case CTL_TASK_CLEAR_TASK_SET:
11595		break;
11596	case CTL_TASK_LUN_RESET: {
11597		struct ctl_lun *lun;
11598		uint32_t targ_lun;
11599		int retval;
11600
11601		targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11602		mtx_lock(&ctl_softc->ctl_lock);
11603		if ((targ_lun < CTL_MAX_LUNS)
11604		 && (ctl_softc->ctl_luns[targ_lun] != NULL))
11605			lun = ctl_softc->ctl_luns[targ_lun];
11606		else {
11607			mtx_unlock(&ctl_softc->ctl_lock);
11608			retval = 1;
11609			break;
11610		}
11611
11612		if (!(io->io_hdr.flags &
11613		    CTL_FLAG_FROM_OTHER_SC)) {
11614			union ctl_ha_msg msg_info;
11615
11616			io->io_hdr.flags |=
11617				CTL_FLAG_SENT_2OTHER_SC;
11618			msg_info.hdr.msg_type =
11619				CTL_MSG_MANAGE_TASKS;
11620			msg_info.hdr.nexus = io->io_hdr.nexus;
11621			msg_info.task.task_action =
11622				CTL_TASK_LUN_RESET;
11623			msg_info.hdr.original_sc = NULL;
11624			msg_info.hdr.serializing_sc = NULL;
11625			if (CTL_HA_STATUS_SUCCESS !=
11626			    ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11627			    (void *)&msg_info,
11628			    sizeof(msg_info), 0)) {
11629			}
11630		}
11631
11632		retval = ctl_lun_reset(lun, io,
11633				       CTL_UA_LUN_RESET);
11634		mtx_unlock(&ctl_softc->ctl_lock);
11635		break;
11636	}
11637	case CTL_TASK_TARGET_RESET:
11638		retval = ctl_target_reset(ctl_softc, io, CTL_UA_TARG_RESET);
11639		break;
11640	case CTL_TASK_BUS_RESET:
11641		retval = ctl_bus_reset(ctl_softc, io);
11642		break;
11643	case CTL_TASK_PORT_LOGIN:
11644		break;
11645	case CTL_TASK_PORT_LOGOUT:
11646		break;
11647	default:
11648		printf("ctl_run_task: got unknown task management event %d\n",
11649		       io->taskio.task_action);
11650		break;
11651	}
11652	if (retval == 0)
11653		io->io_hdr.status = CTL_SUCCESS;
11654	else
11655		io->io_hdr.status = CTL_ERROR;
11656
11657	/*
11658	 * This will queue this I/O to the done queue, but the
11659	 * work thread won't be able to process it until we
11660	 * return and the lock is released.
11661	 */
11662	ctl_done(io);
11663}
11664
11665/*
11666 * For HA operation.  Handle commands that come in from the other
11667 * controller.
11668 */
11669static void
11670ctl_handle_isc(union ctl_io *io)
11671{
11672	int free_io;
11673	struct ctl_lun *lun;
11674	struct ctl_softc *ctl_softc;
11675	uint32_t targ_lun;
11676
11677	ctl_softc = control_softc;
11678
11679	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11680	lun = ctl_softc->ctl_luns[targ_lun];
11681
11682	switch (io->io_hdr.msg_type) {
11683	case CTL_MSG_SERIALIZE:
11684		free_io = ctl_serialize_other_sc_cmd(&io->scsiio);
11685		break;
11686	case CTL_MSG_R2R: {
11687		uint8_t opcode;
11688		struct ctl_cmd_entry *entry;
11689
11690		/*
11691		 * This is only used in SER_ONLY mode.
11692		 */
11693		free_io = 0;
11694		opcode = io->scsiio.cdb[0];
11695		entry = &ctl_cmd_table[opcode];
11696		mtx_lock(&lun->lun_lock);
11697		if (ctl_scsiio_lun_check(ctl_softc, lun,
11698		    entry, (struct ctl_scsiio *)io) != 0) {
11699			mtx_unlock(&lun->lun_lock);
11700			ctl_done(io);
11701			break;
11702		}
11703		io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11704		mtx_unlock(&lun->lun_lock);
11705		ctl_enqueue_rtr(io);
11706		break;
11707	}
11708	case CTL_MSG_FINISH_IO:
11709		if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
11710			free_io = 0;
11711			ctl_done(io);
11712		} else {
11713			free_io = 1;
11714			mtx_lock(&lun->lun_lock);
11715			TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr,
11716				     ooa_links);
11717			ctl_check_blocked(lun);
11718			mtx_unlock(&lun->lun_lock);
11719		}
11720		break;
11721	case CTL_MSG_PERS_ACTION:
11722		ctl_hndl_per_res_out_on_other_sc(
11723			(union ctl_ha_msg *)&io->presio.pr_msg);
11724		free_io = 1;
11725		break;
11726	case CTL_MSG_BAD_JUJU:
11727		free_io = 0;
11728		ctl_done(io);
11729		break;
11730	case CTL_MSG_DATAMOVE:
11731		/* Only used in XFER mode */
11732		free_io = 0;
11733		ctl_datamove_remote(io);
11734		break;
11735	case CTL_MSG_DATAMOVE_DONE:
11736		/* Only used in XFER mode */
11737		free_io = 0;
11738		io->scsiio.be_move_done(io);
11739		break;
11740	default:
11741		free_io = 1;
11742		printf("%s: Invalid message type %d\n",
11743		       __func__, io->io_hdr.msg_type);
11744		break;
11745	}
11746	if (free_io)
11747		ctl_free_io(io);
11748
11749}
11750
11751
11752/*
11753 * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
11754 * there is no match.
11755 */
11756static ctl_lun_error_pattern
11757ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
11758{
11759	struct ctl_cmd_entry *entry;
11760	ctl_lun_error_pattern filtered_pattern, pattern;
11761	uint8_t opcode;
11762
11763	pattern = desc->error_pattern;
11764
11765	/*
11766	 * XXX KDM we need more data passed into this function to match a
11767	 * custom pattern, and we actually need to implement custom pattern
11768	 * matching.
11769	 */
11770	if (pattern & CTL_LUN_PAT_CMD)
11771		return (CTL_LUN_PAT_CMD);
11772
11773	if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
11774		return (CTL_LUN_PAT_ANY);
11775
11776	opcode = ctsio->cdb[0];
11777	entry = &ctl_cmd_table[opcode];
11778
11779	filtered_pattern = entry->pattern & pattern;
11780
11781	/*
11782	 * If the user requested specific flags in the pattern (e.g.
11783	 * CTL_LUN_PAT_RANGE), make sure the command supports all of those
11784	 * flags.
11785	 *
11786	 * If the user did not specify any flags, it doesn't matter whether
11787	 * or not the command supports the flags.
11788	 */
11789	if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
11790	     (pattern & ~CTL_LUN_PAT_MASK))
11791		return (CTL_LUN_PAT_NONE);
11792
11793	/*
11794	 * If the user asked for a range check, see if the requested LBA
11795	 * range overlaps with this command's LBA range.
11796	 */
11797	if (filtered_pattern & CTL_LUN_PAT_RANGE) {
11798		uint64_t lba1;
11799		uint32_t len1;
11800		ctl_action action;
11801		int retval;
11802
11803		retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
11804		if (retval != 0)
11805			return (CTL_LUN_PAT_NONE);
11806
11807		action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
11808					      desc->lba_range.len);
11809		/*
11810		 * A "pass" means that the LBA ranges don't overlap, so
11811		 * this doesn't match the user's range criteria.
11812		 */
11813		if (action == CTL_ACTION_PASS)
11814			return (CTL_LUN_PAT_NONE);
11815	}
11816
11817	return (filtered_pattern);
11818}
11819
11820static void
11821ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
11822{
11823	struct ctl_error_desc *desc, *desc2;
11824
11825	mtx_assert(&lun->lun_lock, MA_OWNED);
11826
11827	STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
11828		ctl_lun_error_pattern pattern;
11829		/*
11830		 * Check to see whether this particular command matches
11831		 * the pattern in the descriptor.
11832		 */
11833		pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
11834		if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
11835			continue;
11836
11837		switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
11838		case CTL_LUN_INJ_ABORTED:
11839			ctl_set_aborted(&io->scsiio);
11840			break;
11841		case CTL_LUN_INJ_MEDIUM_ERR:
11842			ctl_set_medium_error(&io->scsiio);
11843			break;
11844		case CTL_LUN_INJ_UA:
11845			/* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
11846			 * OCCURRED */
11847			ctl_set_ua(&io->scsiio, 0x29, 0x00);
11848			break;
11849		case CTL_LUN_INJ_CUSTOM:
11850			/*
11851			 * We're assuming the user knows what he is doing.
11852			 * Just copy the sense information without doing
11853			 * checks.
11854			 */
11855			bcopy(&desc->custom_sense, &io->scsiio.sense_data,
11856			      ctl_min(sizeof(desc->custom_sense),
11857				      sizeof(io->scsiio.sense_data)));
11858			io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
11859			io->scsiio.sense_len = SSD_FULL_SIZE;
11860			io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
11861			break;
11862		case CTL_LUN_INJ_NONE:
11863		default:
11864			/*
11865			 * If this is an error injection type we don't know
11866			 * about, clear the continuous flag (if it is set)
11867			 * so it will get deleted below.
11868			 */
11869			desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
11870			break;
11871		}
11872		/*
11873		 * By default, each error injection action is a one-shot
11874		 */
11875		if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
11876			continue;
11877
11878		STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
11879
11880		free(desc, M_CTL);
11881	}
11882}
11883
11884#ifdef CTL_IO_DELAY
11885static void
11886ctl_datamove_timer_wakeup(void *arg)
11887{
11888	union ctl_io *io;
11889
11890	io = (union ctl_io *)arg;
11891
11892	ctl_datamove(io);
11893}
11894#endif /* CTL_IO_DELAY */
11895
11896void
11897ctl_datamove(union ctl_io *io)
11898{
11899	void (*fe_datamove)(union ctl_io *io);
11900
11901	mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
11902
11903	CTL_DEBUG_PRINT(("ctl_datamove\n"));
11904
11905#ifdef CTL_TIME_IO
11906	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
11907		char str[256];
11908		char path_str[64];
11909		struct sbuf sb;
11910
11911		ctl_scsi_path_string(io, path_str, sizeof(path_str));
11912		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
11913
11914		sbuf_cat(&sb, path_str);
11915		switch (io->io_hdr.io_type) {
11916		case CTL_IO_SCSI:
11917			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
11918			sbuf_printf(&sb, "\n");
11919			sbuf_cat(&sb, path_str);
11920			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
11921				    io->scsiio.tag_num, io->scsiio.tag_type);
11922			break;
11923		case CTL_IO_TASK:
11924			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
11925				    "Tag Type: %d\n", io->taskio.task_action,
11926				    io->taskio.tag_num, io->taskio.tag_type);
11927			break;
11928		default:
11929			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
11930			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
11931			break;
11932		}
11933		sbuf_cat(&sb, path_str);
11934		sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
11935			    (intmax_t)time_uptime - io->io_hdr.start_time);
11936		sbuf_finish(&sb);
11937		printf("%s", sbuf_data(&sb));
11938	}
11939#endif /* CTL_TIME_IO */
11940
11941#ifdef CTL_IO_DELAY
11942	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
11943		struct ctl_lun *lun;
11944
11945		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
11946
11947		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
11948	} else {
11949		struct ctl_lun *lun;
11950
11951		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
11952		if ((lun != NULL)
11953		 && (lun->delay_info.datamove_delay > 0)) {
11954			struct callout *callout;
11955
11956			callout = (struct callout *)&io->io_hdr.timer_bytes;
11957			callout_init(callout, /*mpsafe*/ 1);
11958			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
11959			callout_reset(callout,
11960				      lun->delay_info.datamove_delay * hz,
11961				      ctl_datamove_timer_wakeup, io);
11962			if (lun->delay_info.datamove_type ==
11963			    CTL_DELAY_TYPE_ONESHOT)
11964				lun->delay_info.datamove_delay = 0;
11965			return;
11966		}
11967	}
11968#endif
11969
11970	/*
11971	 * This command has been aborted.  Set the port status, so we fail
11972	 * the data move.
11973	 */
11974	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
11975		printf("ctl_datamove: tag 0x%04x on (%ju:%d:%ju:%d) aborted\n",
11976		       io->scsiio.tag_num,(uintmax_t)io->io_hdr.nexus.initid.id,
11977		       io->io_hdr.nexus.targ_port,
11978		       (uintmax_t)io->io_hdr.nexus.targ_target.id,
11979		       io->io_hdr.nexus.targ_lun);
11980		io->io_hdr.status = CTL_CMD_ABORTED;
11981		io->io_hdr.port_status = 31337;
11982		/*
11983		 * Note that the backend, in this case, will get the
11984		 * callback in its context.  In other cases it may get
11985		 * called in the frontend's interrupt thread context.
11986		 */
11987		io->scsiio.be_move_done(io);
11988		return;
11989	}
11990
11991	/*
11992	 * If we're in XFER mode and this I/O is from the other shelf
11993	 * controller, we need to send the DMA to the other side to
11994	 * actually transfer the data to/from the host.  In serialize only
11995	 * mode the transfer happens below CTL and ctl_datamove() is only
11996	 * called on the machine that originally received the I/O.
11997	 */
11998	if ((control_softc->ha_mode == CTL_HA_MODE_XFER)
11999	 && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12000		union ctl_ha_msg msg;
12001		uint32_t sg_entries_sent;
12002		int do_sg_copy;
12003		int i;
12004
12005		memset(&msg, 0, sizeof(msg));
12006		msg.hdr.msg_type = CTL_MSG_DATAMOVE;
12007		msg.hdr.original_sc = io->io_hdr.original_sc;
12008		msg.hdr.serializing_sc = io;
12009		msg.hdr.nexus = io->io_hdr.nexus;
12010		msg.dt.flags = io->io_hdr.flags;
12011		/*
12012		 * We convert everything into a S/G list here.  We can't
12013		 * pass by reference, only by value between controllers.
12014		 * So we can't pass a pointer to the S/G list, only as many
12015		 * S/G entries as we can fit in here.  If it's possible for
12016		 * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
12017		 * then we need to break this up into multiple transfers.
12018		 */
12019		if (io->scsiio.kern_sg_entries == 0) {
12020			msg.dt.kern_sg_entries = 1;
12021			/*
12022			 * If this is in cached memory, flush the cache
12023			 * before we send the DMA request to the other
12024			 * controller.  We want to do this in either the
12025			 * read or the write case.  The read case is
12026			 * straightforward.  In the write case, we want to
12027			 * make sure nothing is in the local cache that
12028			 * could overwrite the DMAed data.
12029			 */
12030			if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12031				/*
12032				 * XXX KDM use bus_dmamap_sync() here.
12033				 */
12034			}
12035
12036			/*
12037			 * Convert to a physical address if this is a
12038			 * virtual address.
12039			 */
12040			if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
12041				msg.dt.sg_list[0].addr =
12042					io->scsiio.kern_data_ptr;
12043			} else {
12044				/*
12045				 * XXX KDM use busdma here!
12046				 */
12047#if 0
12048				msg.dt.sg_list[0].addr = (void *)
12049					vtophys(io->scsiio.kern_data_ptr);
12050#endif
12051			}
12052
12053			msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
12054			do_sg_copy = 0;
12055		} else {
12056			struct ctl_sg_entry *sgl;
12057
12058			do_sg_copy = 1;
12059			msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
12060			sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
12061			if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12062				/*
12063				 * XXX KDM use bus_dmamap_sync() here.
12064				 */
12065			}
12066		}
12067
12068		msg.dt.kern_data_len = io->scsiio.kern_data_len;
12069		msg.dt.kern_total_len = io->scsiio.kern_total_len;
12070		msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
12071		msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
12072		msg.dt.sg_sequence = 0;
12073
12074		/*
12075		 * Loop until we've sent all of the S/G entries.  On the
12076		 * other end, we'll recompose these S/G entries into one
12077		 * contiguous list before passing it to the
12078		 */
12079		for (sg_entries_sent = 0; sg_entries_sent <
12080		     msg.dt.kern_sg_entries; msg.dt.sg_sequence++) {
12081			msg.dt.cur_sg_entries = ctl_min((sizeof(msg.dt.sg_list)/
12082				sizeof(msg.dt.sg_list[0])),
12083				msg.dt.kern_sg_entries - sg_entries_sent);
12084
12085			if (do_sg_copy != 0) {
12086				struct ctl_sg_entry *sgl;
12087				int j;
12088
12089				sgl = (struct ctl_sg_entry *)
12090					io->scsiio.kern_data_ptr;
12091				/*
12092				 * If this is in cached memory, flush the cache
12093				 * before we send the DMA request to the other
12094				 * controller.  We want to do this in either
12095				 * the * read or the write case.  The read
12096				 * case is straightforward.  In the write
12097				 * case, we want to make sure nothing is
12098				 * in the local cache that could overwrite
12099				 * the DMAed data.
12100				 */
12101
12102				for (i = sg_entries_sent, j = 0;
12103				     i < msg.dt.cur_sg_entries; i++, j++) {
12104					if ((io->io_hdr.flags &
12105					     CTL_FLAG_NO_DATASYNC) == 0) {
12106						/*
12107						 * XXX KDM use bus_dmamap_sync()
12108						 */
12109					}
12110					if ((io->io_hdr.flags &
12111					     CTL_FLAG_BUS_ADDR) == 0) {
12112						/*
12113						 * XXX KDM use busdma.
12114						 */
12115#if 0
12116						msg.dt.sg_list[j].addr =(void *)
12117						       vtophys(sgl[i].addr);
12118#endif
12119					} else {
12120						msg.dt.sg_list[j].addr =
12121							sgl[i].addr;
12122					}
12123					msg.dt.sg_list[j].len = sgl[i].len;
12124				}
12125			}
12126
12127			sg_entries_sent += msg.dt.cur_sg_entries;
12128			if (sg_entries_sent >= msg.dt.kern_sg_entries)
12129				msg.dt.sg_last = 1;
12130			else
12131				msg.dt.sg_last = 0;
12132
12133			/*
12134			 * XXX KDM drop and reacquire the lock here?
12135			 */
12136			if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12137			    sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
12138				/*
12139				 * XXX do something here.
12140				 */
12141			}
12142
12143			msg.dt.sent_sg_entries = sg_entries_sent;
12144		}
12145		io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12146		if (io->io_hdr.flags & CTL_FLAG_FAILOVER)
12147			ctl_failover_io(io, /*have_lock*/ 0);
12148
12149	} else {
12150
12151		/*
12152		 * Lookup the fe_datamove() function for this particular
12153		 * front end.
12154		 */
12155		fe_datamove =
12156		    control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12157
12158		fe_datamove(io);
12159	}
12160}
12161
12162static void
12163ctl_send_datamove_done(union ctl_io *io, int have_lock)
12164{
12165	union ctl_ha_msg msg;
12166	int isc_status;
12167
12168	memset(&msg, 0, sizeof(msg));
12169
12170	msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12171	msg.hdr.original_sc = io;
12172	msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12173	msg.hdr.nexus = io->io_hdr.nexus;
12174	msg.hdr.status = io->io_hdr.status;
12175	msg.scsi.tag_num = io->scsiio.tag_num;
12176	msg.scsi.tag_type = io->scsiio.tag_type;
12177	msg.scsi.scsi_status = io->scsiio.scsi_status;
12178	memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12179	       sizeof(io->scsiio.sense_data));
12180	msg.scsi.sense_len = io->scsiio.sense_len;
12181	msg.scsi.sense_residual = io->scsiio.sense_residual;
12182	msg.scsi.fetd_status = io->io_hdr.port_status;
12183	msg.scsi.residual = io->scsiio.residual;
12184	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12185
12186	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12187		ctl_failover_io(io, /*have_lock*/ have_lock);
12188		return;
12189	}
12190
12191	isc_status = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0);
12192	if (isc_status > CTL_HA_STATUS_SUCCESS) {
12193		/* XXX do something if this fails */
12194	}
12195
12196}
12197
12198/*
12199 * The DMA to the remote side is done, now we need to tell the other side
12200 * we're done so it can continue with its data movement.
12201 */
12202static void
12203ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12204{
12205	union ctl_io *io;
12206
12207	io = rq->context;
12208
12209	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12210		printf("%s: ISC DMA write failed with error %d", __func__,
12211		       rq->ret);
12212		ctl_set_internal_failure(&io->scsiio,
12213					 /*sks_valid*/ 1,
12214					 /*retry_count*/ rq->ret);
12215	}
12216
12217	ctl_dt_req_free(rq);
12218
12219	/*
12220	 * In this case, we had to malloc the memory locally.  Free it.
12221	 */
12222	if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
12223		int i;
12224		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12225			free(io->io_hdr.local_sglist[i].addr, M_CTL);
12226	}
12227	/*
12228	 * The data is in local and remote memory, so now we need to send
12229	 * status (good or back) back to the other side.
12230	 */
12231	ctl_send_datamove_done(io, /*have_lock*/ 0);
12232}
12233
12234/*
12235 * We've moved the data from the host/controller into local memory.  Now we
12236 * need to push it over to the remote controller's memory.
12237 */
12238static int
12239ctl_datamove_remote_dm_write_cb(union ctl_io *io)
12240{
12241	int retval;
12242
12243	retval = 0;
12244
12245	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
12246					  ctl_datamove_remote_write_cb);
12247
12248	return (retval);
12249}
12250
12251static void
12252ctl_datamove_remote_write(union ctl_io *io)
12253{
12254	int retval;
12255	void (*fe_datamove)(union ctl_io *io);
12256
12257	/*
12258	 * - Get the data from the host/HBA into local memory.
12259	 * - DMA memory from the local controller to the remote controller.
12260	 * - Send status back to the remote controller.
12261	 */
12262
12263	retval = ctl_datamove_remote_sgl_setup(io);
12264	if (retval != 0)
12265		return;
12266
12267	/* Switch the pointer over so the FETD knows what to do */
12268	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12269
12270	/*
12271	 * Use a custom move done callback, since we need to send completion
12272	 * back to the other controller, not to the backend on this side.
12273	 */
12274	io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
12275
12276	fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12277
12278	fe_datamove(io);
12279
12280	return;
12281
12282}
12283
12284static int
12285ctl_datamove_remote_dm_read_cb(union ctl_io *io)
12286{
12287#if 0
12288	char str[256];
12289	char path_str[64];
12290	struct sbuf sb;
12291#endif
12292
12293	/*
12294	 * In this case, we had to malloc the memory locally.  Free it.
12295	 */
12296	if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
12297		int i;
12298		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12299			free(io->io_hdr.local_sglist[i].addr, M_CTL);
12300	}
12301
12302#if 0
12303	scsi_path_string(io, path_str, sizeof(path_str));
12304	sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12305	sbuf_cat(&sb, path_str);
12306	scsi_command_string(&io->scsiio, NULL, &sb);
12307	sbuf_printf(&sb, "\n");
12308	sbuf_cat(&sb, path_str);
12309	sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12310		    io->scsiio.tag_num, io->scsiio.tag_type);
12311	sbuf_cat(&sb, path_str);
12312	sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
12313		    io->io_hdr.flags, io->io_hdr.status);
12314	sbuf_finish(&sb);
12315	printk("%s", sbuf_data(&sb));
12316#endif
12317
12318
12319	/*
12320	 * The read is done, now we need to send status (good or bad) back
12321	 * to the other side.
12322	 */
12323	ctl_send_datamove_done(io, /*have_lock*/ 0);
12324
12325	return (0);
12326}
12327
12328static void
12329ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
12330{
12331	union ctl_io *io;
12332	void (*fe_datamove)(union ctl_io *io);
12333
12334	io = rq->context;
12335
12336	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12337		printf("%s: ISC DMA read failed with error %d", __func__,
12338		       rq->ret);
12339		ctl_set_internal_failure(&io->scsiio,
12340					 /*sks_valid*/ 1,
12341					 /*retry_count*/ rq->ret);
12342	}
12343
12344	ctl_dt_req_free(rq);
12345
12346	/* Switch the pointer over so the FETD knows what to do */
12347	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12348
12349	/*
12350	 * Use a custom move done callback, since we need to send completion
12351	 * back to the other controller, not to the backend on this side.
12352	 */
12353	io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
12354
12355	/* XXX KDM add checks like the ones in ctl_datamove? */
12356
12357	fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12358
12359	fe_datamove(io);
12360}
12361
12362static int
12363ctl_datamove_remote_sgl_setup(union ctl_io *io)
12364{
12365	struct ctl_sg_entry *local_sglist, *remote_sglist;
12366	struct ctl_sg_entry *local_dma_sglist, *remote_dma_sglist;
12367	struct ctl_softc *softc;
12368	int retval;
12369	int i;
12370
12371	retval = 0;
12372	softc = control_softc;
12373
12374	local_sglist = io->io_hdr.local_sglist;
12375	local_dma_sglist = io->io_hdr.local_dma_sglist;
12376	remote_sglist = io->io_hdr.remote_sglist;
12377	remote_dma_sglist = io->io_hdr.remote_dma_sglist;
12378
12379	if (io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) {
12380		for (i = 0; i < io->scsiio.kern_sg_entries; i++) {
12381			local_sglist[i].len = remote_sglist[i].len;
12382
12383			/*
12384			 * XXX Detect the situation where the RS-level I/O
12385			 * redirector on the other side has already read the
12386			 * data off of the AOR RS on this side, and
12387			 * transferred it to remote (mirror) memory on the
12388			 * other side.  Since we already have the data in
12389			 * memory here, we just need to use it.
12390			 *
12391			 * XXX KDM this can probably be removed once we
12392			 * get the cache device code in and take the
12393			 * current AOR implementation out.
12394			 */
12395#ifdef NEEDTOPORT
12396			if ((remote_sglist[i].addr >=
12397			     (void *)vtophys(softc->mirr->addr))
12398			 && (remote_sglist[i].addr <
12399			     ((void *)vtophys(softc->mirr->addr) +
12400			     CacheMirrorOffset))) {
12401				local_sglist[i].addr = remote_sglist[i].addr -
12402					CacheMirrorOffset;
12403				if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
12404				     CTL_FLAG_DATA_IN)
12405					io->io_hdr.flags |= CTL_FLAG_REDIR_DONE;
12406			} else {
12407				local_sglist[i].addr = remote_sglist[i].addr +
12408					CacheMirrorOffset;
12409			}
12410#endif
12411#if 0
12412			printf("%s: local %p, remote %p, len %d\n",
12413			       __func__, local_sglist[i].addr,
12414			       remote_sglist[i].addr, local_sglist[i].len);
12415#endif
12416		}
12417	} else {
12418		uint32_t len_to_go;
12419
12420		/*
12421		 * In this case, we don't have automatically allocated
12422		 * memory for this I/O on this controller.  This typically
12423		 * happens with internal CTL I/O -- e.g. inquiry, mode
12424		 * sense, etc.  Anything coming from RAIDCore will have
12425		 * a mirror area available.
12426		 */
12427		len_to_go = io->scsiio.kern_data_len;
12428
12429		/*
12430		 * Clear the no datasync flag, we have to use malloced
12431		 * buffers.
12432		 */
12433		io->io_hdr.flags &= ~CTL_FLAG_NO_DATASYNC;
12434
12435		/*
12436		 * The difficult thing here is that the size of the various
12437		 * S/G segments may be different than the size from the
12438		 * remote controller.  That'll make it harder when DMAing
12439		 * the data back to the other side.
12440		 */
12441		for (i = 0; (i < sizeof(io->io_hdr.remote_sglist) /
12442		     sizeof(io->io_hdr.remote_sglist[0])) &&
12443		     (len_to_go > 0); i++) {
12444			local_sglist[i].len = ctl_min(len_to_go, 131072);
12445			CTL_SIZE_8B(local_dma_sglist[i].len,
12446				    local_sglist[i].len);
12447			local_sglist[i].addr =
12448				malloc(local_dma_sglist[i].len, M_CTL,M_WAITOK);
12449
12450			local_dma_sglist[i].addr = local_sglist[i].addr;
12451
12452			if (local_sglist[i].addr == NULL) {
12453				int j;
12454
12455				printf("malloc failed for %zd bytes!",
12456				       local_dma_sglist[i].len);
12457				for (j = 0; j < i; j++) {
12458					free(local_sglist[j].addr, M_CTL);
12459				}
12460				ctl_set_internal_failure(&io->scsiio,
12461							 /*sks_valid*/ 1,
12462							 /*retry_count*/ 4857);
12463				retval = 1;
12464				goto bailout_error;
12465
12466			}
12467			/* XXX KDM do we need a sync here? */
12468
12469			len_to_go -= local_sglist[i].len;
12470		}
12471		/*
12472		 * Reset the number of S/G entries accordingly.  The
12473		 * original number of S/G entries is available in
12474		 * rem_sg_entries.
12475		 */
12476		io->scsiio.kern_sg_entries = i;
12477
12478#if 0
12479		printf("%s: kern_sg_entries = %d\n", __func__,
12480		       io->scsiio.kern_sg_entries);
12481		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12482			printf("%s: sg[%d] = %p, %d (DMA: %d)\n", __func__, i,
12483			       local_sglist[i].addr, local_sglist[i].len,
12484			       local_dma_sglist[i].len);
12485#endif
12486	}
12487
12488
12489	return (retval);
12490
12491bailout_error:
12492
12493	ctl_send_datamove_done(io, /*have_lock*/ 0);
12494
12495	return (retval);
12496}
12497
12498static int
12499ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
12500			 ctl_ha_dt_cb callback)
12501{
12502	struct ctl_ha_dt_req *rq;
12503	struct ctl_sg_entry *remote_sglist, *local_sglist;
12504	struct ctl_sg_entry *remote_dma_sglist, *local_dma_sglist;
12505	uint32_t local_used, remote_used, total_used;
12506	int retval;
12507	int i, j;
12508
12509	retval = 0;
12510
12511	rq = ctl_dt_req_alloc();
12512
12513	/*
12514	 * If we failed to allocate the request, and if the DMA didn't fail
12515	 * anyway, set busy status.  This is just a resource allocation
12516	 * failure.
12517	 */
12518	if ((rq == NULL)
12519	 && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE))
12520		ctl_set_busy(&io->scsiio);
12521
12522	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE) {
12523
12524		if (rq != NULL)
12525			ctl_dt_req_free(rq);
12526
12527		/*
12528		 * The data move failed.  We need to return status back
12529		 * to the other controller.  No point in trying to DMA
12530		 * data to the remote controller.
12531		 */
12532
12533		ctl_send_datamove_done(io, /*have_lock*/ 0);
12534
12535		retval = 1;
12536
12537		goto bailout;
12538	}
12539
12540	local_sglist = io->io_hdr.local_sglist;
12541	local_dma_sglist = io->io_hdr.local_dma_sglist;
12542	remote_sglist = io->io_hdr.remote_sglist;
12543	remote_dma_sglist = io->io_hdr.remote_dma_sglist;
12544	local_used = 0;
12545	remote_used = 0;
12546	total_used = 0;
12547
12548	if (io->io_hdr.flags & CTL_FLAG_REDIR_DONE) {
12549		rq->ret = CTL_HA_STATUS_SUCCESS;
12550		rq->context = io;
12551		callback(rq);
12552		goto bailout;
12553	}
12554
12555	/*
12556	 * Pull/push the data over the wire from/to the other controller.
12557	 * This takes into account the possibility that the local and
12558	 * remote sglists may not be identical in terms of the size of
12559	 * the elements and the number of elements.
12560	 *
12561	 * One fundamental assumption here is that the length allocated for
12562	 * both the local and remote sglists is identical.  Otherwise, we've
12563	 * essentially got a coding error of some sort.
12564	 */
12565	for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
12566		int isc_ret;
12567		uint32_t cur_len, dma_length;
12568		uint8_t *tmp_ptr;
12569
12570		rq->id = CTL_HA_DATA_CTL;
12571		rq->command = command;
12572		rq->context = io;
12573
12574		/*
12575		 * Both pointers should be aligned.  But it is possible
12576		 * that the allocation length is not.  They should both
12577		 * also have enough slack left over at the end, though,
12578		 * to round up to the next 8 byte boundary.
12579		 */
12580		cur_len = ctl_min(local_sglist[i].len - local_used,
12581				  remote_sglist[j].len - remote_used);
12582
12583		/*
12584		 * In this case, we have a size issue and need to decrease
12585		 * the size, except in the case where we actually have less
12586		 * than 8 bytes left.  In that case, we need to increase
12587		 * the DMA length to get the last bit.
12588		 */
12589		if ((cur_len & 0x7) != 0) {
12590			if (cur_len > 0x7) {
12591				cur_len = cur_len - (cur_len & 0x7);
12592				dma_length = cur_len;
12593			} else {
12594				CTL_SIZE_8B(dma_length, cur_len);
12595			}
12596
12597		} else
12598			dma_length = cur_len;
12599
12600		/*
12601		 * If we had to allocate memory for this I/O, instead of using
12602		 * the non-cached mirror memory, we'll need to flush the cache
12603		 * before trying to DMA to the other controller.
12604		 *
12605		 * We could end up doing this multiple times for the same
12606		 * segment if we have a larger local segment than remote
12607		 * segment.  That shouldn't be an issue.
12608		 */
12609		if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12610			/*
12611			 * XXX KDM use bus_dmamap_sync() here.
12612			 */
12613		}
12614
12615		rq->size = dma_length;
12616
12617		tmp_ptr = (uint8_t *)local_sglist[i].addr;
12618		tmp_ptr += local_used;
12619
12620		/* Use physical addresses when talking to ISC hardware */
12621		if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
12622			/* XXX KDM use busdma */
12623#if 0
12624			rq->local = vtophys(tmp_ptr);
12625#endif
12626		} else
12627			rq->local = tmp_ptr;
12628
12629		tmp_ptr = (uint8_t *)remote_sglist[j].addr;
12630		tmp_ptr += remote_used;
12631		rq->remote = tmp_ptr;
12632
12633		rq->callback = NULL;
12634
12635		local_used += cur_len;
12636		if (local_used >= local_sglist[i].len) {
12637			i++;
12638			local_used = 0;
12639		}
12640
12641		remote_used += cur_len;
12642		if (remote_used >= remote_sglist[j].len) {
12643			j++;
12644			remote_used = 0;
12645		}
12646		total_used += cur_len;
12647
12648		if (total_used >= io->scsiio.kern_data_len)
12649			rq->callback = callback;
12650
12651		if ((rq->size & 0x7) != 0) {
12652			printf("%s: warning: size %d is not on 8b boundary\n",
12653			       __func__, rq->size);
12654		}
12655		if (((uintptr_t)rq->local & 0x7) != 0) {
12656			printf("%s: warning: local %p not on 8b boundary\n",
12657			       __func__, rq->local);
12658		}
12659		if (((uintptr_t)rq->remote & 0x7) != 0) {
12660			printf("%s: warning: remote %p not on 8b boundary\n",
12661			       __func__, rq->local);
12662		}
12663#if 0
12664		printf("%s: %s: local %#x remote %#x size %d\n", __func__,
12665		       (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
12666		       rq->local, rq->remote, rq->size);
12667#endif
12668
12669		isc_ret = ctl_dt_single(rq);
12670		if (isc_ret == CTL_HA_STATUS_WAIT)
12671			continue;
12672
12673		if (isc_ret == CTL_HA_STATUS_DISCONNECT) {
12674			rq->ret = CTL_HA_STATUS_SUCCESS;
12675		} else {
12676			rq->ret = isc_ret;
12677		}
12678		callback(rq);
12679		goto bailout;
12680	}
12681
12682bailout:
12683	return (retval);
12684
12685}
12686
12687static void
12688ctl_datamove_remote_read(union ctl_io *io)
12689{
12690	int retval;
12691	int i;
12692
12693	/*
12694	 * This will send an error to the other controller in the case of a
12695	 * failure.
12696	 */
12697	retval = ctl_datamove_remote_sgl_setup(io);
12698	if (retval != 0)
12699		return;
12700
12701	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
12702					  ctl_datamove_remote_read_cb);
12703	if ((retval != 0)
12704	 && ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0)) {
12705		/*
12706		 * Make sure we free memory if there was an error..  The
12707		 * ctl_datamove_remote_xfer() function will send the
12708		 * datamove done message, or call the callback with an
12709		 * error if there is a problem.
12710		 */
12711		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12712			free(io->io_hdr.local_sglist[i].addr, M_CTL);
12713	}
12714
12715	return;
12716}
12717
12718/*
12719 * Process a datamove request from the other controller.  This is used for
12720 * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
12721 * first.  Once that is complete, the data gets DMAed into the remote
12722 * controller's memory.  For reads, we DMA from the remote controller's
12723 * memory into our memory first, and then move it out to the FETD.
12724 */
12725static void
12726ctl_datamove_remote(union ctl_io *io)
12727{
12728	struct ctl_softc *softc;
12729
12730	softc = control_softc;
12731
12732	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
12733
12734	/*
12735	 * Note that we look for an aborted I/O here, but don't do some of
12736	 * the other checks that ctl_datamove() normally does.  We don't
12737	 * need to run the task queue, because this I/O is on the ISC
12738	 * queue, which is executed by the work thread after the task queue.
12739	 * We don't need to run the datamove delay code, since that should
12740	 * have been done if need be on the other controller.
12741	 */
12742	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12743
12744		printf("%s: tag 0x%04x on (%d:%d:%d:%d) aborted\n", __func__,
12745		       io->scsiio.tag_num, io->io_hdr.nexus.initid.id,
12746		       io->io_hdr.nexus.targ_port,
12747		       io->io_hdr.nexus.targ_target.id,
12748		       io->io_hdr.nexus.targ_lun);
12749		io->io_hdr.status = CTL_CMD_ABORTED;
12750		io->io_hdr.port_status = 31338;
12751
12752		ctl_send_datamove_done(io, /*have_lock*/ 0);
12753
12754		return;
12755	}
12756
12757	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT) {
12758		ctl_datamove_remote_write(io);
12759	} else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN){
12760		ctl_datamove_remote_read(io);
12761	} else {
12762		union ctl_ha_msg msg;
12763		struct scsi_sense_data *sense;
12764		uint8_t sks[3];
12765		int retry_count;
12766
12767		memset(&msg, 0, sizeof(msg));
12768
12769		msg.hdr.msg_type = CTL_MSG_BAD_JUJU;
12770		msg.hdr.status = CTL_SCSI_ERROR;
12771		msg.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
12772
12773		retry_count = 4243;
12774
12775		sense = &msg.scsi.sense_data;
12776		sks[0] = SSD_SCS_VALID;
12777		sks[1] = (retry_count >> 8) & 0xff;
12778		sks[2] = retry_count & 0xff;
12779
12780		/* "Internal target failure" */
12781		scsi_set_sense_data(sense,
12782				    /*sense_format*/ SSD_TYPE_NONE,
12783				    /*current_error*/ 1,
12784				    /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
12785				    /*asc*/ 0x44,
12786				    /*ascq*/ 0x00,
12787				    /*type*/ SSD_ELEM_SKS,
12788				    /*size*/ sizeof(sks),
12789				    /*data*/ sks,
12790				    SSD_ELEM_NONE);
12791
12792		io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12793		if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12794			ctl_failover_io(io, /*have_lock*/ 1);
12795			return;
12796		}
12797
12798		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0) >
12799		    CTL_HA_STATUS_SUCCESS) {
12800			/* XXX KDM what to do if this fails? */
12801		}
12802		return;
12803	}
12804
12805}
12806
12807static int
12808ctl_process_done(union ctl_io *io)
12809{
12810	struct ctl_lun *lun;
12811	struct ctl_softc *ctl_softc;
12812	void (*fe_done)(union ctl_io *io);
12813	uint32_t targ_port = ctl_port_idx(io->io_hdr.nexus.targ_port);
12814
12815	CTL_DEBUG_PRINT(("ctl_process_done\n"));
12816
12817	fe_done =
12818	    control_softc->ctl_ports[targ_port]->fe_done;
12819
12820#ifdef CTL_TIME_IO
12821	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12822		char str[256];
12823		char path_str[64];
12824		struct sbuf sb;
12825
12826		ctl_scsi_path_string(io, path_str, sizeof(path_str));
12827		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12828
12829		sbuf_cat(&sb, path_str);
12830		switch (io->io_hdr.io_type) {
12831		case CTL_IO_SCSI:
12832			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12833			sbuf_printf(&sb, "\n");
12834			sbuf_cat(&sb, path_str);
12835			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12836				    io->scsiio.tag_num, io->scsiio.tag_type);
12837			break;
12838		case CTL_IO_TASK:
12839			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12840				    "Tag Type: %d\n", io->taskio.task_action,
12841				    io->taskio.tag_num, io->taskio.tag_type);
12842			break;
12843		default:
12844			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12845			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12846			break;
12847		}
12848		sbuf_cat(&sb, path_str);
12849		sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
12850			    (intmax_t)time_uptime - io->io_hdr.start_time);
12851		sbuf_finish(&sb);
12852		printf("%s", sbuf_data(&sb));
12853	}
12854#endif /* CTL_TIME_IO */
12855
12856	switch (io->io_hdr.io_type) {
12857	case CTL_IO_SCSI:
12858		break;
12859	case CTL_IO_TASK:
12860		if (bootverbose || verbose > 0)
12861			ctl_io_error_print(io, NULL);
12862		if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
12863			ctl_free_io(io);
12864		else
12865			fe_done(io);
12866		return (CTL_RETVAL_COMPLETE);
12867		break;
12868	default:
12869		printf("ctl_process_done: invalid io type %d\n",
12870		       io->io_hdr.io_type);
12871		panic("ctl_process_done: invalid io type %d\n",
12872		      io->io_hdr.io_type);
12873		break; /* NOTREACHED */
12874	}
12875
12876	lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12877	if (lun == NULL) {
12878		CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
12879				 io->io_hdr.nexus.targ_mapped_lun));
12880		fe_done(io);
12881		goto bailout;
12882	}
12883	ctl_softc = lun->ctl_softc;
12884
12885	mtx_lock(&lun->lun_lock);
12886
12887	/*
12888	 * Check to see if we have any errors to inject here.  We only
12889	 * inject errors for commands that don't already have errors set.
12890	 */
12891	if ((STAILQ_FIRST(&lun->error_list) != NULL)
12892	 && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS))
12893		ctl_inject_error(lun, io);
12894
12895	/*
12896	 * XXX KDM how do we treat commands that aren't completed
12897	 * successfully?
12898	 *
12899	 * XXX KDM should we also track I/O latency?
12900	 */
12901	if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
12902	    io->io_hdr.io_type == CTL_IO_SCSI) {
12903#ifdef CTL_TIME_IO
12904		struct bintime cur_bt;
12905#endif
12906		int type;
12907
12908		if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
12909		    CTL_FLAG_DATA_IN)
12910			type = CTL_STATS_READ;
12911		else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
12912		    CTL_FLAG_DATA_OUT)
12913			type = CTL_STATS_WRITE;
12914		else
12915			type = CTL_STATS_NO_IO;
12916
12917		lun->stats.ports[targ_port].bytes[type] +=
12918		    io->scsiio.kern_total_len;
12919		lun->stats.ports[targ_port].operations[type]++;
12920#ifdef CTL_TIME_IO
12921		bintime_add(&lun->stats.ports[targ_port].dma_time[type],
12922		   &io->io_hdr.dma_bt);
12923		lun->stats.ports[targ_port].num_dmas[type] +=
12924		    io->io_hdr.num_dmas;
12925		getbintime(&cur_bt);
12926		bintime_sub(&cur_bt, &io->io_hdr.start_bt);
12927		bintime_add(&lun->stats.ports[targ_port].time[type], &cur_bt);
12928#endif
12929	}
12930
12931	/*
12932	 * Remove this from the OOA queue.
12933	 */
12934	TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
12935
12936	/*
12937	 * Run through the blocked queue on this LUN and see if anything
12938	 * has become unblocked, now that this transaction is done.
12939	 */
12940	ctl_check_blocked(lun);
12941
12942	/*
12943	 * If the LUN has been invalidated, free it if there is nothing
12944	 * left on its OOA queue.
12945	 */
12946	if ((lun->flags & CTL_LUN_INVALID)
12947	 && TAILQ_EMPTY(&lun->ooa_queue)) {
12948		mtx_unlock(&lun->lun_lock);
12949		mtx_lock(&ctl_softc->ctl_lock);
12950		ctl_free_lun(lun);
12951		mtx_unlock(&ctl_softc->ctl_lock);
12952	} else
12953		mtx_unlock(&lun->lun_lock);
12954
12955	/*
12956	 * If this command has been aborted, make sure we set the status
12957	 * properly.  The FETD is responsible for freeing the I/O and doing
12958	 * whatever it needs to do to clean up its state.
12959	 */
12960	if (io->io_hdr.flags & CTL_FLAG_ABORT)
12961		io->io_hdr.status = CTL_CMD_ABORTED;
12962
12963	/*
12964	 * We print out status for every task management command.  For SCSI
12965	 * commands, we filter out any unit attention errors; they happen
12966	 * on every boot, and would clutter up the log.  Note:  task
12967	 * management commands aren't printed here, they are printed above,
12968	 * since they should never even make it down here.
12969	 */
12970	switch (io->io_hdr.io_type) {
12971	case CTL_IO_SCSI: {
12972		int error_code, sense_key, asc, ascq;
12973
12974		sense_key = 0;
12975
12976		if (((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SCSI_ERROR)
12977		 && (io->scsiio.scsi_status == SCSI_STATUS_CHECK_COND)) {
12978			/*
12979			 * Since this is just for printing, no need to
12980			 * show errors here.
12981			 */
12982			scsi_extract_sense_len(&io->scsiio.sense_data,
12983					       io->scsiio.sense_len,
12984					       &error_code,
12985					       &sense_key,
12986					       &asc,
12987					       &ascq,
12988					       /*show_errors*/ 0);
12989		}
12990
12991		if (((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)
12992		 && (((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SCSI_ERROR)
12993		  || (io->scsiio.scsi_status != SCSI_STATUS_CHECK_COND)
12994		  || (sense_key != SSD_KEY_UNIT_ATTENTION))) {
12995
12996			if ((time_uptime - ctl_softc->last_print_jiffies) <= 0){
12997				ctl_softc->skipped_prints++;
12998			} else {
12999				uint32_t skipped_prints;
13000
13001				skipped_prints = ctl_softc->skipped_prints;
13002
13003				ctl_softc->skipped_prints = 0;
13004				ctl_softc->last_print_jiffies = time_uptime;
13005
13006				if (skipped_prints > 0) {
13007#ifdef NEEDTOPORT
13008					csevent_log(CSC_CTL | CSC_SHELF_SW |
13009					    CTL_ERROR_REPORT,
13010					    csevent_LogType_Trace,
13011					    csevent_Severity_Information,
13012					    csevent_AlertLevel_Green,
13013					    csevent_FRU_Firmware,
13014					    csevent_FRU_Unknown,
13015					    "High CTL error volume, %d prints "
13016					    "skipped", skipped_prints);
13017#endif
13018				}
13019				if (bootverbose || verbose > 0)
13020					ctl_io_error_print(io, NULL);
13021			}
13022		}
13023		break;
13024	}
13025	case CTL_IO_TASK:
13026		if (bootverbose || verbose > 0)
13027			ctl_io_error_print(io, NULL);
13028		break;
13029	default:
13030		break;
13031	}
13032
13033	/*
13034	 * Tell the FETD or the other shelf controller we're done with this
13035	 * command.  Note that only SCSI commands get to this point.  Task
13036	 * management commands are completed above.
13037	 *
13038	 * We only send status to the other controller if we're in XFER
13039	 * mode.  In SER_ONLY mode, the I/O is done on the controller that
13040	 * received the I/O (from CTL's perspective), and so the status is
13041	 * generated there.
13042	 *
13043	 * XXX KDM if we hold the lock here, we could cause a deadlock
13044	 * if the frontend comes back in in this context to queue
13045	 * something.
13046	 */
13047	if ((ctl_softc->ha_mode == CTL_HA_MODE_XFER)
13048	 && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
13049		union ctl_ha_msg msg;
13050
13051		memset(&msg, 0, sizeof(msg));
13052		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13053		msg.hdr.original_sc = io->io_hdr.original_sc;
13054		msg.hdr.nexus = io->io_hdr.nexus;
13055		msg.hdr.status = io->io_hdr.status;
13056		msg.scsi.scsi_status = io->scsiio.scsi_status;
13057		msg.scsi.tag_num = io->scsiio.tag_num;
13058		msg.scsi.tag_type = io->scsiio.tag_type;
13059		msg.scsi.sense_len = io->scsiio.sense_len;
13060		msg.scsi.sense_residual = io->scsiio.sense_residual;
13061		msg.scsi.residual = io->scsiio.residual;
13062		memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
13063		       sizeof(io->scsiio.sense_data));
13064		/*
13065		 * We copy this whether or not this is an I/O-related
13066		 * command.  Otherwise, we'd have to go and check to see
13067		 * whether it's a read/write command, and it really isn't
13068		 * worth it.
13069		 */
13070		memcpy(&msg.scsi.lbalen,
13071		       &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
13072		       sizeof(msg.scsi.lbalen));
13073
13074		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13075				sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
13076			/* XXX do something here */
13077		}
13078
13079		ctl_free_io(io);
13080	} else
13081		fe_done(io);
13082
13083bailout:
13084
13085	return (CTL_RETVAL_COMPLETE);
13086}
13087
13088/*
13089 * Front end should call this if it doesn't do autosense.  When the request
13090 * sense comes back in from the initiator, we'll dequeue this and send it.
13091 */
13092int
13093ctl_queue_sense(union ctl_io *io)
13094{
13095	struct ctl_lun *lun;
13096	struct ctl_softc *ctl_softc;
13097	uint32_t initidx, targ_lun;
13098
13099	ctl_softc = control_softc;
13100
13101	CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13102
13103	/*
13104	 * LUN lookup will likely move to the ctl_work_thread() once we
13105	 * have our new queueing infrastructure (that doesn't put things on
13106	 * a per-LUN queue initially).  That is so that we can handle
13107	 * things like an INQUIRY to a LUN that we don't have enabled.  We
13108	 * can't deal with that right now.
13109	 */
13110	mtx_lock(&ctl_softc->ctl_lock);
13111
13112	/*
13113	 * If we don't have a LUN for this, just toss the sense
13114	 * information.
13115	 */
13116	targ_lun = io->io_hdr.nexus.targ_lun;
13117	if (io->io_hdr.nexus.lun_map_fn != NULL)
13118		targ_lun = io->io_hdr.nexus.lun_map_fn(io->io_hdr.nexus.lun_map_arg, targ_lun);
13119	if ((targ_lun < CTL_MAX_LUNS)
13120	 && (ctl_softc->ctl_luns[targ_lun] != NULL))
13121		lun = ctl_softc->ctl_luns[targ_lun];
13122	else
13123		goto bailout;
13124
13125	initidx = ctl_get_initindex(&io->io_hdr.nexus);
13126
13127	mtx_lock(&lun->lun_lock);
13128	/*
13129	 * Already have CA set for this LUN...toss the sense information.
13130	 */
13131	if (ctl_is_set(lun->have_ca, initidx)) {
13132		mtx_unlock(&lun->lun_lock);
13133		goto bailout;
13134	}
13135
13136	memcpy(&lun->pending_sense[initidx].sense, &io->scsiio.sense_data,
13137	       ctl_min(sizeof(lun->pending_sense[initidx].sense),
13138	       sizeof(io->scsiio.sense_data)));
13139	ctl_set_mask(lun->have_ca, initidx);
13140	mtx_unlock(&lun->lun_lock);
13141
13142bailout:
13143	mtx_unlock(&ctl_softc->ctl_lock);
13144
13145	ctl_free_io(io);
13146
13147	return (CTL_RETVAL_COMPLETE);
13148}
13149
13150/*
13151 * Primary command inlet from frontend ports.  All SCSI and task I/O
13152 * requests must go through this function.
13153 */
13154int
13155ctl_queue(union ctl_io *io)
13156{
13157	struct ctl_softc *ctl_softc;
13158
13159	CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13160
13161	ctl_softc = control_softc;
13162
13163#ifdef CTL_TIME_IO
13164	io->io_hdr.start_time = time_uptime;
13165	getbintime(&io->io_hdr.start_bt);
13166#endif /* CTL_TIME_IO */
13167
13168	/* Map FE-specific LUN ID into global one. */
13169	if (io->io_hdr.nexus.lun_map_fn != NULL)
13170		io->io_hdr.nexus.targ_mapped_lun = io->io_hdr.nexus.lun_map_fn(
13171		    io->io_hdr.nexus.lun_map_arg, io->io_hdr.nexus.targ_lun);
13172	else
13173		io->io_hdr.nexus.targ_mapped_lun = io->io_hdr.nexus.targ_lun;
13174
13175	switch (io->io_hdr.io_type) {
13176	case CTL_IO_SCSI:
13177	case CTL_IO_TASK:
13178		ctl_enqueue_incoming(io);
13179		break;
13180	default:
13181		printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13182		return (EINVAL);
13183	}
13184
13185	return (CTL_RETVAL_COMPLETE);
13186}
13187
13188#ifdef CTL_IO_DELAY
13189static void
13190ctl_done_timer_wakeup(void *arg)
13191{
13192	union ctl_io *io;
13193
13194	io = (union ctl_io *)arg;
13195	ctl_done(io);
13196}
13197#endif /* CTL_IO_DELAY */
13198
13199void
13200ctl_done(union ctl_io *io)
13201{
13202	struct ctl_softc *ctl_softc;
13203
13204	ctl_softc = control_softc;
13205
13206	/*
13207	 * Enable this to catch duplicate completion issues.
13208	 */
13209#if 0
13210	if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13211		printf("%s: type %d msg %d cdb %x iptl: "
13212		       "%d:%d:%d:%d tag 0x%04x "
13213		       "flag %#x status %x\n",
13214			__func__,
13215			io->io_hdr.io_type,
13216			io->io_hdr.msg_type,
13217			io->scsiio.cdb[0],
13218			io->io_hdr.nexus.initid.id,
13219			io->io_hdr.nexus.targ_port,
13220			io->io_hdr.nexus.targ_target.id,
13221			io->io_hdr.nexus.targ_lun,
13222			(io->io_hdr.io_type ==
13223			CTL_IO_TASK) ?
13224			io->taskio.tag_num :
13225			io->scsiio.tag_num,
13226		        io->io_hdr.flags,
13227			io->io_hdr.status);
13228	} else
13229		io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13230#endif
13231
13232	/*
13233	 * This is an internal copy of an I/O, and should not go through
13234	 * the normal done processing logic.
13235	 */
13236	if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13237		return;
13238
13239	/*
13240	 * We need to send a msg to the serializing shelf to finish the IO
13241	 * as well.  We don't send a finish message to the other shelf if
13242	 * this is a task management command.  Task management commands
13243	 * aren't serialized in the OOA queue, but rather just executed on
13244	 * both shelf controllers for commands that originated on that
13245	 * controller.
13246	 */
13247	if ((io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)
13248	 && (io->io_hdr.io_type != CTL_IO_TASK)) {
13249		union ctl_ha_msg msg_io;
13250
13251		msg_io.hdr.msg_type = CTL_MSG_FINISH_IO;
13252		msg_io.hdr.serializing_sc = io->io_hdr.serializing_sc;
13253		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_io,
13254		    sizeof(msg_io), 0 ) != CTL_HA_STATUS_SUCCESS) {
13255		}
13256		/* continue on to finish IO */
13257	}
13258#ifdef CTL_IO_DELAY
13259	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13260		struct ctl_lun *lun;
13261
13262		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13263
13264		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13265	} else {
13266		struct ctl_lun *lun;
13267
13268		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13269
13270		if ((lun != NULL)
13271		 && (lun->delay_info.done_delay > 0)) {
13272			struct callout *callout;
13273
13274			callout = (struct callout *)&io->io_hdr.timer_bytes;
13275			callout_init(callout, /*mpsafe*/ 1);
13276			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
13277			callout_reset(callout,
13278				      lun->delay_info.done_delay * hz,
13279				      ctl_done_timer_wakeup, io);
13280			if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
13281				lun->delay_info.done_delay = 0;
13282			return;
13283		}
13284	}
13285#endif /* CTL_IO_DELAY */
13286
13287	ctl_enqueue_done(io);
13288}
13289
13290int
13291ctl_isc(struct ctl_scsiio *ctsio)
13292{
13293	struct ctl_lun *lun;
13294	int retval;
13295
13296	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13297
13298	CTL_DEBUG_PRINT(("ctl_isc: command: %02x\n", ctsio->cdb[0]));
13299
13300	CTL_DEBUG_PRINT(("ctl_isc: calling data_submit()\n"));
13301
13302	retval = lun->backend->data_submit((union ctl_io *)ctsio);
13303
13304	return (retval);
13305}
13306
13307
13308static void
13309ctl_work_thread(void *arg)
13310{
13311	struct ctl_thread *thr = (struct ctl_thread *)arg;
13312	struct ctl_softc *softc = thr->ctl_softc;
13313	union ctl_io *io;
13314	int retval;
13315
13316	CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
13317
13318	for (;;) {
13319		retval = 0;
13320
13321		/*
13322		 * We handle the queues in this order:
13323		 * - ISC
13324		 * - done queue (to free up resources, unblock other commands)
13325		 * - RtR queue
13326		 * - incoming queue
13327		 *
13328		 * If those queues are empty, we break out of the loop and
13329		 * go to sleep.
13330		 */
13331		mtx_lock(&thr->queue_lock);
13332		io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
13333		if (io != NULL) {
13334			STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
13335			mtx_unlock(&thr->queue_lock);
13336			ctl_handle_isc(io);
13337			continue;
13338		}
13339		io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
13340		if (io != NULL) {
13341			STAILQ_REMOVE_HEAD(&thr->done_queue, links);
13342			/* clear any blocked commands, call fe_done */
13343			mtx_unlock(&thr->queue_lock);
13344			retval = ctl_process_done(io);
13345			continue;
13346		}
13347		io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
13348		if (io != NULL) {
13349			STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
13350			mtx_unlock(&thr->queue_lock);
13351			if (io->io_hdr.io_type == CTL_IO_TASK)
13352				ctl_run_task(io);
13353			else
13354				ctl_scsiio_precheck(softc, &io->scsiio);
13355			continue;
13356		}
13357		if (!ctl_pause_rtr) {
13358			io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
13359			if (io != NULL) {
13360				STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
13361				mtx_unlock(&thr->queue_lock);
13362				retval = ctl_scsiio(&io->scsiio);
13363				if (retval != CTL_RETVAL_COMPLETE)
13364					CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
13365				continue;
13366			}
13367		}
13368
13369		/* Sleep until we have something to do. */
13370		mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
13371	}
13372}
13373
13374static void
13375ctl_lun_thread(void *arg)
13376{
13377	struct ctl_softc *softc = (struct ctl_softc *)arg;
13378	struct ctl_be_lun *be_lun;
13379	int retval;
13380
13381	CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
13382
13383	for (;;) {
13384		retval = 0;
13385		mtx_lock(&softc->ctl_lock);
13386		be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
13387		if (be_lun != NULL) {
13388			STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
13389			mtx_unlock(&softc->ctl_lock);
13390			ctl_create_lun(be_lun);
13391			continue;
13392		}
13393
13394		/* Sleep until we have something to do. */
13395		mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
13396		    PDROP | PRIBIO, "-", 0);
13397	}
13398}
13399
13400static void
13401ctl_enqueue_incoming(union ctl_io *io)
13402{
13403	struct ctl_softc *softc = control_softc;
13404	struct ctl_thread *thr;
13405	u_int idx;
13406
13407	idx = (io->io_hdr.nexus.targ_port * 127 +
13408	       io->io_hdr.nexus.initid.id) % worker_threads;
13409	thr = &softc->threads[idx];
13410	mtx_lock(&thr->queue_lock);
13411	STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
13412	mtx_unlock(&thr->queue_lock);
13413	wakeup(thr);
13414}
13415
13416static void
13417ctl_enqueue_rtr(union ctl_io *io)
13418{
13419	struct ctl_softc *softc = control_softc;
13420	struct ctl_thread *thr;
13421
13422	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13423	mtx_lock(&thr->queue_lock);
13424	STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
13425	mtx_unlock(&thr->queue_lock);
13426	wakeup(thr);
13427}
13428
13429static void
13430ctl_enqueue_done(union ctl_io *io)
13431{
13432	struct ctl_softc *softc = control_softc;
13433	struct ctl_thread *thr;
13434
13435	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13436	mtx_lock(&thr->queue_lock);
13437	STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
13438	mtx_unlock(&thr->queue_lock);
13439	wakeup(thr);
13440}
13441
13442static void
13443ctl_enqueue_isc(union ctl_io *io)
13444{
13445	struct ctl_softc *softc = control_softc;
13446	struct ctl_thread *thr;
13447
13448	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13449	mtx_lock(&thr->queue_lock);
13450	STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
13451	mtx_unlock(&thr->queue_lock);
13452	wakeup(thr);
13453}
13454
13455/* Initialization and failover */
13456
13457void
13458ctl_init_isc_msg(void)
13459{
13460	printf("CTL: Still calling this thing\n");
13461}
13462
13463/*
13464 * Init component
13465 * 	Initializes component into configuration defined by bootMode
13466 *	(see hasc-sv.c)
13467 *  	returns hasc_Status:
13468 * 		OK
13469 *		ERROR - fatal error
13470 */
13471static ctl_ha_comp_status
13472ctl_isc_init(struct ctl_ha_component *c)
13473{
13474	ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
13475
13476	c->status = ret;
13477	return ret;
13478}
13479
13480/* Start component
13481 * 	Starts component in state requested. If component starts successfully,
13482 *	it must set its own state to the requestrd state
13483 *	When requested state is HASC_STATE_HA, the component may refine it
13484 * 	by adding _SLAVE or _MASTER flags.
13485 *	Currently allowed state transitions are:
13486 *	UNKNOWN->HA		- initial startup
13487 *	UNKNOWN->SINGLE - initial startup when no parter detected
13488 *	HA->SINGLE		- failover
13489 * returns ctl_ha_comp_status:
13490 * 		OK	- component successfully started in requested state
13491 *		FAILED  - could not start the requested state, failover may
13492 * 			  be possible
13493 *		ERROR	- fatal error detected, no future startup possible
13494 */
13495static ctl_ha_comp_status
13496ctl_isc_start(struct ctl_ha_component *c, ctl_ha_state state)
13497{
13498	ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
13499
13500	printf("%s: go\n", __func__);
13501
13502	// UNKNOWN->HA or UNKNOWN->SINGLE (bootstrap)
13503	if (c->state == CTL_HA_STATE_UNKNOWN ) {
13504		ctl_is_single = 0;
13505		if (ctl_ha_msg_create(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
13506		    != CTL_HA_STATUS_SUCCESS) {
13507			printf("ctl_isc_start: ctl_ha_msg_create failed.\n");
13508			ret = CTL_HA_COMP_STATUS_ERROR;
13509		}
13510	} else if (CTL_HA_STATE_IS_HA(c->state)
13511		&& CTL_HA_STATE_IS_SINGLE(state)){
13512		// HA->SINGLE transition
13513	        ctl_failover();
13514		ctl_is_single = 1;
13515	} else {
13516		printf("ctl_isc_start:Invalid state transition %X->%X\n",
13517		       c->state, state);
13518		ret = CTL_HA_COMP_STATUS_ERROR;
13519	}
13520	if (CTL_HA_STATE_IS_SINGLE(state))
13521		ctl_is_single = 1;
13522
13523	c->state = state;
13524	c->status = ret;
13525	return ret;
13526}
13527
13528/*
13529 * Quiesce component
13530 * The component must clear any error conditions (set status to OK) and
13531 * prepare itself to another Start call
13532 * returns ctl_ha_comp_status:
13533 * 	OK
13534 *	ERROR
13535 */
13536static ctl_ha_comp_status
13537ctl_isc_quiesce(struct ctl_ha_component *c)
13538{
13539	int ret = CTL_HA_COMP_STATUS_OK;
13540
13541	ctl_pause_rtr = 1;
13542	c->status = ret;
13543	return ret;
13544}
13545
13546struct ctl_ha_component ctl_ha_component_ctlisc =
13547{
13548	.name = "CTL ISC",
13549	.state = CTL_HA_STATE_UNKNOWN,
13550	.init = ctl_isc_init,
13551	.start = ctl_isc_start,
13552	.quiesce = ctl_isc_quiesce
13553};
13554
13555/*
13556 *  vim: ts=8
13557 */
13558