xref: /freebsd/sys/cam/ctl/ctl.c (revision 3fc9e2c36555140de248a0b4def91bbfa44d7c2c)
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$");
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/endian.h>
64 #include <sys/sysctl.h>
65 
66 #include <cam/cam.h>
67 #include <cam/scsi/scsi_all.h>
68 #include <cam/scsi/scsi_da.h>
69 #include <cam/ctl/ctl_io.h>
70 #include <cam/ctl/ctl.h>
71 #include <cam/ctl/ctl_frontend.h>
72 #include <cam/ctl/ctl_frontend_internal.h>
73 #include <cam/ctl/ctl_util.h>
74 #include <cam/ctl/ctl_backend.h>
75 #include <cam/ctl/ctl_ioctl.h>
76 #include <cam/ctl/ctl_ha.h>
77 #include <cam/ctl/ctl_private.h>
78 #include <cam/ctl/ctl_debug.h>
79 #include <cam/ctl/ctl_scsi_all.h>
80 #include <cam/ctl/ctl_error.h>
81 
82 struct ctl_softc *control_softc = NULL;
83 
84 /*
85  * The default is to run with CTL_DONE_THREAD turned on.  Completed
86  * transactions are queued for processing by the CTL work thread.  When
87  * CTL_DONE_THREAD is not defined, completed transactions are processed in
88  * the caller's context.
89  */
90 #define CTL_DONE_THREAD
91 
92 /*
93  * Use the serial number and device ID provided by the backend, rather than
94  * making up our own.
95  */
96 #define CTL_USE_BACKEND_SN
97 
98 /*
99  * Size and alignment macros needed for Copan-specific HA hardware.  These
100  * can go away when the HA code is re-written, and uses busdma for any
101  * hardware.
102  */
103 #define	CTL_ALIGN_8B(target, source, type)				\
104 	if (((uint32_t)source & 0x7) != 0)				\
105 		target = (type)(source + (0x8 - ((uint32_t)source & 0x7)));\
106 	else								\
107 		target = (type)source;
108 
109 #define	CTL_SIZE_8B(target, size)					\
110 	if ((size & 0x7) != 0)						\
111 		target = size + (0x8 - (size & 0x7));			\
112 	else								\
113 		target = size;
114 
115 #define CTL_ALIGN_8B_MARGIN	16
116 
117 /*
118  * Template mode pages.
119  */
120 
121 /*
122  * Note that these are default values only.  The actual values will be
123  * filled in when the user does a mode sense.
124  */
125 static struct copan_power_subpage power_page_default = {
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*/ PWR_VERSION,
131 	/* total_luns */ 26,
132 	/* max_active_luns*/ PWR_DFLT_MAX_LUNS,
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 
138 static struct copan_power_subpage power_page_changeable = {
139 	/*page_code*/ PWR_PAGE_CODE | SMPH_SPF,
140 	/*subpage*/ PWR_SUBPAGE_CODE,
141 	/*page_length*/ {(sizeof(struct copan_power_subpage) - 4) & 0xff00,
142 			 (sizeof(struct copan_power_subpage) - 4) & 0x00ff},
143 	/*page_version*/ 0,
144 	/* total_luns */ 0,
145 	/* max_active_luns*/ 0,
146 	/*reserved*/ {0, 0, 0, 0, 0, 0, 0, 0, 0,
147 		      0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
148 		      0, 0, 0, 0, 0, 0}
149 };
150 
151 static struct copan_aps_subpage aps_page_default = {
152 	APS_PAGE_CODE | SMPH_SPF, //page_code
153 	APS_SUBPAGE_CODE, //subpage
154 	{(sizeof(struct copan_aps_subpage) - 4) & 0xff00,
155 	 (sizeof(struct copan_aps_subpage) - 4) & 0x00ff}, //page_length
156 	APS_VERSION, //page_version
157 	0, //lock_active
158 	{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
159 	0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
160 	0, 0, 0, 0, 0} //reserved
161 };
162 
163 static struct copan_aps_subpage aps_page_changeable = {
164 	APS_PAGE_CODE | SMPH_SPF, //page_code
165 	APS_SUBPAGE_CODE, //subpage
166 	{(sizeof(struct copan_aps_subpage) - 4) & 0xff00,
167 	 (sizeof(struct copan_aps_subpage) - 4) & 0x00ff}, //page_length
168 	0, //page_version
169 	0, //lock_active
170 	{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
171 	0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
172 	0, 0, 0, 0, 0} //reserved
173 };
174 
175 static struct copan_debugconf_subpage debugconf_page_default = {
176 	DBGCNF_PAGE_CODE | SMPH_SPF,	/* page_code */
177 	DBGCNF_SUBPAGE_CODE,		/* subpage */
178 	{(sizeof(struct copan_debugconf_subpage) - 4) >> 8,
179 	 (sizeof(struct copan_debugconf_subpage) - 4) >> 0}, /* page_length */
180 	DBGCNF_VERSION,			/* page_version */
181 	{CTL_TIME_IO_DEFAULT_SECS>>8,
182 	 CTL_TIME_IO_DEFAULT_SECS>>0},	/* ctl_time_io_secs */
183 };
184 
185 static struct copan_debugconf_subpage debugconf_page_changeable = {
186 	DBGCNF_PAGE_CODE | SMPH_SPF,	/* page_code */
187 	DBGCNF_SUBPAGE_CODE,		/* subpage */
188 	{(sizeof(struct copan_debugconf_subpage) - 4) >> 8,
189 	 (sizeof(struct copan_debugconf_subpage) - 4) >> 0}, /* page_length */
190 	0,				/* page_version */
191 	{0xff,0xff},			/* ctl_time_io_secs */
192 };
193 
194 static struct scsi_format_page format_page_default = {
195 	/*page_code*/SMS_FORMAT_DEVICE_PAGE,
196 	/*page_length*/sizeof(struct scsi_format_page) - 2,
197 	/*tracks_per_zone*/ {0, 0},
198 	/*alt_sectors_per_zone*/ {0, 0},
199 	/*alt_tracks_per_zone*/ {0, 0},
200 	/*alt_tracks_per_lun*/ {0, 0},
201 	/*sectors_per_track*/ {(CTL_DEFAULT_SECTORS_PER_TRACK >> 8) & 0xff,
202 			        CTL_DEFAULT_SECTORS_PER_TRACK & 0xff},
203 	/*bytes_per_sector*/ {0, 0},
204 	/*interleave*/ {0, 0},
205 	/*track_skew*/ {0, 0},
206 	/*cylinder_skew*/ {0, 0},
207 	/*flags*/ SFP_HSEC,
208 	/*reserved*/ {0, 0, 0}
209 };
210 
211 static struct scsi_format_page format_page_changeable = {
212 	/*page_code*/SMS_FORMAT_DEVICE_PAGE,
213 	/*page_length*/sizeof(struct scsi_format_page) - 2,
214 	/*tracks_per_zone*/ {0, 0},
215 	/*alt_sectors_per_zone*/ {0, 0},
216 	/*alt_tracks_per_zone*/ {0, 0},
217 	/*alt_tracks_per_lun*/ {0, 0},
218 	/*sectors_per_track*/ {0, 0},
219 	/*bytes_per_sector*/ {0, 0},
220 	/*interleave*/ {0, 0},
221 	/*track_skew*/ {0, 0},
222 	/*cylinder_skew*/ {0, 0},
223 	/*flags*/ 0,
224 	/*reserved*/ {0, 0, 0}
225 };
226 
227 static struct scsi_rigid_disk_page rigid_disk_page_default = {
228 	/*page_code*/SMS_RIGID_DISK_PAGE,
229 	/*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
230 	/*cylinders*/ {0, 0, 0},
231 	/*heads*/ CTL_DEFAULT_HEADS,
232 	/*start_write_precomp*/ {0, 0, 0},
233 	/*start_reduced_current*/ {0, 0, 0},
234 	/*step_rate*/ {0, 0},
235 	/*landing_zone_cylinder*/ {0, 0, 0},
236 	/*rpl*/ SRDP_RPL_DISABLED,
237 	/*rotational_offset*/ 0,
238 	/*reserved1*/ 0,
239 	/*rotation_rate*/ {(CTL_DEFAULT_ROTATION_RATE >> 8) & 0xff,
240 			   CTL_DEFAULT_ROTATION_RATE & 0xff},
241 	/*reserved2*/ {0, 0}
242 };
243 
244 static struct scsi_rigid_disk_page rigid_disk_page_changeable = {
245 	/*page_code*/SMS_RIGID_DISK_PAGE,
246 	/*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
247 	/*cylinders*/ {0, 0, 0},
248 	/*heads*/ 0,
249 	/*start_write_precomp*/ {0, 0, 0},
250 	/*start_reduced_current*/ {0, 0, 0},
251 	/*step_rate*/ {0, 0},
252 	/*landing_zone_cylinder*/ {0, 0, 0},
253 	/*rpl*/ 0,
254 	/*rotational_offset*/ 0,
255 	/*reserved1*/ 0,
256 	/*rotation_rate*/ {0, 0},
257 	/*reserved2*/ {0, 0}
258 };
259 
260 static struct scsi_caching_page caching_page_default = {
261 	/*page_code*/SMS_CACHING_PAGE,
262 	/*page_length*/sizeof(struct scsi_caching_page) - 2,
263 	/*flags1*/ SCP_DISC | SCP_WCE,
264 	/*ret_priority*/ 0,
265 	/*disable_pf_transfer_len*/ {0xff, 0xff},
266 	/*min_prefetch*/ {0, 0},
267 	/*max_prefetch*/ {0xff, 0xff},
268 	/*max_pf_ceiling*/ {0xff, 0xff},
269 	/*flags2*/ 0,
270 	/*cache_segments*/ 0,
271 	/*cache_seg_size*/ {0, 0},
272 	/*reserved*/ 0,
273 	/*non_cache_seg_size*/ {0, 0, 0}
274 };
275 
276 static struct scsi_caching_page caching_page_changeable = {
277 	/*page_code*/SMS_CACHING_PAGE,
278 	/*page_length*/sizeof(struct scsi_caching_page) - 2,
279 	/*flags1*/ 0,
280 	/*ret_priority*/ 0,
281 	/*disable_pf_transfer_len*/ {0, 0},
282 	/*min_prefetch*/ {0, 0},
283 	/*max_prefetch*/ {0, 0},
284 	/*max_pf_ceiling*/ {0, 0},
285 	/*flags2*/ 0,
286 	/*cache_segments*/ 0,
287 	/*cache_seg_size*/ {0, 0},
288 	/*reserved*/ 0,
289 	/*non_cache_seg_size*/ {0, 0, 0}
290 };
291 
292 static struct scsi_control_page control_page_default = {
293 	/*page_code*/SMS_CONTROL_MODE_PAGE,
294 	/*page_length*/sizeof(struct scsi_control_page) - 2,
295 	/*rlec*/0,
296 	/*queue_flags*/0,
297 	/*eca_and_aen*/0,
298 	/*reserved*/0,
299 	/*aen_holdoff_period*/{0, 0}
300 };
301 
302 static struct scsi_control_page control_page_changeable = {
303 	/*page_code*/SMS_CONTROL_MODE_PAGE,
304 	/*page_length*/sizeof(struct scsi_control_page) - 2,
305 	/*rlec*/SCP_DSENSE,
306 	/*queue_flags*/0,
307 	/*eca_and_aen*/0,
308 	/*reserved*/0,
309 	/*aen_holdoff_period*/{0, 0}
310 };
311 
312 
313 /*
314  * XXX KDM move these into the softc.
315  */
316 static int rcv_sync_msg;
317 static int persis_offset;
318 static uint8_t ctl_pause_rtr;
319 static int     ctl_is_single = 1;
320 static int     index_to_aps_page;
321 
322 SYSCTL_NODE(_kern_cam, OID_AUTO, ctl, CTLFLAG_RD, 0, "CAM Target Layer");
323 
324 /*
325  * Serial number (0x80), device id (0x83), and supported pages (0x00)
326  */
327 #define SCSI_EVPD_NUM_SUPPORTED_PAGES	3
328 
329 static void ctl_isc_event_handler(ctl_ha_channel chanel, ctl_ha_event event,
330 				  int param);
331 static void ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest);
332 static int ctl_init(void);
333 void ctl_shutdown(void);
334 static int ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td);
335 static int ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td);
336 static void ctl_ioctl_online(void *arg);
337 static void ctl_ioctl_offline(void *arg);
338 static int ctl_ioctl_targ_enable(void *arg, struct ctl_id targ_id);
339 static int ctl_ioctl_targ_disable(void *arg, struct ctl_id targ_id);
340 static int ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id);
341 static int ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id);
342 static int ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio);
343 static int ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio, int have_lock);
344 static int ctl_ioctl_submit_wait(union ctl_io *io);
345 static void ctl_ioctl_datamove(union ctl_io *io);
346 static void ctl_ioctl_done(union ctl_io *io);
347 static void ctl_ioctl_hard_startstop_callback(void *arg,
348 					      struct cfi_metatask *metatask);
349 static void ctl_ioctl_bbrread_callback(void *arg,struct cfi_metatask *metatask);
350 static int ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
351 			      struct ctl_ooa *ooa_hdr,
352 			      struct ctl_ooa_entry *kern_entries);
353 static int ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
354 		     struct thread *td);
355 uint32_t ctl_get_resindex(struct ctl_nexus *nexus);
356 uint32_t ctl_port_idx(int port_num);
357 #ifdef unused
358 static union ctl_io *ctl_malloc_io(ctl_io_type io_type, uint32_t targ_port,
359 				   uint32_t targ_target, uint32_t targ_lun,
360 				   int can_wait);
361 static void ctl_kfree_io(union ctl_io *io);
362 #endif /* unused */
363 static void ctl_free_io_internal(union ctl_io *io, int have_lock);
364 static int ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
365 			 struct ctl_be_lun *be_lun, struct ctl_id target_id);
366 static int ctl_free_lun(struct ctl_lun *lun);
367 static void ctl_create_lun(struct ctl_be_lun *be_lun);
368 /**
369 static void ctl_failover_change_pages(struct ctl_softc *softc,
370 				      struct ctl_scsiio *ctsio, int master);
371 **/
372 
373 static int ctl_do_mode_select(union ctl_io *io);
374 static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
375 			   uint64_t res_key, uint64_t sa_res_key,
376 			   uint8_t type, uint32_t residx,
377 			   struct ctl_scsiio *ctsio,
378 			   struct scsi_per_res_out *cdb,
379 			   struct scsi_per_res_out_parms* param);
380 static void ctl_pro_preempt_other(struct ctl_lun *lun,
381 				  union ctl_ha_msg *msg);
382 static void ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg);
383 static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
384 static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
385 static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
386 static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
387 static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
388 static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint32_t *len);
389 static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2);
390 static ctl_action ctl_check_for_blockage(union ctl_io *pending_io,
391 					 union ctl_io *ooa_io);
392 static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
393 				union ctl_io *starting_io);
394 static int ctl_check_blocked(struct ctl_lun *lun);
395 static int ctl_scsiio_lun_check(struct ctl_softc *ctl_softc,
396 				struct ctl_lun *lun,
397 				struct ctl_cmd_entry *entry,
398 				struct ctl_scsiio *ctsio);
399 //static int ctl_check_rtr(union ctl_io *pending_io, struct ctl_softc *softc);
400 static void ctl_failover(void);
401 static int ctl_scsiio_precheck(struct ctl_softc *ctl_softc,
402 			       struct ctl_scsiio *ctsio);
403 static int ctl_scsiio(struct ctl_scsiio *ctsio);
404 
405 static int ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
406 static int ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
407 			    ctl_ua_type ua_type);
408 static int ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io,
409 			 ctl_ua_type ua_type);
410 static int ctl_abort_task(union ctl_io *io);
411 static void ctl_run_task_queue(struct ctl_softc *ctl_softc);
412 #ifdef CTL_IO_DELAY
413 static void ctl_datamove_timer_wakeup(void *arg);
414 static void ctl_done_timer_wakeup(void *arg);
415 #endif /* CTL_IO_DELAY */
416 
417 static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
418 static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
419 static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
420 static void ctl_datamove_remote_write(union ctl_io *io);
421 static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
422 static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
423 static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
424 static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
425 				    ctl_ha_dt_cb callback);
426 static void ctl_datamove_remote_read(union ctl_io *io);
427 static void ctl_datamove_remote(union ctl_io *io);
428 static int ctl_process_done(union ctl_io *io, int have_lock);
429 static void ctl_work_thread(void *arg);
430 
431 /*
432  * Load the serialization table.  This isn't very pretty, but is probably
433  * the easiest way to do it.
434  */
435 #include "ctl_ser_table.c"
436 
437 /*
438  * We only need to define open, close and ioctl routines for this driver.
439  */
440 static struct cdevsw ctl_cdevsw = {
441 	.d_version =	D_VERSION,
442 	.d_flags =	0,
443 	.d_open =	ctl_open,
444 	.d_close =	ctl_close,
445 	.d_ioctl =	ctl_ioctl,
446 	.d_name =	"ctl",
447 };
448 
449 
450 MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
451 
452 static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
453 
454 static moduledata_t ctl_moduledata = {
455 	"ctl",
456 	ctl_module_event_handler,
457 	NULL
458 };
459 
460 DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
461 MODULE_VERSION(ctl, 1);
462 
463 static void
464 ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
465 			    union ctl_ha_msg *msg_info)
466 {
467 	struct ctl_scsiio *ctsio;
468 
469 	if (msg_info->hdr.original_sc == NULL) {
470 		printf("%s: original_sc == NULL!\n", __func__);
471 		/* XXX KDM now what? */
472 		return;
473 	}
474 
475 	ctsio = &msg_info->hdr.original_sc->scsiio;
476 	ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
477 	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
478 	ctsio->io_hdr.status = msg_info->hdr.status;
479 	ctsio->scsi_status = msg_info->scsi.scsi_status;
480 	ctsio->sense_len = msg_info->scsi.sense_len;
481 	ctsio->sense_residual = msg_info->scsi.sense_residual;
482 	ctsio->residual = msg_info->scsi.residual;
483 	memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
484 	       sizeof(ctsio->sense_data));
485 	memcpy(&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
486 	       &msg_info->scsi.lbalen, sizeof(msg_info->scsi.lbalen));
487 	STAILQ_INSERT_TAIL(&ctl_softc->isc_queue, &ctsio->io_hdr, links);
488 	ctl_wakeup_thread();
489 }
490 
491 static void
492 ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
493 				union ctl_ha_msg *msg_info)
494 {
495 	struct ctl_scsiio *ctsio;
496 
497 	if (msg_info->hdr.serializing_sc == NULL) {
498 		printf("%s: serializing_sc == NULL!\n", __func__);
499 		/* XXX KDM now what? */
500 		return;
501 	}
502 
503 	ctsio = &msg_info->hdr.serializing_sc->scsiio;
504 #if 0
505 	/*
506 	 * Attempt to catch the situation where an I/O has
507 	 * been freed, and we're using it again.
508 	 */
509 	if (ctsio->io_hdr.io_type == 0xff) {
510 		union ctl_io *tmp_io;
511 		tmp_io = (union ctl_io *)ctsio;
512 		printf("%s: %p use after free!\n", __func__,
513 		       ctsio);
514 		printf("%s: type %d msg %d cdb %x iptl: "
515 		       "%d:%d:%d:%d tag 0x%04x "
516 		       "flag %#x status %x\n",
517 			__func__,
518 			tmp_io->io_hdr.io_type,
519 			tmp_io->io_hdr.msg_type,
520 			tmp_io->scsiio.cdb[0],
521 			tmp_io->io_hdr.nexus.initid.id,
522 			tmp_io->io_hdr.nexus.targ_port,
523 			tmp_io->io_hdr.nexus.targ_target.id,
524 			tmp_io->io_hdr.nexus.targ_lun,
525 			(tmp_io->io_hdr.io_type ==
526 			CTL_IO_TASK) ?
527 			tmp_io->taskio.tag_num :
528 			tmp_io->scsiio.tag_num,
529 		        tmp_io->io_hdr.flags,
530 			tmp_io->io_hdr.status);
531 	}
532 #endif
533 	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
534 	STAILQ_INSERT_TAIL(&ctl_softc->isc_queue, &ctsio->io_hdr, links);
535 	ctl_wakeup_thread();
536 }
537 
538 /*
539  * ISC (Inter Shelf Communication) event handler.  Events from the HA
540  * subsystem come in here.
541  */
542 static void
543 ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
544 {
545 	struct ctl_softc *ctl_softc;
546 	union ctl_io *io;
547 	struct ctl_prio *presio;
548 	ctl_ha_status isc_status;
549 
550 	ctl_softc = control_softc;
551 	io = NULL;
552 
553 
554 #if 0
555 	printf("CTL: Isc Msg event %d\n", event);
556 #endif
557 	if (event == CTL_HA_EVT_MSG_RECV) {
558 		union ctl_ha_msg msg_info;
559 
560 		isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
561 					     sizeof(msg_info), /*wait*/ 0);
562 #if 0
563 		printf("CTL: msg_type %d\n", msg_info.msg_type);
564 #endif
565 		if (isc_status != 0) {
566 			printf("Error receiving message, status = %d\n",
567 			       isc_status);
568 			return;
569 		}
570 		mtx_lock(&ctl_softc->ctl_lock);
571 
572 		switch (msg_info.hdr.msg_type) {
573 		case CTL_MSG_SERIALIZE:
574 #if 0
575 			printf("Serialize\n");
576 #endif
577 			io = ctl_alloc_io((void *)ctl_softc->othersc_pool);
578 			if (io == NULL) {
579 				printf("ctl_isc_event_handler: can't allocate "
580 				       "ctl_io!\n");
581 				/* Bad Juju */
582 				/* Need to set busy and send msg back */
583 				mtx_unlock(&ctl_softc->ctl_lock);
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 			STAILQ_INSERT_TAIL(&ctl_softc->isc_queue,
635 					   &io->io_hdr, links);
636 			ctl_wakeup_thread();
637 			break;
638 
639 		/* Performed on the Originating SC, XFER mode only */
640 		case CTL_MSG_DATAMOVE: {
641 			struct ctl_sg_entry *sgl;
642 			int i, j;
643 
644 			io = msg_info.hdr.original_sc;
645 			if (io == NULL) {
646 				printf("%s: original_sc == NULL!\n", __func__);
647 				/* XXX KDM do something here */
648 				break;
649 			}
650 			io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
651 			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
652 			/*
653 			 * Keep track of this, we need to send it back over
654 			 * when the datamove is complete.
655 			 */
656 			io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
657 
658 			if (msg_info.dt.sg_sequence == 0) {
659 				/*
660 				 * XXX KDM we use the preallocated S/G list
661 				 * here, but we'll need to change this to
662 				 * dynamic allocation if we need larger S/G
663 				 * lists.
664 				 */
665 				if (msg_info.dt.kern_sg_entries >
666 				    sizeof(io->io_hdr.remote_sglist) /
667 				    sizeof(io->io_hdr.remote_sglist[0])) {
668 					printf("%s: number of S/G entries "
669 					    "needed %u > allocated num %zd\n",
670 					    __func__,
671 					    msg_info.dt.kern_sg_entries,
672 					    sizeof(io->io_hdr.remote_sglist)/
673 					    sizeof(io->io_hdr.remote_sglist[0]));
674 
675 					/*
676 					 * XXX KDM send a message back to
677 					 * the other side to shut down the
678 					 * DMA.  The error will come back
679 					 * through via the normal channel.
680 					 */
681 					break;
682 				}
683 				sgl = io->io_hdr.remote_sglist;
684 				memset(sgl, 0,
685 				       sizeof(io->io_hdr.remote_sglist));
686 
687 				io->scsiio.kern_data_ptr = (uint8_t *)sgl;
688 
689 				io->scsiio.kern_sg_entries =
690 					msg_info.dt.kern_sg_entries;
691 				io->scsiio.rem_sg_entries =
692 					msg_info.dt.kern_sg_entries;
693 				io->scsiio.kern_data_len =
694 					msg_info.dt.kern_data_len;
695 				io->scsiio.kern_total_len =
696 					msg_info.dt.kern_total_len;
697 				io->scsiio.kern_data_resid =
698 					msg_info.dt.kern_data_resid;
699 				io->scsiio.kern_rel_offset =
700 					msg_info.dt.kern_rel_offset;
701 				/*
702 				 * Clear out per-DMA flags.
703 				 */
704 				io->io_hdr.flags &= ~CTL_FLAG_RDMA_MASK;
705 				/*
706 				 * Add per-DMA flags that are set for this
707 				 * particular DMA request.
708 				 */
709 				io->io_hdr.flags |= msg_info.dt.flags &
710 						    CTL_FLAG_RDMA_MASK;
711 			} else
712 				sgl = (struct ctl_sg_entry *)
713 					io->scsiio.kern_data_ptr;
714 
715 			for (i = msg_info.dt.sent_sg_entries, j = 0;
716 			     i < (msg_info.dt.sent_sg_entries +
717 			     msg_info.dt.cur_sg_entries); i++, j++) {
718 				sgl[i].addr = msg_info.dt.sg_list[j].addr;
719 				sgl[i].len = msg_info.dt.sg_list[j].len;
720 
721 #if 0
722 				printf("%s: L: %p,%d -> %p,%d j=%d, i=%d\n",
723 				       __func__,
724 				       msg_info.dt.sg_list[j].addr,
725 				       msg_info.dt.sg_list[j].len,
726 				       sgl[i].addr, sgl[i].len, j, i);
727 #endif
728 			}
729 #if 0
730 			memcpy(&sgl[msg_info.dt.sent_sg_entries],
731 			       msg_info.dt.sg_list,
732 			       sizeof(*sgl) * msg_info.dt.cur_sg_entries);
733 #endif
734 
735 			/*
736 			 * If this is the last piece of the I/O, we've got
737 			 * the full S/G list.  Queue processing in the thread.
738 			 * Otherwise wait for the next piece.
739 			 */
740 			if (msg_info.dt.sg_last != 0) {
741 				STAILQ_INSERT_TAIL(&ctl_softc->isc_queue,
742 						   &io->io_hdr, links);
743 				ctl_wakeup_thread();
744 			}
745 			break;
746 		}
747 		/* Performed on the Serializing (primary) SC, XFER mode only */
748 		case CTL_MSG_DATAMOVE_DONE: {
749 			if (msg_info.hdr.serializing_sc == NULL) {
750 				printf("%s: serializing_sc == NULL!\n",
751 				       __func__);
752 				/* XXX KDM now what? */
753 				break;
754 			}
755 			/*
756 			 * We grab the sense information here in case
757 			 * there was a failure, so we can return status
758 			 * back to the initiator.
759 			 */
760 			io = msg_info.hdr.serializing_sc;
761 			io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
762 			io->io_hdr.status = msg_info.hdr.status;
763 			io->scsiio.scsi_status = msg_info.scsi.scsi_status;
764 			io->scsiio.sense_len = msg_info.scsi.sense_len;
765 			io->scsiio.sense_residual =msg_info.scsi.sense_residual;
766 			io->io_hdr.port_status = msg_info.scsi.fetd_status;
767 			io->scsiio.residual = msg_info.scsi.residual;
768 			memcpy(&io->scsiio.sense_data,&msg_info.scsi.sense_data,
769 			       sizeof(io->scsiio.sense_data));
770 
771 			STAILQ_INSERT_TAIL(&ctl_softc->isc_queue,
772 					   &io->io_hdr, links);
773 			ctl_wakeup_thread();
774 			break;
775 		}
776 
777 		/* Preformed on Originating SC, SER_ONLY mode */
778 		case CTL_MSG_R2R:
779 			io = msg_info.hdr.original_sc;
780 			if (io == NULL) {
781 				printf("%s: Major Bummer\n", __func__);
782 				mtx_unlock(&ctl_softc->ctl_lock);
783 				return;
784 			} else {
785 #if 0
786 				printf("pOrig %x\n",(int) ctsio);
787 #endif
788 			}
789 			io->io_hdr.msg_type = CTL_MSG_R2R;
790 			io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
791 			STAILQ_INSERT_TAIL(&ctl_softc->isc_queue,
792 					   &io->io_hdr, links);
793 			ctl_wakeup_thread();
794 			break;
795 
796 		/*
797 		 * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
798 		 * mode.
799 		 * Performed on the Originating (i.e. secondary) SC in XFER
800 		 * mode
801 		 */
802 		case CTL_MSG_FINISH_IO:
803 			if (ctl_softc->ha_mode == CTL_HA_MODE_XFER)
804 				ctl_isc_handler_finish_xfer(ctl_softc,
805 							    &msg_info);
806 			else
807 				ctl_isc_handler_finish_ser_only(ctl_softc,
808 								&msg_info);
809 			break;
810 
811 		/* Preformed on Originating SC */
812 		case CTL_MSG_BAD_JUJU:
813 			io = msg_info.hdr.original_sc;
814 			if (io == NULL) {
815 				printf("%s: Bad JUJU!, original_sc is NULL!\n",
816 				       __func__);
817 				break;
818 			}
819 			ctl_copy_sense_data(&msg_info, io);
820 			/*
821 			 * IO should have already been cleaned up on other
822 			 * SC so clear this flag so we won't send a message
823 			 * back to finish the IO there.
824 			 */
825 			io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
826 			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
827 
828 			/* io = msg_info.hdr.serializing_sc; */
829 			io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
830 		        STAILQ_INSERT_TAIL(&ctl_softc->isc_queue,
831 					   &io->io_hdr, links);
832 			ctl_wakeup_thread();
833 			break;
834 
835 		/* Handle resets sent from the other side */
836 		case CTL_MSG_MANAGE_TASKS: {
837 			struct ctl_taskio *taskio;
838 			taskio = (struct ctl_taskio *)ctl_alloc_io(
839 				(void *)ctl_softc->othersc_pool);
840 			if (taskio == NULL) {
841 				printf("ctl_isc_event_handler: can't allocate "
842 				       "ctl_io!\n");
843 				/* Bad Juju */
844 				/* should I just call the proper reset func
845 				   here??? */
846 				mtx_unlock(&ctl_softc->ctl_lock);
847 				goto bailout;
848 			}
849 			ctl_zero_io((union ctl_io *)taskio);
850 			taskio->io_hdr.io_type = CTL_IO_TASK;
851 			taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
852 			taskio->io_hdr.nexus = msg_info.hdr.nexus;
853 			taskio->task_action = msg_info.task.task_action;
854 			taskio->tag_num = msg_info.task.tag_num;
855 			taskio->tag_type = msg_info.task.tag_type;
856 #ifdef CTL_TIME_IO
857 			taskio->io_hdr.start_time = time_uptime;
858 			getbintime(&taskio->io_hdr.start_bt);
859 #if 0
860 			cs_prof_gettime(&taskio->io_hdr.start_ticks);
861 #endif
862 #endif /* CTL_TIME_IO */
863 		        STAILQ_INSERT_TAIL(&ctl_softc->task_queue,
864 					   &taskio->io_hdr, links);
865 			ctl_softc->flags |= CTL_FLAG_TASK_PENDING;
866 			ctl_wakeup_thread();
867 			break;
868 		}
869 		/* Persistent Reserve action which needs attention */
870 		case CTL_MSG_PERS_ACTION:
871 			presio = (struct ctl_prio *)ctl_alloc_io(
872 				(void *)ctl_softc->othersc_pool);
873 			if (presio == NULL) {
874 				printf("ctl_isc_event_handler: can't allocate "
875 				       "ctl_io!\n");
876 				/* Bad Juju */
877 				/* Need to set busy and send msg back */
878 				mtx_unlock(&ctl_softc->ctl_lock);
879 				goto bailout;
880 			}
881 			ctl_zero_io((union ctl_io *)presio);
882 			presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
883 			presio->pr_msg = msg_info.pr;
884 		        STAILQ_INSERT_TAIL(&ctl_softc->isc_queue,
885 					   &presio->io_hdr, links);
886 			ctl_wakeup_thread();
887 			break;
888 		case CTL_MSG_SYNC_FE:
889 			rcv_sync_msg = 1;
890 			break;
891 		case CTL_MSG_APS_LOCK: {
892 			// It's quicker to execute this then to
893 			// queue it.
894 			struct ctl_lun *lun;
895 			struct ctl_page_index *page_index;
896 			struct copan_aps_subpage *current_sp;
897 			uint32_t targ_lun;
898 
899 			targ_lun = msg_info.hdr.nexus.targ_lun;
900 			if (msg_info.hdr.nexus.lun_map_fn != NULL)
901 				targ_lun = msg_info.hdr.nexus.lun_map_fn(msg_info.hdr.nexus.lun_map_arg, targ_lun);
902 
903 			lun = ctl_softc->ctl_luns[targ_lun];
904 			page_index = &lun->mode_pages.index[index_to_aps_page];
905 			current_sp = (struct copan_aps_subpage *)
906 				     (page_index->page_data +
907 				     (page_index->page_len * CTL_PAGE_CURRENT));
908 
909 			current_sp->lock_active = msg_info.aps.lock_flag;
910 		        break;
911 		}
912 		default:
913 		        printf("How did I get here?\n");
914 		}
915 		mtx_unlock(&ctl_softc->ctl_lock);
916 	} else if (event == CTL_HA_EVT_MSG_SENT) {
917 		if (param != CTL_HA_STATUS_SUCCESS) {
918 			printf("Bad status from ctl_ha_msg_send status %d\n",
919 			       param);
920 		}
921 		return;
922 	} else if (event == CTL_HA_EVT_DISCONNECT) {
923 		printf("CTL: Got a disconnect from Isc\n");
924 		return;
925 	} else {
926 		printf("ctl_isc_event_handler: Unknown event %d\n", event);
927 		return;
928 	}
929 
930 bailout:
931 	return;
932 }
933 
934 static void
935 ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
936 {
937 	struct scsi_sense_data *sense;
938 
939 	sense = &dest->scsiio.sense_data;
940 	bcopy(&src->scsi.sense_data, sense, sizeof(*sense));
941 	dest->scsiio.scsi_status = src->scsi.scsi_status;
942 	dest->scsiio.sense_len = src->scsi.sense_len;
943 	dest->io_hdr.status = src->hdr.status;
944 }
945 
946 static int
947 ctl_init(void)
948 {
949 	struct ctl_softc *softc;
950 	struct ctl_io_pool *internal_pool, *emergency_pool, *other_pool;
951 	struct ctl_frontend *fe;
952 	struct ctl_lun *lun;
953         uint8_t sc_id =0;
954 #if 0
955 	int i;
956 #endif
957 	int error, retval;
958 	//int isc_retval;
959 
960 	retval = 0;
961 	ctl_pause_rtr = 0;
962         rcv_sync_msg = 0;
963 
964 	control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
965 			       M_WAITOK | M_ZERO);
966 	softc = control_softc;
967 
968 	softc->dev = make_dev(&ctl_cdevsw, 0, UID_ROOT, GID_OPERATOR, 0600,
969 			      "cam/ctl");
970 
971 	softc->dev->si_drv1 = softc;
972 
973 	/*
974 	 * By default, return a "bad LUN" peripheral qualifier for unknown
975 	 * LUNs.  The user can override this default using the tunable or
976 	 * sysctl.  See the comment in ctl_inquiry_std() for more details.
977 	 */
978 	softc->inquiry_pq_no_lun = 1;
979 	TUNABLE_INT_FETCH("kern.cam.ctl.inquiry_pq_no_lun",
980 			  &softc->inquiry_pq_no_lun);
981 	sysctl_ctx_init(&softc->sysctl_ctx);
982 	softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
983 		SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
984 		CTLFLAG_RD, 0, "CAM Target Layer");
985 
986 	if (softc->sysctl_tree == NULL) {
987 		printf("%s: unable to allocate sysctl tree\n", __func__);
988 		destroy_dev(softc->dev);
989 		free(control_softc, M_DEVBUF);
990 		control_softc = NULL;
991 		return (ENOMEM);
992 	}
993 
994 	SYSCTL_ADD_INT(&softc->sysctl_ctx,
995 		       SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
996 		       "inquiry_pq_no_lun", CTLFLAG_RW,
997 		       &softc->inquiry_pq_no_lun, 0,
998 		       "Report no lun possible for invalid LUNs");
999 
1000 	mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
1001 	softc->open_count = 0;
1002 
1003 	/*
1004 	 * Default to actually sending a SYNCHRONIZE CACHE command down to
1005 	 * the drive.
1006 	 */
1007 	softc->flags = CTL_FLAG_REAL_SYNC;
1008 
1009 	/*
1010 	 * In Copan's HA scheme, the "master" and "slave" roles are
1011 	 * figured out through the slot the controller is in.  Although it
1012 	 * is an active/active system, someone has to be in charge.
1013  	 */
1014 #ifdef NEEDTOPORT
1015         scmicro_rw(SCMICRO_GET_SHELF_ID, &sc_id);
1016 #endif
1017 
1018         if (sc_id == 0) {
1019 		softc->flags |= CTL_FLAG_MASTER_SHELF;
1020 		persis_offset = 0;
1021 	} else
1022 		persis_offset = CTL_MAX_INITIATORS;
1023 
1024 	/*
1025 	 * XXX KDM need to figure out where we want to get our target ID
1026 	 * and WWID.  Is it different on each port?
1027 	 */
1028 	softc->target.id = 0;
1029 	softc->target.wwid[0] = 0x12345678;
1030 	softc->target.wwid[1] = 0x87654321;
1031 	STAILQ_INIT(&softc->lun_list);
1032 	STAILQ_INIT(&softc->pending_lun_queue);
1033 	STAILQ_INIT(&softc->task_queue);
1034 	STAILQ_INIT(&softc->incoming_queue);
1035 	STAILQ_INIT(&softc->rtr_queue);
1036 	STAILQ_INIT(&softc->done_queue);
1037 	STAILQ_INIT(&softc->isc_queue);
1038 	STAILQ_INIT(&softc->fe_list);
1039 	STAILQ_INIT(&softc->be_list);
1040 	STAILQ_INIT(&softc->io_pools);
1041 
1042 	lun = &softc->lun;
1043 
1044 	/*
1045 	 * We don't bother calling these with ctl_lock held here, because,
1046 	 * in theory, no one else can try to do anything while we're in our
1047 	 * module init routine.
1048 	 */
1049 	if (ctl_pool_create(softc, CTL_POOL_INTERNAL, CTL_POOL_ENTRIES_INTERNAL,
1050 			    &internal_pool)!= 0){
1051 		printf("ctl: can't allocate %d entry internal pool, "
1052 		       "exiting\n", CTL_POOL_ENTRIES_INTERNAL);
1053 		return (ENOMEM);
1054 	}
1055 
1056 	if (ctl_pool_create(softc, CTL_POOL_EMERGENCY,
1057 			    CTL_POOL_ENTRIES_EMERGENCY, &emergency_pool) != 0) {
1058 		printf("ctl: can't allocate %d entry emergency pool, "
1059 		       "exiting\n", CTL_POOL_ENTRIES_EMERGENCY);
1060 		ctl_pool_free(softc, internal_pool);
1061 		return (ENOMEM);
1062 	}
1063 
1064 	if (ctl_pool_create(softc, CTL_POOL_4OTHERSC, CTL_POOL_ENTRIES_OTHER_SC,
1065 	                    &other_pool) != 0)
1066 	{
1067 		printf("ctl: can't allocate %d entry other SC pool, "
1068 		       "exiting\n", CTL_POOL_ENTRIES_OTHER_SC);
1069 		ctl_pool_free(softc, internal_pool);
1070 		ctl_pool_free(softc, emergency_pool);
1071 		return (ENOMEM);
1072 	}
1073 
1074 	softc->internal_pool = internal_pool;
1075 	softc->emergency_pool = emergency_pool;
1076 	softc->othersc_pool = other_pool;
1077 
1078 	mtx_lock(&softc->ctl_lock);
1079 	ctl_pool_acquire(internal_pool);
1080 	ctl_pool_acquire(emergency_pool);
1081 	ctl_pool_acquire(other_pool);
1082 	mtx_unlock(&softc->ctl_lock);
1083 
1084 	/*
1085 	 * We used to allocate a processor LUN here.  The new scheme is to
1086 	 * just let the user allocate LUNs as he sees fit.
1087 	 */
1088 #if 0
1089 	mtx_lock(&softc->ctl_lock);
1090 	ctl_alloc_lun(softc, lun, /*be_lun*/NULL, /*target*/softc->target);
1091 	mtx_unlock(&softc->ctl_lock);
1092 #endif
1093 
1094 	error = kproc_create(ctl_work_thread, softc, &softc->work_thread, 0, 0,
1095 			 "ctl_thrd");
1096 	if (error != 0) {
1097 		printf("error creating CTL work thread!\n");
1098 		mtx_lock(&softc->ctl_lock);
1099 		ctl_free_lun(lun);
1100 		ctl_pool_free(softc, internal_pool);
1101 		ctl_pool_free(softc, emergency_pool);
1102 		ctl_pool_free(softc, other_pool);
1103 		mtx_unlock(&softc->ctl_lock);
1104 		return (error);
1105 	}
1106 	if (bootverbose)
1107 		printf("ctl: CAM Target Layer loaded\n");
1108 
1109 	/*
1110 	 * Initialize the initiator and portname mappings
1111 	 */
1112 	memset(softc->wwpn_iid, 0, sizeof(softc->wwpn_iid));
1113 
1114 	/*
1115 	 * Initialize the ioctl front end.
1116 	 */
1117 	fe = &softc->ioctl_info.fe;
1118 	sprintf(softc->ioctl_info.port_name, "CTL ioctl");
1119 	fe->port_type = CTL_PORT_IOCTL;
1120 	fe->num_requested_ctl_io = 100;
1121 	fe->port_name = softc->ioctl_info.port_name;
1122 	fe->port_online = ctl_ioctl_online;
1123 	fe->port_offline = ctl_ioctl_offline;
1124 	fe->onoff_arg = &softc->ioctl_info;
1125 	fe->targ_enable = ctl_ioctl_targ_enable;
1126 	fe->targ_disable = ctl_ioctl_targ_disable;
1127 	fe->lun_enable = ctl_ioctl_lun_enable;
1128 	fe->lun_disable = ctl_ioctl_lun_disable;
1129 	fe->targ_lun_arg = &softc->ioctl_info;
1130 	fe->fe_datamove = ctl_ioctl_datamove;
1131 	fe->fe_done = ctl_ioctl_done;
1132 	fe->max_targets = 15;
1133 	fe->max_target_id = 15;
1134 
1135 	if (ctl_frontend_register(&softc->ioctl_info.fe,
1136 	                  (softc->flags & CTL_FLAG_MASTER_SHELF)) != 0) {
1137 		printf("ctl: ioctl front end registration failed, will "
1138 		       "continue anyway\n");
1139 	}
1140 
1141 #ifdef CTL_IO_DELAY
1142 	if (sizeof(struct callout) > CTL_TIMER_BYTES) {
1143 		printf("sizeof(struct callout) %zd > CTL_TIMER_BYTES %zd\n",
1144 		       sizeof(struct callout), CTL_TIMER_BYTES);
1145 		return (EINVAL);
1146 	}
1147 #endif /* CTL_IO_DELAY */
1148 
1149 	return (0);
1150 }
1151 
1152 void
1153 ctl_shutdown(void)
1154 {
1155 	struct ctl_softc *softc;
1156 	struct ctl_lun *lun, *next_lun;
1157 	struct ctl_io_pool *pool, *next_pool;
1158 
1159 	softc = (struct ctl_softc *)control_softc;
1160 
1161 	if (ctl_frontend_deregister(&softc->ioctl_info.fe) != 0)
1162 		printf("ctl: ioctl front end deregistration failed\n");
1163 
1164 	mtx_lock(&softc->ctl_lock);
1165 
1166 	/*
1167 	 * Free up each LUN.
1168 	 */
1169 	for (lun = STAILQ_FIRST(&softc->lun_list); lun != NULL; lun = next_lun){
1170 		next_lun = STAILQ_NEXT(lun, links);
1171 		ctl_free_lun(lun);
1172 	}
1173 
1174 	/*
1175 	 * This will rip the rug out from under any FETDs or anyone else
1176 	 * that has a pool allocated.  Since we increment our module
1177 	 * refcount any time someone outside the main CTL module allocates
1178 	 * a pool, we shouldn't have any problems here.  The user won't be
1179 	 * able to unload the CTL module until client modules have
1180 	 * successfully unloaded.
1181 	 */
1182 	for (pool = STAILQ_FIRST(&softc->io_pools); pool != NULL;
1183 	     pool = next_pool) {
1184 		next_pool = STAILQ_NEXT(pool, links);
1185 		ctl_pool_free(softc, pool);
1186 	}
1187 
1188 	mtx_unlock(&softc->ctl_lock);
1189 
1190 #if 0
1191 	ctl_shutdown_thread(softc->work_thread);
1192 #endif
1193 
1194 	mtx_destroy(&softc->ctl_lock);
1195 
1196 	destroy_dev(softc->dev);
1197 
1198 	sysctl_ctx_free(&softc->sysctl_ctx);
1199 
1200 	free(control_softc, M_DEVBUF);
1201 	control_softc = NULL;
1202 
1203 	if (bootverbose)
1204 		printf("ctl: CAM Target Layer unloaded\n");
1205 }
1206 
1207 static int
1208 ctl_module_event_handler(module_t mod, int what, void *arg)
1209 {
1210 
1211 	switch (what) {
1212 	case MOD_LOAD:
1213 		return (ctl_init());
1214 	case MOD_UNLOAD:
1215 		return (EBUSY);
1216 	default:
1217 		return (EOPNOTSUPP);
1218 	}
1219 }
1220 
1221 /*
1222  * XXX KDM should we do some access checks here?  Bump a reference count to
1223  * prevent a CTL module from being unloaded while someone has it open?
1224  */
1225 static int
1226 ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
1227 {
1228 	return (0);
1229 }
1230 
1231 static int
1232 ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
1233 {
1234 	return (0);
1235 }
1236 
1237 int
1238 ctl_port_enable(ctl_port_type port_type)
1239 {
1240 	struct ctl_softc *softc;
1241 	struct ctl_frontend *fe;
1242 
1243 	if (ctl_is_single == 0) {
1244 		union ctl_ha_msg msg_info;
1245 		int isc_retval;
1246 
1247 #if 0
1248 		printf("%s: HA mode, synchronizing frontend enable\n",
1249 		        __func__);
1250 #endif
1251 		msg_info.hdr.msg_type = CTL_MSG_SYNC_FE;
1252 	        if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1253 		        sizeof(msg_info), 1 )) > CTL_HA_STATUS_SUCCESS) {
1254 			printf("Sync msg send error retval %d\n", isc_retval);
1255 		}
1256 		if (!rcv_sync_msg) {
1257 			isc_retval=ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
1258 			        sizeof(msg_info), 1);
1259 		}
1260 #if 0
1261         	printf("CTL:Frontend Enable\n");
1262 	} else {
1263 		printf("%s: single mode, skipping frontend synchronization\n",
1264 		        __func__);
1265 #endif
1266 	}
1267 
1268 	softc = control_softc;
1269 
1270 	STAILQ_FOREACH(fe, &softc->fe_list, links) {
1271 		if (port_type & fe->port_type)
1272 		{
1273 #if 0
1274 			printf("port %d\n", fe->targ_port);
1275 #endif
1276 			ctl_frontend_online(fe);
1277 		}
1278 	}
1279 
1280 	return (0);
1281 }
1282 
1283 int
1284 ctl_port_disable(ctl_port_type port_type)
1285 {
1286 	struct ctl_softc *softc;
1287 	struct ctl_frontend *fe;
1288 
1289 	softc = control_softc;
1290 
1291 	STAILQ_FOREACH(fe, &softc->fe_list, links) {
1292 		if (port_type & fe->port_type)
1293 			ctl_frontend_offline(fe);
1294 	}
1295 
1296 	return (0);
1297 }
1298 
1299 /*
1300  * Returns 0 for success, 1 for failure.
1301  * Currently the only failure mode is if there aren't enough entries
1302  * allocated.  So, in case of a failure, look at num_entries_dropped,
1303  * reallocate and try again.
1304  */
1305 int
1306 ctl_port_list(struct ctl_port_entry *entries, int num_entries_alloced,
1307 	      int *num_entries_filled, int *num_entries_dropped,
1308 	      ctl_port_type port_type, int no_virtual)
1309 {
1310 	struct ctl_softc *softc;
1311 	struct ctl_frontend *fe;
1312 	int entries_dropped, entries_filled;
1313 	int retval;
1314 	int i;
1315 
1316 	softc = control_softc;
1317 
1318 	retval = 0;
1319 	entries_filled = 0;
1320 	entries_dropped = 0;
1321 
1322 	i = 0;
1323 	mtx_lock(&softc->ctl_lock);
1324 	STAILQ_FOREACH(fe, &softc->fe_list, links) {
1325 		struct ctl_port_entry *entry;
1326 
1327 		if ((fe->port_type & port_type) == 0)
1328 			continue;
1329 
1330 		if ((no_virtual != 0)
1331 		 && (fe->virtual_port != 0))
1332 			continue;
1333 
1334 		if (entries_filled >= num_entries_alloced) {
1335 			entries_dropped++;
1336 			continue;
1337 		}
1338 		entry = &entries[i];
1339 
1340 		entry->port_type = fe->port_type;
1341 		strlcpy(entry->port_name, fe->port_name,
1342 			sizeof(entry->port_name));
1343 		entry->physical_port = fe->physical_port;
1344 		entry->virtual_port = fe->virtual_port;
1345 		entry->wwnn = fe->wwnn;
1346 		entry->wwpn = fe->wwpn;
1347 
1348 		i++;
1349 		entries_filled++;
1350 	}
1351 
1352 	mtx_unlock(&softc->ctl_lock);
1353 
1354 	if (entries_dropped > 0)
1355 		retval = 1;
1356 
1357 	*num_entries_dropped = entries_dropped;
1358 	*num_entries_filled = entries_filled;
1359 
1360 	return (retval);
1361 }
1362 
1363 static void
1364 ctl_ioctl_online(void *arg)
1365 {
1366 	struct ctl_ioctl_info *ioctl_info;
1367 
1368 	ioctl_info = (struct ctl_ioctl_info *)arg;
1369 
1370 	ioctl_info->flags |= CTL_IOCTL_FLAG_ENABLED;
1371 }
1372 
1373 static void
1374 ctl_ioctl_offline(void *arg)
1375 {
1376 	struct ctl_ioctl_info *ioctl_info;
1377 
1378 	ioctl_info = (struct ctl_ioctl_info *)arg;
1379 
1380 	ioctl_info->flags &= ~CTL_IOCTL_FLAG_ENABLED;
1381 }
1382 
1383 /*
1384  * Remove an initiator by port number and initiator ID.
1385  * Returns 0 for success, 1 for failure.
1386  */
1387 int
1388 ctl_remove_initiator(int32_t targ_port, uint32_t iid)
1389 {
1390 	struct ctl_softc *softc;
1391 
1392 	softc = control_softc;
1393 
1394 	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1395 
1396 	if ((targ_port < 0)
1397 	 || (targ_port > CTL_MAX_PORTS)) {
1398 		printf("%s: invalid port number %d\n", __func__, targ_port);
1399 		return (1);
1400 	}
1401 	if (iid > CTL_MAX_INIT_PER_PORT) {
1402 		printf("%s: initiator ID %u > maximun %u!\n",
1403 		       __func__, iid, CTL_MAX_INIT_PER_PORT);
1404 		return (1);
1405 	}
1406 
1407 	mtx_lock(&softc->ctl_lock);
1408 
1409 	softc->wwpn_iid[targ_port][iid].in_use = 0;
1410 
1411 	mtx_unlock(&softc->ctl_lock);
1412 
1413 	return (0);
1414 }
1415 
1416 /*
1417  * Add an initiator to the initiator map.
1418  * Returns 0 for success, 1 for failure.
1419  */
1420 int
1421 ctl_add_initiator(uint64_t wwpn, int32_t targ_port, uint32_t iid)
1422 {
1423 	struct ctl_softc *softc;
1424 	int retval;
1425 
1426 	softc = control_softc;
1427 
1428 	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1429 
1430 	retval = 0;
1431 
1432 	if ((targ_port < 0)
1433 	 || (targ_port > CTL_MAX_PORTS)) {
1434 		printf("%s: invalid port number %d\n", __func__, targ_port);
1435 		return (1);
1436 	}
1437 	if (iid > CTL_MAX_INIT_PER_PORT) {
1438 		printf("%s: WWPN %#jx initiator ID %u > maximun %u!\n",
1439 		       __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
1440 		return (1);
1441 	}
1442 
1443 	mtx_lock(&softc->ctl_lock);
1444 
1445 	if (softc->wwpn_iid[targ_port][iid].in_use != 0) {
1446 		/*
1447 		 * We don't treat this as an error.
1448 		 */
1449 		if (softc->wwpn_iid[targ_port][iid].wwpn == wwpn) {
1450 			printf("%s: port %d iid %u WWPN %#jx arrived again?\n",
1451 			       __func__, targ_port, iid, (uintmax_t)wwpn);
1452 			goto bailout;
1453 		}
1454 
1455 		/*
1456 		 * This is an error, but what do we do about it?  The
1457 		 * driver is telling us we have a new WWPN for this
1458 		 * initiator ID, so we pretty much need to use it.
1459 		 */
1460 		printf("%s: port %d iid %u WWPN %#jx arrived, WWPN %#jx is "
1461 		       "still at that address\n", __func__, targ_port, iid,
1462 		       (uintmax_t)wwpn,
1463 		       (uintmax_t)softc->wwpn_iid[targ_port][iid].wwpn);
1464 
1465 		/*
1466 		 * XXX KDM clear have_ca and ua_pending on each LUN for
1467 		 * this initiator.
1468 		 */
1469 	}
1470 	softc->wwpn_iid[targ_port][iid].in_use = 1;
1471 	softc->wwpn_iid[targ_port][iid].iid = iid;
1472 	softc->wwpn_iid[targ_port][iid].wwpn = wwpn;
1473 	softc->wwpn_iid[targ_port][iid].port = targ_port;
1474 
1475 bailout:
1476 
1477 	mtx_unlock(&softc->ctl_lock);
1478 
1479 	return (retval);
1480 }
1481 
1482 /*
1483  * XXX KDM should we pretend to do something in the target/lun
1484  * enable/disable functions?
1485  */
1486 static int
1487 ctl_ioctl_targ_enable(void *arg, struct ctl_id targ_id)
1488 {
1489 	return (0);
1490 }
1491 
1492 static int
1493 ctl_ioctl_targ_disable(void *arg, struct ctl_id targ_id)
1494 {
1495 	return (0);
1496 }
1497 
1498 static int
1499 ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id)
1500 {
1501 	return (0);
1502 }
1503 
1504 static int
1505 ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id)
1506 {
1507 	return (0);
1508 }
1509 
1510 /*
1511  * Data movement routine for the CTL ioctl frontend port.
1512  */
1513 static int
1514 ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio)
1515 {
1516 	struct ctl_sg_entry *ext_sglist, *kern_sglist;
1517 	struct ctl_sg_entry ext_entry, kern_entry;
1518 	int ext_sglen, ext_sg_entries, kern_sg_entries;
1519 	int ext_sg_start, ext_offset;
1520 	int len_to_copy, len_copied;
1521 	int kern_watermark, ext_watermark;
1522 	int ext_sglist_malloced;
1523 	int i, j;
1524 
1525 	ext_sglist_malloced = 0;
1526 	ext_sg_start = 0;
1527 	ext_offset = 0;
1528 
1529 	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove\n"));
1530 
1531 	/*
1532 	 * If this flag is set, fake the data transfer.
1533 	 */
1534 	if (ctsio->io_hdr.flags & CTL_FLAG_NO_DATAMOVE) {
1535 		ctsio->ext_data_filled = ctsio->ext_data_len;
1536 		goto bailout;
1537 	}
1538 
1539 	/*
1540 	 * To simplify things here, if we have a single buffer, stick it in
1541 	 * a S/G entry and just make it a single entry S/G list.
1542 	 */
1543 	if (ctsio->io_hdr.flags & CTL_FLAG_EDPTR_SGLIST) {
1544 		int len_seen;
1545 
1546 		ext_sglen = ctsio->ext_sg_entries * sizeof(*ext_sglist);
1547 
1548 		ext_sglist = (struct ctl_sg_entry *)malloc(ext_sglen, M_CTL,
1549 							   M_WAITOK);
1550 		ext_sglist_malloced = 1;
1551 		if (copyin(ctsio->ext_data_ptr, ext_sglist,
1552 				   ext_sglen) != 0) {
1553 			ctl_set_internal_failure(ctsio,
1554 						 /*sks_valid*/ 0,
1555 						 /*retry_count*/ 0);
1556 			goto bailout;
1557 		}
1558 		ext_sg_entries = ctsio->ext_sg_entries;
1559 		len_seen = 0;
1560 		for (i = 0; i < ext_sg_entries; i++) {
1561 			if ((len_seen + ext_sglist[i].len) >=
1562 			     ctsio->ext_data_filled) {
1563 				ext_sg_start = i;
1564 				ext_offset = ctsio->ext_data_filled - len_seen;
1565 				break;
1566 			}
1567 			len_seen += ext_sglist[i].len;
1568 		}
1569 	} else {
1570 		ext_sglist = &ext_entry;
1571 		ext_sglist->addr = ctsio->ext_data_ptr;
1572 		ext_sglist->len = ctsio->ext_data_len;
1573 		ext_sg_entries = 1;
1574 		ext_sg_start = 0;
1575 		ext_offset = ctsio->ext_data_filled;
1576 	}
1577 
1578 	if (ctsio->kern_sg_entries > 0) {
1579 		kern_sglist = (struct ctl_sg_entry *)ctsio->kern_data_ptr;
1580 		kern_sg_entries = ctsio->kern_sg_entries;
1581 	} else {
1582 		kern_sglist = &kern_entry;
1583 		kern_sglist->addr = ctsio->kern_data_ptr;
1584 		kern_sglist->len = ctsio->kern_data_len;
1585 		kern_sg_entries = 1;
1586 	}
1587 
1588 
1589 	kern_watermark = 0;
1590 	ext_watermark = ext_offset;
1591 	len_copied = 0;
1592 	for (i = ext_sg_start, j = 0;
1593 	     i < ext_sg_entries && j < kern_sg_entries;) {
1594 		uint8_t *ext_ptr, *kern_ptr;
1595 
1596 		len_to_copy = ctl_min(ext_sglist[i].len - ext_watermark,
1597 				      kern_sglist[j].len - kern_watermark);
1598 
1599 		ext_ptr = (uint8_t *)ext_sglist[i].addr;
1600 		ext_ptr = ext_ptr + ext_watermark;
1601 		if (ctsio->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
1602 			/*
1603 			 * XXX KDM fix this!
1604 			 */
1605 			panic("need to implement bus address support");
1606 #if 0
1607 			kern_ptr = bus_to_virt(kern_sglist[j].addr);
1608 #endif
1609 		} else
1610 			kern_ptr = (uint8_t *)kern_sglist[j].addr;
1611 		kern_ptr = kern_ptr + kern_watermark;
1612 
1613 		kern_watermark += len_to_copy;
1614 		ext_watermark += len_to_copy;
1615 
1616 		if ((ctsio->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
1617 		     CTL_FLAG_DATA_IN) {
1618 			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1619 					 "bytes to user\n", len_to_copy));
1620 			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1621 					 "to %p\n", kern_ptr, ext_ptr));
1622 			if (copyout(kern_ptr, ext_ptr, len_to_copy) != 0) {
1623 				ctl_set_internal_failure(ctsio,
1624 							 /*sks_valid*/ 0,
1625 							 /*retry_count*/ 0);
1626 				goto bailout;
1627 			}
1628 		} else {
1629 			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1630 					 "bytes from user\n", len_to_copy));
1631 			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1632 					 "to %p\n", ext_ptr, kern_ptr));
1633 			if (copyin(ext_ptr, kern_ptr, len_to_copy)!= 0){
1634 				ctl_set_internal_failure(ctsio,
1635 							 /*sks_valid*/ 0,
1636 							 /*retry_count*/0);
1637 				goto bailout;
1638 			}
1639 		}
1640 
1641 		len_copied += len_to_copy;
1642 
1643 		if (ext_sglist[i].len == ext_watermark) {
1644 			i++;
1645 			ext_watermark = 0;
1646 		}
1647 
1648 		if (kern_sglist[j].len == kern_watermark) {
1649 			j++;
1650 			kern_watermark = 0;
1651 		}
1652 	}
1653 
1654 	ctsio->ext_data_filled += len_copied;
1655 
1656 	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_sg_entries: %d, "
1657 			 "kern_sg_entries: %d\n", ext_sg_entries,
1658 			 kern_sg_entries));
1659 	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_data_len = %d, "
1660 			 "kern_data_len = %d\n", ctsio->ext_data_len,
1661 			 ctsio->kern_data_len));
1662 
1663 
1664 	/* XXX KDM set residual?? */
1665 bailout:
1666 
1667 	if (ext_sglist_malloced != 0)
1668 		free(ext_sglist, M_CTL);
1669 
1670 	return (CTL_RETVAL_COMPLETE);
1671 }
1672 
1673 /*
1674  * Serialize a command that went down the "wrong" side, and so was sent to
1675  * this controller for execution.  The logic is a little different than the
1676  * standard case in ctl_scsiio_precheck().  Errors in this case need to get
1677  * sent back to the other side, but in the success case, we execute the
1678  * command on this side (XFER mode) or tell the other side to execute it
1679  * (SER_ONLY mode).
1680  */
1681 static int
1682 ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio, int have_lock)
1683 {
1684 	struct ctl_softc *ctl_softc;
1685 	union ctl_ha_msg msg_info;
1686 	struct ctl_lun *lun;
1687 	int retval = 0;
1688 	uint32_t targ_lun;
1689 
1690 	ctl_softc = control_softc;
1691 	if (have_lock == 0)
1692 		mtx_lock(&ctl_softc->ctl_lock);
1693 
1694 	targ_lun = ctsio->io_hdr.nexus.targ_lun;
1695 	if (ctsio->io_hdr.nexus.lun_map_fn != NULL)
1696 		targ_lun = ctsio->io_hdr.nexus.lun_map_fn(ctsio->io_hdr.nexus.lun_map_arg, targ_lun);
1697 	lun = ctl_softc->ctl_luns[targ_lun];
1698 	if (lun==NULL)
1699 	{
1700 		/*
1701 		 * Why isn't LUN defined? The other side wouldn't
1702 		 * send a cmd if the LUN is undefined.
1703 		 */
1704 		printf("%s: Bad JUJU!, LUN is NULL!\n", __func__);
1705 
1706 		/* "Logical unit not supported" */
1707 		ctl_set_sense_data(&msg_info.scsi.sense_data,
1708 				   lun,
1709 				   /*sense_format*/SSD_TYPE_NONE,
1710 				   /*current_error*/ 1,
1711 				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1712 				   /*asc*/ 0x25,
1713 				   /*ascq*/ 0x00,
1714 				   SSD_ELEM_NONE);
1715 
1716 		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1717 		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1718 		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1719 		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1720 		msg_info.hdr.serializing_sc = NULL;
1721 		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1722 	        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1723 				sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1724 		}
1725 		if (have_lock == 0)
1726 			mtx_unlock(&ctl_softc->ctl_lock);
1727 		return(1);
1728 
1729 	}
1730 
1731     	TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1732 
1733 	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
1734 		(union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
1735 		 ooa_links))) {
1736 	case CTL_ACTION_BLOCK:
1737 		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
1738 		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
1739 				  blocked_links);
1740 		break;
1741 	case CTL_ACTION_PASS:
1742 	case CTL_ACTION_SKIP:
1743 		if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
1744 			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
1745 			STAILQ_INSERT_TAIL(&ctl_softc->rtr_queue,
1746 					   &ctsio->io_hdr, links);
1747 		} else {
1748 
1749 			/* send msg back to other side */
1750 			msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1751 			msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
1752 			msg_info.hdr.msg_type = CTL_MSG_R2R;
1753 #if 0
1754 			printf("2. pOrig %x\n", (int)msg_info.hdr.original_sc);
1755 #endif
1756 		        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1757 			    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1758 			}
1759 		}
1760 		break;
1761 	case CTL_ACTION_OVERLAP:
1762 		/* OVERLAPPED COMMANDS ATTEMPTED */
1763 		ctl_set_sense_data(&msg_info.scsi.sense_data,
1764 				   lun,
1765 				   /*sense_format*/SSD_TYPE_NONE,
1766 				   /*current_error*/ 1,
1767 				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1768 				   /*asc*/ 0x4E,
1769 				   /*ascq*/ 0x00,
1770 				   SSD_ELEM_NONE);
1771 
1772 		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1773 		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1774 		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1775 		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1776 		msg_info.hdr.serializing_sc = NULL;
1777 		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1778 #if 0
1779 		printf("BAD JUJU:Major Bummer Overlap\n");
1780 #endif
1781 		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1782 		retval = 1;
1783 		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1784 		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1785 		}
1786 		break;
1787 	case CTL_ACTION_OVERLAP_TAG:
1788 		/* TAGGED OVERLAPPED COMMANDS (NN = QUEUE TAG) */
1789 		ctl_set_sense_data(&msg_info.scsi.sense_data,
1790 				   lun,
1791 				   /*sense_format*/SSD_TYPE_NONE,
1792 				   /*current_error*/ 1,
1793 				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1794 				   /*asc*/ 0x4D,
1795 				   /*ascq*/ ctsio->tag_num & 0xff,
1796 				   SSD_ELEM_NONE);
1797 
1798 		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1799 		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1800 		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1801 		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1802 		msg_info.hdr.serializing_sc = NULL;
1803 		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1804 #if 0
1805 		printf("BAD JUJU:Major Bummer Overlap Tag\n");
1806 #endif
1807 		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1808 		retval = 1;
1809 		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1810 		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1811 		}
1812 		break;
1813 	case CTL_ACTION_ERROR:
1814 	default:
1815 		/* "Internal target failure" */
1816 		ctl_set_sense_data(&msg_info.scsi.sense_data,
1817 				   lun,
1818 				   /*sense_format*/SSD_TYPE_NONE,
1819 				   /*current_error*/ 1,
1820 				   /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
1821 				   /*asc*/ 0x44,
1822 				   /*ascq*/ 0x00,
1823 				   SSD_ELEM_NONE);
1824 
1825 		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1826 		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1827 		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1828 		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1829 		msg_info.hdr.serializing_sc = NULL;
1830 		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1831 #if 0
1832 		printf("BAD JUJU:Major Bummer HW Error\n");
1833 #endif
1834 		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1835 		retval = 1;
1836 		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1837 		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1838 		}
1839 		break;
1840 	}
1841 	if (have_lock == 0)
1842 		mtx_unlock(&ctl_softc->ctl_lock);
1843 	return (retval);
1844 }
1845 
1846 static int
1847 ctl_ioctl_submit_wait(union ctl_io *io)
1848 {
1849 	struct ctl_fe_ioctl_params params;
1850 	ctl_fe_ioctl_state last_state;
1851 	int done, retval;
1852 
1853 	retval = 0;
1854 
1855 	bzero(&params, sizeof(params));
1856 
1857 	mtx_init(&params.ioctl_mtx, "ctliocmtx", NULL, MTX_DEF);
1858 	cv_init(&params.sem, "ctlioccv");
1859 	params.state = CTL_IOCTL_INPROG;
1860 	last_state = params.state;
1861 
1862 	io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr = &params;
1863 
1864 	CTL_DEBUG_PRINT(("ctl_ioctl_submit_wait\n"));
1865 
1866 	/* This shouldn't happen */
1867 	if ((retval = ctl_queue(io)) != CTL_RETVAL_COMPLETE)
1868 		return (retval);
1869 
1870 	done = 0;
1871 
1872 	do {
1873 		mtx_lock(&params.ioctl_mtx);
1874 		/*
1875 		 * Check the state here, and don't sleep if the state has
1876 		 * already changed (i.e. wakeup has already occured, but we
1877 		 * weren't waiting yet).
1878 		 */
1879 		if (params.state == last_state) {
1880 			/* XXX KDM cv_wait_sig instead? */
1881 			cv_wait(&params.sem, &params.ioctl_mtx);
1882 		}
1883 		last_state = params.state;
1884 
1885 		switch (params.state) {
1886 		case CTL_IOCTL_INPROG:
1887 			/* Why did we wake up? */
1888 			/* XXX KDM error here? */
1889 			mtx_unlock(&params.ioctl_mtx);
1890 			break;
1891 		case CTL_IOCTL_DATAMOVE:
1892 			CTL_DEBUG_PRINT(("got CTL_IOCTL_DATAMOVE\n"));
1893 
1894 			/*
1895 			 * change last_state back to INPROG to avoid
1896 			 * deadlock on subsequent data moves.
1897 			 */
1898 			params.state = last_state = CTL_IOCTL_INPROG;
1899 
1900 			mtx_unlock(&params.ioctl_mtx);
1901 			ctl_ioctl_do_datamove(&io->scsiio);
1902 			/*
1903 			 * Note that in some cases, most notably writes,
1904 			 * this will queue the I/O and call us back later.
1905 			 * In other cases, generally reads, this routine
1906 			 * will immediately call back and wake us up,
1907 			 * probably using our own context.
1908 			 */
1909 			io->scsiio.be_move_done(io);
1910 			break;
1911 		case CTL_IOCTL_DONE:
1912 			mtx_unlock(&params.ioctl_mtx);
1913 			CTL_DEBUG_PRINT(("got CTL_IOCTL_DONE\n"));
1914 			done = 1;
1915 			break;
1916 		default:
1917 			mtx_unlock(&params.ioctl_mtx);
1918 			/* XXX KDM error here? */
1919 			break;
1920 		}
1921 	} while (done == 0);
1922 
1923 	mtx_destroy(&params.ioctl_mtx);
1924 	cv_destroy(&params.sem);
1925 
1926 	return (CTL_RETVAL_COMPLETE);
1927 }
1928 
1929 static void
1930 ctl_ioctl_datamove(union ctl_io *io)
1931 {
1932 	struct ctl_fe_ioctl_params *params;
1933 
1934 	params = (struct ctl_fe_ioctl_params *)
1935 		io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
1936 
1937 	mtx_lock(&params->ioctl_mtx);
1938 	params->state = CTL_IOCTL_DATAMOVE;
1939 	cv_broadcast(&params->sem);
1940 	mtx_unlock(&params->ioctl_mtx);
1941 }
1942 
1943 static void
1944 ctl_ioctl_done(union ctl_io *io)
1945 {
1946 	struct ctl_fe_ioctl_params *params;
1947 
1948 	params = (struct ctl_fe_ioctl_params *)
1949 		io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
1950 
1951 	mtx_lock(&params->ioctl_mtx);
1952 	params->state = CTL_IOCTL_DONE;
1953 	cv_broadcast(&params->sem);
1954 	mtx_unlock(&params->ioctl_mtx);
1955 }
1956 
1957 static void
1958 ctl_ioctl_hard_startstop_callback(void *arg, struct cfi_metatask *metatask)
1959 {
1960 	struct ctl_fe_ioctl_startstop_info *sd_info;
1961 
1962 	sd_info = (struct ctl_fe_ioctl_startstop_info *)arg;
1963 
1964 	sd_info->hs_info.status = metatask->status;
1965 	sd_info->hs_info.total_luns = metatask->taskinfo.startstop.total_luns;
1966 	sd_info->hs_info.luns_complete =
1967 		metatask->taskinfo.startstop.luns_complete;
1968 	sd_info->hs_info.luns_failed = metatask->taskinfo.startstop.luns_failed;
1969 
1970 	cv_broadcast(&sd_info->sem);
1971 }
1972 
1973 static void
1974 ctl_ioctl_bbrread_callback(void *arg, struct cfi_metatask *metatask)
1975 {
1976 	struct ctl_fe_ioctl_bbrread_info *fe_bbr_info;
1977 
1978 	fe_bbr_info = (struct ctl_fe_ioctl_bbrread_info *)arg;
1979 
1980 	mtx_lock(fe_bbr_info->lock);
1981 	fe_bbr_info->bbr_info->status = metatask->status;
1982 	fe_bbr_info->bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
1983 	fe_bbr_info->wakeup_done = 1;
1984 	mtx_unlock(fe_bbr_info->lock);
1985 
1986 	cv_broadcast(&fe_bbr_info->sem);
1987 }
1988 
1989 /*
1990  * Returns 0 for success, errno for failure.
1991  */
1992 static int
1993 ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
1994 		   struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
1995 {
1996 	union ctl_io *io;
1997 	int retval;
1998 
1999 	retval = 0;
2000 
2001 	mtx_assert(&control_softc->ctl_lock, MA_OWNED);
2002 
2003 	for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
2004 	     (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2005 	     ooa_links)) {
2006 		struct ctl_ooa_entry *entry;
2007 
2008 		/*
2009 		 * If we've got more than we can fit, just count the
2010 		 * remaining entries.
2011 		 */
2012 		if (*cur_fill_num >= ooa_hdr->alloc_num)
2013 			continue;
2014 
2015 		entry = &kern_entries[*cur_fill_num];
2016 
2017 		entry->tag_num = io->scsiio.tag_num;
2018 		entry->lun_num = lun->lun;
2019 #ifdef CTL_TIME_IO
2020 		entry->start_bt = io->io_hdr.start_bt;
2021 #endif
2022 		bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2023 		entry->cdb_len = io->scsiio.cdb_len;
2024 		if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
2025 			entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2026 
2027 		if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2028 			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2029 
2030 		if (io->io_hdr.flags & CTL_FLAG_ABORT)
2031 			entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2032 
2033 		if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2034 			entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2035 
2036 		if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2037 			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2038 	}
2039 
2040 	return (retval);
2041 }
2042 
2043 static void *
2044 ctl_copyin_alloc(void *user_addr, int len, char *error_str,
2045 		 size_t error_str_len)
2046 {
2047 	void *kptr;
2048 
2049 	kptr = malloc(len, M_CTL, M_WAITOK | M_ZERO);
2050 
2051 	if (copyin(user_addr, kptr, len) != 0) {
2052 		snprintf(error_str, error_str_len, "Error copying %d bytes "
2053 			 "from user address %p to kernel address %p", len,
2054 			 user_addr, kptr);
2055 		free(kptr, M_CTL);
2056 		return (NULL);
2057 	}
2058 
2059 	return (kptr);
2060 }
2061 
2062 static void
2063 ctl_free_args(int num_be_args, struct ctl_be_arg *be_args)
2064 {
2065 	int i;
2066 
2067 	if (be_args == NULL)
2068 		return;
2069 
2070 	for (i = 0; i < num_be_args; i++) {
2071 		free(be_args[i].kname, M_CTL);
2072 		free(be_args[i].kvalue, M_CTL);
2073 	}
2074 
2075 	free(be_args, M_CTL);
2076 }
2077 
2078 static struct ctl_be_arg *
2079 ctl_copyin_args(int num_be_args, struct ctl_be_arg *be_args,
2080 		char *error_str, size_t error_str_len)
2081 {
2082 	struct ctl_be_arg *args;
2083 	int i;
2084 
2085 	args = ctl_copyin_alloc(be_args, num_be_args * sizeof(*be_args),
2086 				error_str, error_str_len);
2087 
2088 	if (args == NULL)
2089 		goto bailout;
2090 
2091 	for (i = 0; i < num_be_args; i++) {
2092 		args[i].kname = NULL;
2093 		args[i].kvalue = NULL;
2094 	}
2095 
2096 	for (i = 0; i < num_be_args; i++) {
2097 		uint8_t *tmpptr;
2098 
2099 		args[i].kname = ctl_copyin_alloc(args[i].name,
2100 			args[i].namelen, error_str, error_str_len);
2101 		if (args[i].kname == NULL)
2102 			goto bailout;
2103 
2104 		if (args[i].kname[args[i].namelen - 1] != '\0') {
2105 			snprintf(error_str, error_str_len, "Argument %d "
2106 				 "name is not NUL-terminated", i);
2107 			goto bailout;
2108 		}
2109 
2110 		args[i].kvalue = NULL;
2111 
2112 		tmpptr = ctl_copyin_alloc(args[i].value,
2113 			args[i].vallen, error_str, error_str_len);
2114 		if (tmpptr == NULL)
2115 			goto bailout;
2116 
2117 		args[i].kvalue = tmpptr;
2118 
2119 		if ((args[i].flags & CTL_BEARG_ASCII)
2120 		 && (tmpptr[args[i].vallen - 1] != '\0')) {
2121 			snprintf(error_str, error_str_len, "Argument %d "
2122 				 "value is not NUL-terminated", i);
2123 			goto bailout;
2124 		}
2125 	}
2126 
2127 	return (args);
2128 bailout:
2129 
2130 	ctl_free_args(num_be_args, args);
2131 
2132 	return (NULL);
2133 }
2134 
2135 /*
2136  * Escape characters that are illegal or not recommended in XML.
2137  */
2138 int
2139 ctl_sbuf_printf_esc(struct sbuf *sb, char *str)
2140 {
2141 	int retval;
2142 
2143 	retval = 0;
2144 
2145 	for (; *str; str++) {
2146 		switch (*str) {
2147 		case '&':
2148 			retval = sbuf_printf(sb, "&amp;");
2149 			break;
2150 		case '>':
2151 			retval = sbuf_printf(sb, "&gt;");
2152 			break;
2153 		case '<':
2154 			retval = sbuf_printf(sb, "&lt;");
2155 			break;
2156 		default:
2157 			retval = sbuf_putc(sb, *str);
2158 			break;
2159 		}
2160 
2161 		if (retval != 0)
2162 			break;
2163 
2164 	}
2165 
2166 	return (retval);
2167 }
2168 
2169 static int
2170 ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2171 	  struct thread *td)
2172 {
2173 	struct ctl_softc *softc;
2174 	int retval;
2175 
2176 	softc = control_softc;
2177 
2178 	retval = 0;
2179 
2180 	switch (cmd) {
2181 	case CTL_IO: {
2182 		union ctl_io *io;
2183 		void *pool_tmp;
2184 
2185 		/*
2186 		 * If we haven't been "enabled", don't allow any SCSI I/O
2187 		 * to this FETD.
2188 		 */
2189 		if ((softc->ioctl_info.flags & CTL_IOCTL_FLAG_ENABLED) == 0) {
2190 			retval = -EPERM;
2191 			break;
2192 		}
2193 
2194 		io = ctl_alloc_io(softc->ioctl_info.fe.ctl_pool_ref);
2195 		if (io == NULL) {
2196 			printf("ctl_ioctl: can't allocate ctl_io!\n");
2197 			retval = -ENOSPC;
2198 			break;
2199 		}
2200 
2201 		/*
2202 		 * Need to save the pool reference so it doesn't get
2203 		 * spammed by the user's ctl_io.
2204 		 */
2205 		pool_tmp = io->io_hdr.pool;
2206 
2207 		memcpy(io, (void *)addr, sizeof(*io));
2208 
2209 		io->io_hdr.pool = pool_tmp;
2210 		/*
2211 		 * No status yet, so make sure the status is set properly.
2212 		 */
2213 		io->io_hdr.status = CTL_STATUS_NONE;
2214 
2215 		/*
2216 		 * The user sets the initiator ID, target and LUN IDs.
2217 		 */
2218 		io->io_hdr.nexus.targ_port = softc->ioctl_info.fe.targ_port;
2219 		io->io_hdr.flags |= CTL_FLAG_USER_REQ;
2220 		if ((io->io_hdr.io_type == CTL_IO_SCSI)
2221 		 && (io->scsiio.tag_type != CTL_TAG_UNTAGGED))
2222 			io->scsiio.tag_num = softc->ioctl_info.cur_tag_num++;
2223 
2224 		retval = ctl_ioctl_submit_wait(io);
2225 
2226 		if (retval != 0) {
2227 			ctl_free_io(io);
2228 			break;
2229 		}
2230 
2231 		memcpy((void *)addr, io, sizeof(*io));
2232 
2233 		/* return this to our pool */
2234 		ctl_free_io(io);
2235 
2236 		break;
2237 	}
2238 	case CTL_ENABLE_PORT:
2239 	case CTL_DISABLE_PORT:
2240 	case CTL_SET_PORT_WWNS: {
2241 		struct ctl_frontend *fe;
2242 		struct ctl_port_entry *entry;
2243 
2244 		entry = (struct ctl_port_entry *)addr;
2245 
2246 		mtx_lock(&softc->ctl_lock);
2247 		STAILQ_FOREACH(fe, &softc->fe_list, links) {
2248 			int action, done;
2249 
2250 			action = 0;
2251 			done = 0;
2252 
2253 			if ((entry->port_type == CTL_PORT_NONE)
2254 			 && (entry->targ_port == fe->targ_port)) {
2255 				/*
2256 				 * If the user only wants to enable or
2257 				 * disable or set WWNs on a specific port,
2258 				 * do the operation and we're done.
2259 				 */
2260 				action = 1;
2261 				done = 1;
2262 			} else if (entry->port_type & fe->port_type) {
2263 				/*
2264 				 * Compare the user's type mask with the
2265 				 * particular frontend type to see if we
2266 				 * have a match.
2267 				 */
2268 				action = 1;
2269 				done = 0;
2270 
2271 				/*
2272 				 * Make sure the user isn't trying to set
2273 				 * WWNs on multiple ports at the same time.
2274 				 */
2275 				if (cmd == CTL_SET_PORT_WWNS) {
2276 					printf("%s: Can't set WWNs on "
2277 					       "multiple ports\n", __func__);
2278 					retval = EINVAL;
2279 					break;
2280 				}
2281 			}
2282 			if (action != 0) {
2283 				/*
2284 				 * XXX KDM we have to drop the lock here,
2285 				 * because the online/offline operations
2286 				 * can potentially block.  We need to
2287 				 * reference count the frontends so they
2288 				 * can't go away,
2289 				 */
2290 				mtx_unlock(&softc->ctl_lock);
2291 
2292 				if (cmd == CTL_ENABLE_PORT) {
2293 					struct ctl_lun *lun;
2294 
2295 					STAILQ_FOREACH(lun, &softc->lun_list,
2296 						       links) {
2297 						fe->lun_enable(fe->targ_lun_arg,
2298 						    lun->target,
2299 						    lun->lun);
2300 					}
2301 
2302 					ctl_frontend_online(fe);
2303 				} else if (cmd == CTL_DISABLE_PORT) {
2304 					struct ctl_lun *lun;
2305 
2306 					ctl_frontend_offline(fe);
2307 
2308 					STAILQ_FOREACH(lun, &softc->lun_list,
2309 						       links) {
2310 						fe->lun_disable(
2311 						    fe->targ_lun_arg,
2312 						    lun->target,
2313 						    lun->lun);
2314 					}
2315 				}
2316 
2317 				mtx_lock(&softc->ctl_lock);
2318 
2319 				if (cmd == CTL_SET_PORT_WWNS)
2320 					ctl_frontend_set_wwns(fe,
2321 					    (entry->flags & CTL_PORT_WWNN_VALID) ?
2322 					    1 : 0, entry->wwnn,
2323 					    (entry->flags & CTL_PORT_WWPN_VALID) ?
2324 					    1 : 0, entry->wwpn);
2325 			}
2326 			if (done != 0)
2327 				break;
2328 		}
2329 		mtx_unlock(&softc->ctl_lock);
2330 		break;
2331 	}
2332 	case CTL_GET_PORT_LIST: {
2333 		struct ctl_frontend *fe;
2334 		struct ctl_port_list *list;
2335 		int i;
2336 
2337 		list = (struct ctl_port_list *)addr;
2338 
2339 		if (list->alloc_len != (list->alloc_num *
2340 		    sizeof(struct ctl_port_entry))) {
2341 			printf("%s: CTL_GET_PORT_LIST: alloc_len %u != "
2342 			       "alloc_num %u * sizeof(struct ctl_port_entry) "
2343 			       "%zu\n", __func__, list->alloc_len,
2344 			       list->alloc_num, sizeof(struct ctl_port_entry));
2345 			retval = EINVAL;
2346 			break;
2347 		}
2348 		list->fill_len = 0;
2349 		list->fill_num = 0;
2350 		list->dropped_num = 0;
2351 		i = 0;
2352 		mtx_lock(&softc->ctl_lock);
2353 		STAILQ_FOREACH(fe, &softc->fe_list, links) {
2354 			struct ctl_port_entry entry, *list_entry;
2355 
2356 			if (list->fill_num >= list->alloc_num) {
2357 				list->dropped_num++;
2358 				continue;
2359 			}
2360 
2361 			entry.port_type = fe->port_type;
2362 			strlcpy(entry.port_name, fe->port_name,
2363 				sizeof(entry.port_name));
2364 			entry.targ_port = fe->targ_port;
2365 			entry.physical_port = fe->physical_port;
2366 			entry.virtual_port = fe->virtual_port;
2367 			entry.wwnn = fe->wwnn;
2368 			entry.wwpn = fe->wwpn;
2369 			if (fe->status & CTL_PORT_STATUS_ONLINE)
2370 				entry.online = 1;
2371 			else
2372 				entry.online = 0;
2373 
2374 			list_entry = &list->entries[i];
2375 
2376 			retval = copyout(&entry, list_entry, sizeof(entry));
2377 			if (retval != 0) {
2378 				printf("%s: CTL_GET_PORT_LIST: copyout "
2379 				       "returned %d\n", __func__, retval);
2380 				break;
2381 			}
2382 			i++;
2383 			list->fill_num++;
2384 			list->fill_len += sizeof(entry);
2385 		}
2386 		mtx_unlock(&softc->ctl_lock);
2387 
2388 		/*
2389 		 * If this is non-zero, we had a copyout fault, so there's
2390 		 * probably no point in attempting to set the status inside
2391 		 * the structure.
2392 		 */
2393 		if (retval != 0)
2394 			break;
2395 
2396 		if (list->dropped_num > 0)
2397 			list->status = CTL_PORT_LIST_NEED_MORE_SPACE;
2398 		else
2399 			list->status = CTL_PORT_LIST_OK;
2400 		break;
2401 	}
2402 	case CTL_DUMP_OOA: {
2403 		struct ctl_lun *lun;
2404 		union ctl_io *io;
2405 		char printbuf[128];
2406 		struct sbuf sb;
2407 
2408 		mtx_lock(&softc->ctl_lock);
2409 		printf("Dumping OOA queues:\n");
2410 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
2411 			for (io = (union ctl_io *)TAILQ_FIRST(
2412 			     &lun->ooa_queue); io != NULL;
2413 			     io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2414 			     ooa_links)) {
2415 				sbuf_new(&sb, printbuf, sizeof(printbuf),
2416 					 SBUF_FIXEDLEN);
2417 				sbuf_printf(&sb, "LUN %jd tag 0x%04x%s%s%s%s: ",
2418 					    (intmax_t)lun->lun,
2419 					    io->scsiio.tag_num,
2420 					    (io->io_hdr.flags &
2421 					    CTL_FLAG_BLOCKED) ? "" : " BLOCKED",
2422 					    (io->io_hdr.flags &
2423 					    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
2424 					    (io->io_hdr.flags &
2425 					    CTL_FLAG_ABORT) ? " ABORT" : "",
2426 			                    (io->io_hdr.flags &
2427 		                        CTL_FLAG_IS_WAS_ON_RTR) ? " RTR" : "");
2428 				ctl_scsi_command_string(&io->scsiio, NULL, &sb);
2429 				sbuf_finish(&sb);
2430 				printf("%s\n", sbuf_data(&sb));
2431 			}
2432 		}
2433 		printf("OOA queues dump done\n");
2434 		mtx_unlock(&softc->ctl_lock);
2435 		break;
2436 	}
2437 	case CTL_GET_OOA: {
2438 		struct ctl_lun *lun;
2439 		struct ctl_ooa *ooa_hdr;
2440 		struct ctl_ooa_entry *entries;
2441 		uint32_t cur_fill_num;
2442 
2443 		ooa_hdr = (struct ctl_ooa *)addr;
2444 
2445 		if ((ooa_hdr->alloc_len == 0)
2446 		 || (ooa_hdr->alloc_num == 0)) {
2447 			printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2448 			       "must be non-zero\n", __func__,
2449 			       ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2450 			retval = EINVAL;
2451 			break;
2452 		}
2453 
2454 		if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2455 		    sizeof(struct ctl_ooa_entry))) {
2456 			printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2457 			       "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2458 			       __func__, ooa_hdr->alloc_len,
2459 			       ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2460 			retval = EINVAL;
2461 			break;
2462 		}
2463 
2464 		entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2465 		if (entries == NULL) {
2466 			printf("%s: could not allocate %d bytes for OOA "
2467 			       "dump\n", __func__, ooa_hdr->alloc_len);
2468 			retval = ENOMEM;
2469 			break;
2470 		}
2471 
2472 		mtx_lock(&softc->ctl_lock);
2473 		if (((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0)
2474 		 && ((ooa_hdr->lun_num > CTL_MAX_LUNS)
2475 		  || (softc->ctl_luns[ooa_hdr->lun_num] == NULL))) {
2476 			mtx_unlock(&softc->ctl_lock);
2477 			free(entries, M_CTL);
2478 			printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2479 			       __func__, (uintmax_t)ooa_hdr->lun_num);
2480 			retval = EINVAL;
2481 			break;
2482 		}
2483 
2484 		cur_fill_num = 0;
2485 
2486 		if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2487 			STAILQ_FOREACH(lun, &softc->lun_list, links) {
2488 				retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2489 					ooa_hdr, entries);
2490 				if (retval != 0)
2491 					break;
2492 			}
2493 			if (retval != 0) {
2494 				mtx_unlock(&softc->ctl_lock);
2495 				free(entries, M_CTL);
2496 				break;
2497 			}
2498 		} else {
2499 			lun = softc->ctl_luns[ooa_hdr->lun_num];
2500 
2501 			retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,ooa_hdr,
2502 						    entries);
2503 		}
2504 		mtx_unlock(&softc->ctl_lock);
2505 
2506 		ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2507 		ooa_hdr->fill_len = ooa_hdr->fill_num *
2508 			sizeof(struct ctl_ooa_entry);
2509 		retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2510 		if (retval != 0) {
2511 			printf("%s: error copying out %d bytes for OOA dump\n",
2512 			       __func__, ooa_hdr->fill_len);
2513 		}
2514 
2515 		getbintime(&ooa_hdr->cur_bt);
2516 
2517 		if (cur_fill_num > ooa_hdr->alloc_num) {
2518 			ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2519 			ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2520 		} else {
2521 			ooa_hdr->dropped_num = 0;
2522 			ooa_hdr->status = CTL_OOA_OK;
2523 		}
2524 
2525 		free(entries, M_CTL);
2526 		break;
2527 	}
2528 	case CTL_CHECK_OOA: {
2529 		union ctl_io *io;
2530 		struct ctl_lun *lun;
2531 		struct ctl_ooa_info *ooa_info;
2532 
2533 
2534 		ooa_info = (struct ctl_ooa_info *)addr;
2535 
2536 		if (ooa_info->lun_id >= CTL_MAX_LUNS) {
2537 			ooa_info->status = CTL_OOA_INVALID_LUN;
2538 			break;
2539 		}
2540 		mtx_lock(&softc->ctl_lock);
2541 		lun = softc->ctl_luns[ooa_info->lun_id];
2542 		if (lun == NULL) {
2543 			mtx_unlock(&softc->ctl_lock);
2544 			ooa_info->status = CTL_OOA_INVALID_LUN;
2545 			break;
2546 		}
2547 
2548 		ooa_info->num_entries = 0;
2549 		for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
2550 		     io != NULL; io = (union ctl_io *)TAILQ_NEXT(
2551 		     &io->io_hdr, ooa_links)) {
2552 			ooa_info->num_entries++;
2553 		}
2554 
2555 		mtx_unlock(&softc->ctl_lock);
2556 		ooa_info->status = CTL_OOA_SUCCESS;
2557 
2558 		break;
2559 	}
2560 	case CTL_HARD_START:
2561 	case CTL_HARD_STOP: {
2562 		struct ctl_fe_ioctl_startstop_info ss_info;
2563 		struct cfi_metatask *metatask;
2564 		struct mtx hs_mtx;
2565 
2566 		mtx_init(&hs_mtx, "HS Mutex", NULL, MTX_DEF);
2567 
2568 		cv_init(&ss_info.sem, "hard start/stop cv" );
2569 
2570 		metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2571 		if (metatask == NULL) {
2572 			retval = ENOMEM;
2573 			mtx_destroy(&hs_mtx);
2574 			break;
2575 		}
2576 
2577 		if (cmd == CTL_HARD_START)
2578 			metatask->tasktype = CFI_TASK_STARTUP;
2579 		else
2580 			metatask->tasktype = CFI_TASK_SHUTDOWN;
2581 
2582 		metatask->callback = ctl_ioctl_hard_startstop_callback;
2583 		metatask->callback_arg = &ss_info;
2584 
2585 		cfi_action(metatask);
2586 
2587 		/* Wait for the callback */
2588 		mtx_lock(&hs_mtx);
2589 		cv_wait_sig(&ss_info.sem, &hs_mtx);
2590 		mtx_unlock(&hs_mtx);
2591 
2592 		/*
2593 		 * All information has been copied from the metatask by the
2594 		 * time cv_broadcast() is called, so we free the metatask here.
2595 		 */
2596 		cfi_free_metatask(metatask);
2597 
2598 		memcpy((void *)addr, &ss_info.hs_info, sizeof(ss_info.hs_info));
2599 
2600 		mtx_destroy(&hs_mtx);
2601 		break;
2602 	}
2603 	case CTL_BBRREAD: {
2604 		struct ctl_bbrread_info *bbr_info;
2605 		struct ctl_fe_ioctl_bbrread_info fe_bbr_info;
2606 		struct mtx bbr_mtx;
2607 		struct cfi_metatask *metatask;
2608 
2609 		bbr_info = (struct ctl_bbrread_info *)addr;
2610 
2611 		bzero(&fe_bbr_info, sizeof(fe_bbr_info));
2612 
2613 		bzero(&bbr_mtx, sizeof(bbr_mtx));
2614 		mtx_init(&bbr_mtx, "BBR Mutex", NULL, MTX_DEF);
2615 
2616 		fe_bbr_info.bbr_info = bbr_info;
2617 		fe_bbr_info.lock = &bbr_mtx;
2618 
2619 		cv_init(&fe_bbr_info.sem, "BBR read cv");
2620 		metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2621 
2622 		if (metatask == NULL) {
2623 			mtx_destroy(&bbr_mtx);
2624 			cv_destroy(&fe_bbr_info.sem);
2625 			retval = ENOMEM;
2626 			break;
2627 		}
2628 		metatask->tasktype = CFI_TASK_BBRREAD;
2629 		metatask->callback = ctl_ioctl_bbrread_callback;
2630 		metatask->callback_arg = &fe_bbr_info;
2631 		metatask->taskinfo.bbrread.lun_num = bbr_info->lun_num;
2632 		metatask->taskinfo.bbrread.lba = bbr_info->lba;
2633 		metatask->taskinfo.bbrread.len = bbr_info->len;
2634 
2635 		cfi_action(metatask);
2636 
2637 		mtx_lock(&bbr_mtx);
2638 		while (fe_bbr_info.wakeup_done == 0)
2639 			cv_wait_sig(&fe_bbr_info.sem, &bbr_mtx);
2640 		mtx_unlock(&bbr_mtx);
2641 
2642 		bbr_info->status = metatask->status;
2643 		bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2644 		bbr_info->scsi_status = metatask->taskinfo.bbrread.scsi_status;
2645 		memcpy(&bbr_info->sense_data,
2646 		       &metatask->taskinfo.bbrread.sense_data,
2647 		       ctl_min(sizeof(bbr_info->sense_data),
2648 			       sizeof(metatask->taskinfo.bbrread.sense_data)));
2649 
2650 		cfi_free_metatask(metatask);
2651 
2652 		mtx_destroy(&bbr_mtx);
2653 		cv_destroy(&fe_bbr_info.sem);
2654 
2655 		break;
2656 	}
2657 	case CTL_DELAY_IO: {
2658 		struct ctl_io_delay_info *delay_info;
2659 #ifdef CTL_IO_DELAY
2660 		struct ctl_lun *lun;
2661 #endif /* CTL_IO_DELAY */
2662 
2663 		delay_info = (struct ctl_io_delay_info *)addr;
2664 
2665 #ifdef CTL_IO_DELAY
2666 		mtx_lock(&softc->ctl_lock);
2667 
2668 		if ((delay_info->lun_id > CTL_MAX_LUNS)
2669 		 || (softc->ctl_luns[delay_info->lun_id] == NULL)) {
2670 			delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2671 		} else {
2672 			lun = softc->ctl_luns[delay_info->lun_id];
2673 
2674 			delay_info->status = CTL_DELAY_STATUS_OK;
2675 
2676 			switch (delay_info->delay_type) {
2677 			case CTL_DELAY_TYPE_CONT:
2678 				break;
2679 			case CTL_DELAY_TYPE_ONESHOT:
2680 				break;
2681 			default:
2682 				delay_info->status =
2683 					CTL_DELAY_STATUS_INVALID_TYPE;
2684 				break;
2685 			}
2686 
2687 			switch (delay_info->delay_loc) {
2688 			case CTL_DELAY_LOC_DATAMOVE:
2689 				lun->delay_info.datamove_type =
2690 					delay_info->delay_type;
2691 				lun->delay_info.datamove_delay =
2692 					delay_info->delay_secs;
2693 				break;
2694 			case CTL_DELAY_LOC_DONE:
2695 				lun->delay_info.done_type =
2696 					delay_info->delay_type;
2697 				lun->delay_info.done_delay =
2698 					delay_info->delay_secs;
2699 				break;
2700 			default:
2701 				delay_info->status =
2702 					CTL_DELAY_STATUS_INVALID_LOC;
2703 				break;
2704 			}
2705 		}
2706 
2707 		mtx_unlock(&softc->ctl_lock);
2708 #else
2709 		delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2710 #endif /* CTL_IO_DELAY */
2711 		break;
2712 	}
2713 	case CTL_REALSYNC_SET: {
2714 		int *syncstate;
2715 
2716 		syncstate = (int *)addr;
2717 
2718 		mtx_lock(&softc->ctl_lock);
2719 		switch (*syncstate) {
2720 		case 0:
2721 			softc->flags &= ~CTL_FLAG_REAL_SYNC;
2722 			break;
2723 		case 1:
2724 			softc->flags |= CTL_FLAG_REAL_SYNC;
2725 			break;
2726 		default:
2727 			retval = -EINVAL;
2728 			break;
2729 		}
2730 		mtx_unlock(&softc->ctl_lock);
2731 		break;
2732 	}
2733 	case CTL_REALSYNC_GET: {
2734 		int *syncstate;
2735 
2736 		syncstate = (int*)addr;
2737 
2738 		mtx_lock(&softc->ctl_lock);
2739 		if (softc->flags & CTL_FLAG_REAL_SYNC)
2740 			*syncstate = 1;
2741 		else
2742 			*syncstate = 0;
2743 		mtx_unlock(&softc->ctl_lock);
2744 
2745 		break;
2746 	}
2747 	case CTL_SETSYNC:
2748 	case CTL_GETSYNC: {
2749 		struct ctl_sync_info *sync_info;
2750 		struct ctl_lun *lun;
2751 
2752 		sync_info = (struct ctl_sync_info *)addr;
2753 
2754 		mtx_lock(&softc->ctl_lock);
2755 		lun = softc->ctl_luns[sync_info->lun_id];
2756 		if (lun == NULL) {
2757 			mtx_unlock(&softc->ctl_lock);
2758 			sync_info->status = CTL_GS_SYNC_NO_LUN;
2759 		}
2760 		/*
2761 		 * Get or set the sync interval.  We're not bounds checking
2762 		 * in the set case, hopefully the user won't do something
2763 		 * silly.
2764 		 */
2765 		if (cmd == CTL_GETSYNC)
2766 			sync_info->sync_interval = lun->sync_interval;
2767 		else
2768 			lun->sync_interval = sync_info->sync_interval;
2769 
2770 		mtx_unlock(&softc->ctl_lock);
2771 
2772 		sync_info->status = CTL_GS_SYNC_OK;
2773 
2774 		break;
2775 	}
2776 	case CTL_GETSTATS: {
2777 		struct ctl_stats *stats;
2778 		struct ctl_lun *lun;
2779 		int i;
2780 
2781 		stats = (struct ctl_stats *)addr;
2782 
2783 		if ((sizeof(struct ctl_lun_io_stats) * softc->num_luns) >
2784 		     stats->alloc_len) {
2785 			stats->status = CTL_SS_NEED_MORE_SPACE;
2786 			stats->num_luns = softc->num_luns;
2787 			break;
2788 		}
2789 		/*
2790 		 * XXX KDM no locking here.  If the LUN list changes,
2791 		 * things can blow up.
2792 		 */
2793 		for (i = 0, lun = STAILQ_FIRST(&softc->lun_list); lun != NULL;
2794 		     i++, lun = STAILQ_NEXT(lun, links)) {
2795 			retval = copyout(&lun->stats, &stats->lun_stats[i],
2796 					 sizeof(lun->stats));
2797 			if (retval != 0)
2798 				break;
2799 		}
2800 		stats->num_luns = softc->num_luns;
2801 		stats->fill_len = sizeof(struct ctl_lun_io_stats) *
2802 				 softc->num_luns;
2803 		stats->status = CTL_SS_OK;
2804 #ifdef CTL_TIME_IO
2805 		stats->flags = CTL_STATS_FLAG_TIME_VALID;
2806 #else
2807 		stats->flags = CTL_STATS_FLAG_NONE;
2808 #endif
2809 		getnanouptime(&stats->timestamp);
2810 		break;
2811 	}
2812 	case CTL_ERROR_INJECT: {
2813 		struct ctl_error_desc *err_desc, *new_err_desc;
2814 		struct ctl_lun *lun;
2815 
2816 		err_desc = (struct ctl_error_desc *)addr;
2817 
2818 		new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2819 				      M_WAITOK | M_ZERO);
2820 		bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2821 
2822 		mtx_lock(&softc->ctl_lock);
2823 		lun = softc->ctl_luns[err_desc->lun_id];
2824 		if (lun == NULL) {
2825 			mtx_unlock(&softc->ctl_lock);
2826 			printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
2827 			       __func__, (uintmax_t)err_desc->lun_id);
2828 			retval = EINVAL;
2829 			break;
2830 		}
2831 
2832 		/*
2833 		 * We could do some checking here to verify the validity
2834 		 * of the request, but given the complexity of error
2835 		 * injection requests, the checking logic would be fairly
2836 		 * complex.
2837 		 *
2838 		 * For now, if the request is invalid, it just won't get
2839 		 * executed and might get deleted.
2840 		 */
2841 		STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
2842 
2843 		/*
2844 		 * XXX KDM check to make sure the serial number is unique,
2845 		 * in case we somehow manage to wrap.  That shouldn't
2846 		 * happen for a very long time, but it's the right thing to
2847 		 * do.
2848 		 */
2849 		new_err_desc->serial = lun->error_serial;
2850 		err_desc->serial = lun->error_serial;
2851 		lun->error_serial++;
2852 
2853 		mtx_unlock(&softc->ctl_lock);
2854 		break;
2855 	}
2856 	case CTL_ERROR_INJECT_DELETE: {
2857 		struct ctl_error_desc *delete_desc, *desc, *desc2;
2858 		struct ctl_lun *lun;
2859 		int delete_done;
2860 
2861 		delete_desc = (struct ctl_error_desc *)addr;
2862 		delete_done = 0;
2863 
2864 		mtx_lock(&softc->ctl_lock);
2865 		lun = softc->ctl_luns[delete_desc->lun_id];
2866 		if (lun == NULL) {
2867 			mtx_unlock(&softc->ctl_lock);
2868 			printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
2869 			       __func__, (uintmax_t)delete_desc->lun_id);
2870 			retval = EINVAL;
2871 			break;
2872 		}
2873 		STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
2874 			if (desc->serial != delete_desc->serial)
2875 				continue;
2876 
2877 			STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
2878 				      links);
2879 			free(desc, M_CTL);
2880 			delete_done = 1;
2881 		}
2882 		mtx_unlock(&softc->ctl_lock);
2883 		if (delete_done == 0) {
2884 			printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
2885 			       "error serial %ju on LUN %u\n", __func__,
2886 			       delete_desc->serial, delete_desc->lun_id);
2887 			retval = EINVAL;
2888 			break;
2889 		}
2890 		break;
2891 	}
2892 	case CTL_DUMP_STRUCTS: {
2893 		int i, j, k;
2894 		struct ctl_frontend *fe;
2895 
2896 		printf("CTL IID to WWPN map start:\n");
2897 		for (i = 0; i < CTL_MAX_PORTS; i++) {
2898 			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
2899 				if (softc->wwpn_iid[i][j].in_use == 0)
2900 					continue;
2901 
2902 				printf("port %d iid %u WWPN %#jx\n",
2903 				       softc->wwpn_iid[i][j].port,
2904 				       softc->wwpn_iid[i][j].iid,
2905 				       (uintmax_t)softc->wwpn_iid[i][j].wwpn);
2906 			}
2907 		}
2908 		printf("CTL IID to WWPN map end\n");
2909 		printf("CTL Persistent Reservation information start:\n");
2910 		for (i = 0; i < CTL_MAX_LUNS; i++) {
2911 			struct ctl_lun *lun;
2912 
2913 			lun = softc->ctl_luns[i];
2914 
2915 			if ((lun == NULL)
2916 			 || ((lun->flags & CTL_LUN_DISABLED) != 0))
2917 				continue;
2918 
2919 			for (j = 0; j < (CTL_MAX_PORTS * 2); j++) {
2920 				for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
2921 					if (lun->per_res[j+k].registered == 0)
2922 						continue;
2923 					printf("LUN %d port %d iid %d key "
2924 					       "%#jx\n", i, j, k,
2925 					       (uintmax_t)scsi_8btou64(
2926 					       lun->per_res[j+k].res_key.key));
2927 				}
2928 			}
2929 		}
2930 		printf("CTL Persistent Reservation information end\n");
2931 		printf("CTL Frontends:\n");
2932 		/*
2933 		 * XXX KDM calling this without a lock.  We'd likely want
2934 		 * to drop the lock before calling the frontend's dump
2935 		 * routine anyway.
2936 		 */
2937 		STAILQ_FOREACH(fe, &softc->fe_list, links) {
2938 			printf("Frontend %s Type %u pport %d vport %d WWNN "
2939 			       "%#jx WWPN %#jx\n", fe->port_name, fe->port_type,
2940 			       fe->physical_port, fe->virtual_port,
2941 			       (uintmax_t)fe->wwnn, (uintmax_t)fe->wwpn);
2942 
2943 			/*
2944 			 * Frontends are not required to support the dump
2945 			 * routine.
2946 			 */
2947 			if (fe->fe_dump == NULL)
2948 				continue;
2949 
2950 			fe->fe_dump();
2951 		}
2952 		printf("CTL Frontend information end\n");
2953 		break;
2954 	}
2955 	case CTL_LUN_REQ: {
2956 		struct ctl_lun_req *lun_req;
2957 		struct ctl_backend_driver *backend;
2958 
2959 		lun_req = (struct ctl_lun_req *)addr;
2960 
2961 		backend = ctl_backend_find(lun_req->backend);
2962 		if (backend == NULL) {
2963 			lun_req->status = CTL_LUN_ERROR;
2964 			snprintf(lun_req->error_str,
2965 				 sizeof(lun_req->error_str),
2966 				 "Backend \"%s\" not found.",
2967 				 lun_req->backend);
2968 			break;
2969 		}
2970 		if (lun_req->num_be_args > 0) {
2971 			lun_req->kern_be_args = ctl_copyin_args(
2972 				lun_req->num_be_args,
2973 				lun_req->be_args,
2974 				lun_req->error_str,
2975 				sizeof(lun_req->error_str));
2976 			if (lun_req->kern_be_args == NULL) {
2977 				lun_req->status = CTL_LUN_ERROR;
2978 				break;
2979 			}
2980 		}
2981 
2982 		retval = backend->ioctl(dev, cmd, addr, flag, td);
2983 
2984 		if (lun_req->num_be_args > 0) {
2985 			ctl_free_args(lun_req->num_be_args,
2986 				      lun_req->kern_be_args);
2987 		}
2988 		break;
2989 	}
2990 	case CTL_LUN_LIST: {
2991 		struct sbuf *sb;
2992 		struct ctl_lun *lun;
2993 		struct ctl_lun_list *list;
2994 		struct ctl_be_lun_option *opt;
2995 
2996 		list = (struct ctl_lun_list *)addr;
2997 
2998 		/*
2999 		 * Allocate a fixed length sbuf here, based on the length
3000 		 * of the user's buffer.  We could allocate an auto-extending
3001 		 * buffer, and then tell the user how much larger our
3002 		 * amount of data is than his buffer, but that presents
3003 		 * some problems:
3004 		 *
3005 		 * 1.  The sbuf(9) routines use a blocking malloc, and so
3006 		 *     we can't hold a lock while calling them with an
3007 		 *     auto-extending buffer.
3008  		 *
3009 		 * 2.  There is not currently a LUN reference counting
3010 		 *     mechanism, outside of outstanding transactions on
3011 		 *     the LUN's OOA queue.  So a LUN could go away on us
3012 		 *     while we're getting the LUN number, backend-specific
3013 		 *     information, etc.  Thus, given the way things
3014 		 *     currently work, we need to hold the CTL lock while
3015 		 *     grabbing LUN information.
3016 		 *
3017 		 * So, from the user's standpoint, the best thing to do is
3018 		 * allocate what he thinks is a reasonable buffer length,
3019 		 * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
3020 		 * double the buffer length and try again.  (And repeat
3021 		 * that until he succeeds.)
3022 		 */
3023 		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3024 		if (sb == NULL) {
3025 			list->status = CTL_LUN_LIST_ERROR;
3026 			snprintf(list->error_str, sizeof(list->error_str),
3027 				 "Unable to allocate %d bytes for LUN list",
3028 				 list->alloc_len);
3029 			break;
3030 		}
3031 
3032 		sbuf_printf(sb, "<ctllunlist>\n");
3033 
3034 		mtx_lock(&softc->ctl_lock);
3035 
3036 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
3037 			retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3038 					     (uintmax_t)lun->lun);
3039 
3040 			/*
3041 			 * Bail out as soon as we see that we've overfilled
3042 			 * the buffer.
3043 			 */
3044 			if (retval != 0)
3045 				break;
3046 
3047 			retval = sbuf_printf(sb, "<backend_type>%s"
3048 					     "</backend_type>\n",
3049 					     (lun->backend == NULL) ?  "none" :
3050 					     lun->backend->name);
3051 
3052 			if (retval != 0)
3053 				break;
3054 
3055 			retval = sbuf_printf(sb, "<lun_type>%d</lun_type>\n",
3056 					     lun->be_lun->lun_type);
3057 
3058 			if (retval != 0)
3059 				break;
3060 
3061 			if (lun->backend == NULL) {
3062 				retval = sbuf_printf(sb, "</lun>\n");
3063 				if (retval != 0)
3064 					break;
3065 				continue;
3066 			}
3067 
3068 			retval = sbuf_printf(sb, "<size>%ju</size>\n",
3069 					     (lun->be_lun->maxlba > 0) ?
3070 					     lun->be_lun->maxlba + 1 : 0);
3071 
3072 			if (retval != 0)
3073 				break;
3074 
3075 			retval = sbuf_printf(sb, "<blocksize>%u</blocksize>\n",
3076 					     lun->be_lun->blocksize);
3077 
3078 			if (retval != 0)
3079 				break;
3080 
3081 			retval = sbuf_printf(sb, "<serial_number>");
3082 
3083 			if (retval != 0)
3084 				break;
3085 
3086 			retval = ctl_sbuf_printf_esc(sb,
3087 						     lun->be_lun->serial_num);
3088 
3089 			if (retval != 0)
3090 				break;
3091 
3092 			retval = sbuf_printf(sb, "</serial_number>\n");
3093 
3094 			if (retval != 0)
3095 				break;
3096 
3097 			retval = sbuf_printf(sb, "<device_id>");
3098 
3099 			if (retval != 0)
3100 				break;
3101 
3102 			retval = ctl_sbuf_printf_esc(sb,lun->be_lun->device_id);
3103 
3104 			if (retval != 0)
3105 				break;
3106 
3107 			retval = sbuf_printf(sb, "</device_id>\n");
3108 
3109 			if (retval != 0)
3110 				break;
3111 
3112 			if (lun->backend->lun_info != NULL) {
3113 				retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
3114 				if (retval != 0)
3115 					break;
3116 			}
3117 			STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
3118 				retval = sbuf_printf(sb, "<%s>%s</%s>", opt->name, opt->value, opt->name);
3119 				if (retval != 0)
3120 					break;
3121 			}
3122 
3123 			retval = sbuf_printf(sb, "</lun>\n");
3124 
3125 			if (retval != 0)
3126 				break;
3127 		}
3128 		mtx_unlock(&softc->ctl_lock);
3129 
3130 		if ((retval != 0)
3131 		 || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3132 			retval = 0;
3133 			sbuf_delete(sb);
3134 			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3135 			snprintf(list->error_str, sizeof(list->error_str),
3136 				 "Out of space, %d bytes is too small",
3137 				 list->alloc_len);
3138 			break;
3139 		}
3140 
3141 		sbuf_finish(sb);
3142 
3143 		retval = copyout(sbuf_data(sb), list->lun_xml,
3144 				 sbuf_len(sb) + 1);
3145 
3146 		list->fill_len = sbuf_len(sb) + 1;
3147 		list->status = CTL_LUN_LIST_OK;
3148 		sbuf_delete(sb);
3149 		break;
3150 	}
3151 	default: {
3152 		/* XXX KDM should we fix this? */
3153 #if 0
3154 		struct ctl_backend_driver *backend;
3155 		unsigned int type;
3156 		int found;
3157 
3158 		found = 0;
3159 
3160 		/*
3161 		 * We encode the backend type as the ioctl type for backend
3162 		 * ioctls.  So parse it out here, and then search for a
3163 		 * backend of this type.
3164 		 */
3165 		type = _IOC_TYPE(cmd);
3166 
3167 		STAILQ_FOREACH(backend, &softc->be_list, links) {
3168 			if (backend->type == type) {
3169 				found = 1;
3170 				break;
3171 			}
3172 		}
3173 		if (found == 0) {
3174 			printf("ctl: unknown ioctl command %#lx or backend "
3175 			       "%d\n", cmd, type);
3176 			retval = -EINVAL;
3177 			break;
3178 		}
3179 		retval = backend->ioctl(dev, cmd, addr, flag, td);
3180 #endif
3181 		retval = ENOTTY;
3182 		break;
3183 	}
3184 	}
3185 	return (retval);
3186 }
3187 
3188 uint32_t
3189 ctl_get_initindex(struct ctl_nexus *nexus)
3190 {
3191 	if (nexus->targ_port < CTL_MAX_PORTS)
3192 		return (nexus->initid.id +
3193 			(nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3194 	else
3195 		return (nexus->initid.id +
3196 		       ((nexus->targ_port - CTL_MAX_PORTS) *
3197 			CTL_MAX_INIT_PER_PORT));
3198 }
3199 
3200 uint32_t
3201 ctl_get_resindex(struct ctl_nexus *nexus)
3202 {
3203 	return (nexus->initid.id + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3204 }
3205 
3206 uint32_t
3207 ctl_port_idx(int port_num)
3208 {
3209 	if (port_num < CTL_MAX_PORTS)
3210 		return(port_num);
3211 	else
3212 		return(port_num - CTL_MAX_PORTS);
3213 }
3214 
3215 /*
3216  * Note:  This only works for bitmask sizes that are at least 32 bits, and
3217  * that are a power of 2.
3218  */
3219 int
3220 ctl_ffz(uint32_t *mask, uint32_t size)
3221 {
3222 	uint32_t num_chunks, num_pieces;
3223 	int i, j;
3224 
3225 	num_chunks = (size >> 5);
3226 	if (num_chunks == 0)
3227 		num_chunks++;
3228 	num_pieces = ctl_min((sizeof(uint32_t) * 8), size);
3229 
3230 	for (i = 0; i < num_chunks; i++) {
3231 		for (j = 0; j < num_pieces; j++) {
3232 			if ((mask[i] & (1 << j)) == 0)
3233 				return ((i << 5) + j);
3234 		}
3235 	}
3236 
3237 	return (-1);
3238 }
3239 
3240 int
3241 ctl_set_mask(uint32_t *mask, uint32_t bit)
3242 {
3243 	uint32_t chunk, piece;
3244 
3245 	chunk = bit >> 5;
3246 	piece = bit % (sizeof(uint32_t) * 8);
3247 
3248 	if ((mask[chunk] & (1 << piece)) != 0)
3249 		return (-1);
3250 	else
3251 		mask[chunk] |= (1 << piece);
3252 
3253 	return (0);
3254 }
3255 
3256 int
3257 ctl_clear_mask(uint32_t *mask, uint32_t bit)
3258 {
3259 	uint32_t chunk, piece;
3260 
3261 	chunk = bit >> 5;
3262 	piece = bit % (sizeof(uint32_t) * 8);
3263 
3264 	if ((mask[chunk] & (1 << piece)) == 0)
3265 		return (-1);
3266 	else
3267 		mask[chunk] &= ~(1 << piece);
3268 
3269 	return (0);
3270 }
3271 
3272 int
3273 ctl_is_set(uint32_t *mask, uint32_t bit)
3274 {
3275 	uint32_t chunk, piece;
3276 
3277 	chunk = bit >> 5;
3278 	piece = bit % (sizeof(uint32_t) * 8);
3279 
3280 	if ((mask[chunk] & (1 << piece)) == 0)
3281 		return (0);
3282 	else
3283 		return (1);
3284 }
3285 
3286 #ifdef unused
3287 /*
3288  * The bus, target and lun are optional, they can be filled in later.
3289  * can_wait is used to determine whether we can wait on the malloc or not.
3290  */
3291 union ctl_io*
3292 ctl_malloc_io(ctl_io_type io_type, uint32_t targ_port, uint32_t targ_target,
3293 	      uint32_t targ_lun, int can_wait)
3294 {
3295 	union ctl_io *io;
3296 
3297 	if (can_wait)
3298 		io = (union ctl_io *)malloc(sizeof(*io), M_CTL, M_WAITOK);
3299 	else
3300 		io = (union ctl_io *)malloc(sizeof(*io), M_CTL, M_NOWAIT);
3301 
3302 	if (io != NULL) {
3303 		io->io_hdr.io_type = io_type;
3304 		io->io_hdr.targ_port = targ_port;
3305 		/*
3306 		 * XXX KDM this needs to change/go away.  We need to move
3307 		 * to a preallocated pool of ctl_scsiio structures.
3308 		 */
3309 		io->io_hdr.nexus.targ_target.id = targ_target;
3310 		io->io_hdr.nexus.targ_lun = targ_lun;
3311 	}
3312 
3313 	return (io);
3314 }
3315 
3316 void
3317 ctl_kfree_io(union ctl_io *io)
3318 {
3319 	free(io, M_CTL);
3320 }
3321 #endif /* unused */
3322 
3323 /*
3324  * ctl_softc, pool_type, total_ctl_io are passed in.
3325  * npool is passed out.
3326  */
3327 int
3328 ctl_pool_create(struct ctl_softc *ctl_softc, ctl_pool_type pool_type,
3329 		uint32_t total_ctl_io, struct ctl_io_pool **npool)
3330 {
3331 	uint32_t i;
3332 	union ctl_io *cur_io, *next_io;
3333 	struct ctl_io_pool *pool;
3334 	int retval;
3335 
3336 	retval = 0;
3337 
3338 	pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3339 					    M_NOWAIT | M_ZERO);
3340 	if (pool == NULL) {
3341 		retval = -ENOMEM;
3342 		goto bailout;
3343 	}
3344 
3345 	pool->type = pool_type;
3346 	pool->ctl_softc = ctl_softc;
3347 
3348 	mtx_lock(&ctl_softc->ctl_lock);
3349 	pool->id = ctl_softc->cur_pool_id++;
3350 	mtx_unlock(&ctl_softc->ctl_lock);
3351 
3352 	pool->flags = CTL_POOL_FLAG_NONE;
3353 	STAILQ_INIT(&pool->free_queue);
3354 
3355 	/*
3356 	 * XXX KDM other options here:
3357 	 * - allocate a page at a time
3358 	 * - allocate one big chunk of memory.
3359 	 * Page allocation might work well, but would take a little more
3360 	 * tracking.
3361 	 */
3362 	for (i = 0; i < total_ctl_io; i++) {
3363 		cur_io = (union ctl_io *)malloc(sizeof(*cur_io), M_CTL,
3364 						M_NOWAIT);
3365 		if (cur_io == NULL) {
3366 			retval = ENOMEM;
3367 			break;
3368 		}
3369 		cur_io->io_hdr.pool = pool;
3370 		STAILQ_INSERT_TAIL(&pool->free_queue, &cur_io->io_hdr, links);
3371 		pool->total_ctl_io++;
3372 		pool->free_ctl_io++;
3373 	}
3374 
3375 	if (retval != 0) {
3376 		for (cur_io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue);
3377 		     cur_io != NULL; cur_io = next_io) {
3378 			next_io = (union ctl_io *)STAILQ_NEXT(&cur_io->io_hdr,
3379 							      links);
3380 			STAILQ_REMOVE(&pool->free_queue, &cur_io->io_hdr,
3381 				      ctl_io_hdr, links);
3382 			free(cur_io, M_CTL);
3383 		}
3384 
3385 		free(pool, M_CTL);
3386 		goto bailout;
3387 	}
3388 	mtx_lock(&ctl_softc->ctl_lock);
3389 	ctl_softc->num_pools++;
3390 	STAILQ_INSERT_TAIL(&ctl_softc->io_pools, pool, links);
3391 	/*
3392 	 * Increment our usage count if this is an external consumer, so we
3393 	 * can't get unloaded until the external consumer (most likely a
3394 	 * FETD) unloads and frees his pool.
3395 	 *
3396 	 * XXX KDM will this increment the caller's module use count, or
3397 	 * mine?
3398 	 */
3399 #if 0
3400 	if ((pool_type != CTL_POOL_EMERGENCY)
3401 	 && (pool_type != CTL_POOL_INTERNAL)
3402 	 && (pool_type != CTL_POOL_IOCTL)
3403 	 && (pool_type != CTL_POOL_4OTHERSC))
3404 		MOD_INC_USE_COUNT;
3405 #endif
3406 
3407 	mtx_unlock(&ctl_softc->ctl_lock);
3408 
3409 	*npool = pool;
3410 
3411 bailout:
3412 
3413 	return (retval);
3414 }
3415 
3416 int
3417 ctl_pool_acquire(struct ctl_io_pool *pool)
3418 {
3419 
3420 	mtx_assert(&control_softc->ctl_lock, MA_OWNED);
3421 
3422 	if (pool == NULL)
3423 		return (-EINVAL);
3424 
3425 	if (pool->flags & CTL_POOL_FLAG_INVALID)
3426 		return (-EINVAL);
3427 
3428 	pool->refcount++;
3429 
3430 	return (0);
3431 }
3432 
3433 int
3434 ctl_pool_invalidate(struct ctl_io_pool *pool)
3435 {
3436 
3437 	mtx_assert(&control_softc->ctl_lock, MA_OWNED);
3438 
3439 	if (pool == NULL)
3440 		return (-EINVAL);
3441 
3442 	pool->flags |= CTL_POOL_FLAG_INVALID;
3443 
3444 	return (0);
3445 }
3446 
3447 int
3448 ctl_pool_release(struct ctl_io_pool *pool)
3449 {
3450 
3451 	mtx_assert(&control_softc->ctl_lock, MA_OWNED);
3452 
3453 	if (pool == NULL)
3454 		return (-EINVAL);
3455 
3456 	if ((--pool->refcount == 0)
3457 	 && (pool->flags & CTL_POOL_FLAG_INVALID)) {
3458 		ctl_pool_free(pool->ctl_softc, pool);
3459 	}
3460 
3461 	return (0);
3462 }
3463 
3464 void
3465 ctl_pool_free(struct ctl_softc *ctl_softc, struct ctl_io_pool *pool)
3466 {
3467 	union ctl_io *cur_io, *next_io;
3468 
3469 	mtx_assert(&ctl_softc->ctl_lock, MA_OWNED);
3470 
3471 	for (cur_io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue);
3472 	     cur_io != NULL; cur_io = next_io) {
3473 		next_io = (union ctl_io *)STAILQ_NEXT(&cur_io->io_hdr,
3474 						      links);
3475 		STAILQ_REMOVE(&pool->free_queue, &cur_io->io_hdr, ctl_io_hdr,
3476 			      links);
3477 		free(cur_io, M_CTL);
3478 	}
3479 
3480 	STAILQ_REMOVE(&ctl_softc->io_pools, pool, ctl_io_pool, links);
3481 	ctl_softc->num_pools--;
3482 
3483 	/*
3484 	 * XXX KDM will this decrement the caller's usage count or mine?
3485 	 */
3486 #if 0
3487 	if ((pool->type != CTL_POOL_EMERGENCY)
3488 	 && (pool->type != CTL_POOL_INTERNAL)
3489 	 && (pool->type != CTL_POOL_IOCTL))
3490 		MOD_DEC_USE_COUNT;
3491 #endif
3492 
3493 	free(pool, M_CTL);
3494 }
3495 
3496 /*
3497  * This routine does not block (except for spinlocks of course).
3498  * It tries to allocate a ctl_io union from the caller's pool as quickly as
3499  * possible.
3500  */
3501 union ctl_io *
3502 ctl_alloc_io(void *pool_ref)
3503 {
3504 	union ctl_io *io;
3505 	struct ctl_softc *ctl_softc;
3506 	struct ctl_io_pool *pool, *npool;
3507 	struct ctl_io_pool *emergency_pool;
3508 
3509 	pool = (struct ctl_io_pool *)pool_ref;
3510 
3511 	if (pool == NULL) {
3512 		printf("%s: pool is NULL\n", __func__);
3513 		return (NULL);
3514 	}
3515 
3516 	emergency_pool = NULL;
3517 
3518 	ctl_softc = pool->ctl_softc;
3519 
3520 	mtx_lock(&ctl_softc->ctl_lock);
3521 	/*
3522 	 * First, try to get the io structure from the user's pool.
3523 	 */
3524 	if (ctl_pool_acquire(pool) == 0) {
3525 		io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue);
3526 		if (io != NULL) {
3527 			STAILQ_REMOVE_HEAD(&pool->free_queue, links);
3528 			pool->total_allocated++;
3529 			pool->free_ctl_io--;
3530 			mtx_unlock(&ctl_softc->ctl_lock);
3531 			return (io);
3532 		} else
3533 			ctl_pool_release(pool);
3534 	}
3535 	/*
3536 	 * If he doesn't have any io structures left, search for an
3537 	 * emergency pool and grab one from there.
3538 	 */
3539 	STAILQ_FOREACH(npool, &ctl_softc->io_pools, links) {
3540 		if (npool->type != CTL_POOL_EMERGENCY)
3541 			continue;
3542 
3543 		if (ctl_pool_acquire(npool) != 0)
3544 			continue;
3545 
3546 		emergency_pool = npool;
3547 
3548 		io = (union ctl_io *)STAILQ_FIRST(&npool->free_queue);
3549 		if (io != NULL) {
3550 			STAILQ_REMOVE_HEAD(&npool->free_queue, links);
3551 			npool->total_allocated++;
3552 			npool->free_ctl_io--;
3553 			mtx_unlock(&ctl_softc->ctl_lock);
3554 			return (io);
3555 		} else
3556 			ctl_pool_release(npool);
3557 	}
3558 
3559 	/* Drop the spinlock before we malloc */
3560 	mtx_unlock(&ctl_softc->ctl_lock);
3561 
3562 	/*
3563 	 * The emergency pool (if it exists) didn't have one, so try an
3564 	 * atomic (i.e. nonblocking) malloc and see if we get lucky.
3565 	 */
3566 	io = (union ctl_io *)malloc(sizeof(*io), M_CTL, M_NOWAIT);
3567 	if (io != NULL) {
3568 		/*
3569 		 * If the emergency pool exists but is empty, add this
3570 		 * ctl_io to its list when it gets freed.
3571 		 */
3572 		if (emergency_pool != NULL) {
3573 			mtx_lock(&ctl_softc->ctl_lock);
3574 			if (ctl_pool_acquire(emergency_pool) == 0) {
3575 				io->io_hdr.pool = emergency_pool;
3576 				emergency_pool->total_ctl_io++;
3577 				/*
3578 				 * Need to bump this, otherwise
3579 				 * total_allocated and total_freed won't
3580 				 * match when we no longer have anything
3581 				 * outstanding.
3582 				 */
3583 				emergency_pool->total_allocated++;
3584 			}
3585 			mtx_unlock(&ctl_softc->ctl_lock);
3586 		} else
3587 			io->io_hdr.pool = NULL;
3588 	}
3589 
3590 	return (io);
3591 }
3592 
3593 static void
3594 ctl_free_io_internal(union ctl_io *io, int have_lock)
3595 {
3596 	if (io == NULL)
3597 		return;
3598 
3599 	/*
3600 	 * If this ctl_io has a pool, return it to that pool.
3601 	 */
3602 	if (io->io_hdr.pool != NULL) {
3603 		struct ctl_io_pool *pool;
3604 #if 0
3605 		struct ctl_softc *ctl_softc;
3606 		union ctl_io *tmp_io;
3607 		unsigned long xflags;
3608 		int i;
3609 
3610 		ctl_softc = control_softc;
3611 #endif
3612 
3613 		pool = (struct ctl_io_pool *)io->io_hdr.pool;
3614 
3615 		if (have_lock == 0)
3616 			mtx_lock(&pool->ctl_softc->ctl_lock);
3617 #if 0
3618 		save_flags(xflags);
3619 
3620 		for (i = 0, tmp_io = (union ctl_io *)STAILQ_FIRST(
3621 		     &ctl_softc->task_queue); tmp_io != NULL; i++,
3622 		     tmp_io = (union ctl_io *)STAILQ_NEXT(&tmp_io->io_hdr,
3623 		     links)) {
3624 			if (tmp_io == io) {
3625 				printf("%s: %p is still on the task queue!\n",
3626 				       __func__, tmp_io);
3627 				printf("%s: (%d): type %d "
3628 				       "msg %d cdb %x iptl: "
3629 				       "%d:%d:%d:%d tag 0x%04x "
3630 				       "flg %#lx\n",
3631 					__func__, i,
3632 					tmp_io->io_hdr.io_type,
3633 					tmp_io->io_hdr.msg_type,
3634 					tmp_io->scsiio.cdb[0],
3635 					tmp_io->io_hdr.nexus.initid.id,
3636 					tmp_io->io_hdr.nexus.targ_port,
3637 					tmp_io->io_hdr.nexus.targ_target.id,
3638 					tmp_io->io_hdr.nexus.targ_lun,
3639 					(tmp_io->io_hdr.io_type ==
3640 					CTL_IO_TASK) ?
3641 					tmp_io->taskio.tag_num :
3642 					tmp_io->scsiio.tag_num,
3643 					xflags);
3644 				panic("I/O still on the task queue!");
3645 			}
3646 		}
3647 #endif
3648 		io->io_hdr.io_type = 0xff;
3649 		STAILQ_INSERT_TAIL(&pool->free_queue, &io->io_hdr, links);
3650 		pool->total_freed++;
3651 		pool->free_ctl_io++;
3652 		ctl_pool_release(pool);
3653 		if (have_lock == 0)
3654 			mtx_unlock(&pool->ctl_softc->ctl_lock);
3655 	} else {
3656 		/*
3657 		 * Otherwise, just free it.  We probably malloced it and
3658 		 * the emergency pool wasn't available.
3659 		 */
3660 		free(io, M_CTL);
3661 	}
3662 
3663 }
3664 
3665 void
3666 ctl_free_io(union ctl_io *io)
3667 {
3668 	ctl_free_io_internal(io, /*have_lock*/ 0);
3669 }
3670 
3671 void
3672 ctl_zero_io(union ctl_io *io)
3673 {
3674 	void *pool_ref;
3675 
3676 	if (io == NULL)
3677 		return;
3678 
3679 	/*
3680 	 * May need to preserve linked list pointers at some point too.
3681 	 */
3682 	pool_ref = io->io_hdr.pool;
3683 
3684 	memset(io, 0, sizeof(*io));
3685 
3686 	io->io_hdr.pool = pool_ref;
3687 }
3688 
3689 /*
3690  * This routine is currently used for internal copies of ctl_ios that need
3691  * to persist for some reason after we've already returned status to the
3692  * FETD.  (Thus the flag set.)
3693  *
3694  * XXX XXX
3695  * Note that this makes a blind copy of all fields in the ctl_io, except
3696  * for the pool reference.  This includes any memory that has been
3697  * allocated!  That memory will no longer be valid after done has been
3698  * called, so this would be VERY DANGEROUS for command that actually does
3699  * any reads or writes.  Right now (11/7/2005), this is only used for immediate
3700  * start and stop commands, which don't transfer any data, so this is not a
3701  * problem.  If it is used for anything else, the caller would also need to
3702  * allocate data buffer space and this routine would need to be modified to
3703  * copy the data buffer(s) as well.
3704  */
3705 void
3706 ctl_copy_io(union ctl_io *src, union ctl_io *dest)
3707 {
3708 	void *pool_ref;
3709 
3710 	if ((src == NULL)
3711 	 || (dest == NULL))
3712 		return;
3713 
3714 	/*
3715 	 * May need to preserve linked list pointers at some point too.
3716 	 */
3717 	pool_ref = dest->io_hdr.pool;
3718 
3719 	memcpy(dest, src, ctl_min(sizeof(*src), sizeof(*dest)));
3720 
3721 	dest->io_hdr.pool = pool_ref;
3722 	/*
3723 	 * We need to know that this is an internal copy, and doesn't need
3724 	 * to get passed back to the FETD that allocated it.
3725 	 */
3726 	dest->io_hdr.flags |= CTL_FLAG_INT_COPY;
3727 }
3728 
3729 #ifdef NEEDTOPORT
3730 static void
3731 ctl_update_power_subpage(struct copan_power_subpage *page)
3732 {
3733 	int num_luns, num_partitions, config_type;
3734 	struct ctl_softc *softc;
3735 	cs_BOOL_t aor_present, shelf_50pct_power;
3736 	cs_raidset_personality_t rs_type;
3737 	int max_active_luns;
3738 
3739 	softc = control_softc;
3740 
3741 	/* subtract out the processor LUN */
3742 	num_luns = softc->num_luns - 1;
3743 	/*
3744 	 * Default to 7 LUNs active, which was the only number we allowed
3745 	 * in the past.
3746 	 */
3747 	max_active_luns = 7;
3748 
3749 	num_partitions = config_GetRsPartitionInfo();
3750 	config_type = config_GetConfigType();
3751 	shelf_50pct_power = config_GetShelfPowerMode();
3752 	aor_present = config_IsAorRsPresent();
3753 
3754 	rs_type = ddb_GetRsRaidType(1);
3755 	if ((rs_type != CS_RAIDSET_PERSONALITY_RAID5)
3756 	 && (rs_type != CS_RAIDSET_PERSONALITY_RAID1)) {
3757 		EPRINT(0, "Unsupported RS type %d!", rs_type);
3758 	}
3759 
3760 
3761 	page->total_luns = num_luns;
3762 
3763 	switch (config_type) {
3764 	case 40:
3765 		/*
3766 		 * In a 40 drive configuration, it doesn't matter what DC
3767 		 * cards we have, whether we have AOR enabled or not,
3768 		 * partitioning or not, or what type of RAIDset we have.
3769 		 * In that scenario, we can power up every LUN we present
3770 		 * to the user.
3771 		 */
3772 		max_active_luns = num_luns;
3773 
3774 		break;
3775 	case 64:
3776 		if (shelf_50pct_power == CS_FALSE) {
3777 			/* 25% power */
3778 			if (aor_present == CS_TRUE) {
3779 				if (rs_type ==
3780 				     CS_RAIDSET_PERSONALITY_RAID5) {
3781 					max_active_luns = 7;
3782 				} else if (rs_type ==
3783 					 CS_RAIDSET_PERSONALITY_RAID1){
3784 					max_active_luns = 14;
3785 				} else {
3786 					/* XXX KDM now what?? */
3787 				}
3788 			} else {
3789 				if (rs_type ==
3790 				     CS_RAIDSET_PERSONALITY_RAID5) {
3791 					max_active_luns = 8;
3792 				} else if (rs_type ==
3793 					 CS_RAIDSET_PERSONALITY_RAID1){
3794 					max_active_luns = 16;
3795 				} else {
3796 					/* XXX KDM now what?? */
3797 				}
3798 			}
3799 		} else {
3800 			/* 50% power */
3801 			/*
3802 			 * With 50% power in a 64 drive configuration, we
3803 			 * can power all LUNs we present.
3804 			 */
3805 			max_active_luns = num_luns;
3806 		}
3807 		break;
3808 	case 112:
3809 		if (shelf_50pct_power == CS_FALSE) {
3810 			/* 25% power */
3811 			if (aor_present == CS_TRUE) {
3812 				if (rs_type ==
3813 				     CS_RAIDSET_PERSONALITY_RAID5) {
3814 					max_active_luns = 7;
3815 				} else if (rs_type ==
3816 					 CS_RAIDSET_PERSONALITY_RAID1){
3817 					max_active_luns = 14;
3818 				} else {
3819 					/* XXX KDM now what?? */
3820 				}
3821 			} else {
3822 				if (rs_type ==
3823 				     CS_RAIDSET_PERSONALITY_RAID5) {
3824 					max_active_luns = 8;
3825 				} else if (rs_type ==
3826 					 CS_RAIDSET_PERSONALITY_RAID1){
3827 					max_active_luns = 16;
3828 				} else {
3829 					/* XXX KDM now what?? */
3830 				}
3831 			}
3832 		} else {
3833 			/* 50% power */
3834 			if (aor_present == CS_TRUE) {
3835 				if (rs_type ==
3836 				     CS_RAIDSET_PERSONALITY_RAID5) {
3837 					max_active_luns = 14;
3838 				} else if (rs_type ==
3839 					 CS_RAIDSET_PERSONALITY_RAID1){
3840 					/*
3841 					 * We're assuming here that disk
3842 					 * caching is enabled, and so we're
3843 					 * able to power up half of each
3844 					 * LUN, and cache all writes.
3845 					 */
3846 					max_active_luns = num_luns;
3847 				} else {
3848 					/* XXX KDM now what?? */
3849 				}
3850 			} else {
3851 				if (rs_type ==
3852 				     CS_RAIDSET_PERSONALITY_RAID5) {
3853 					max_active_luns = 15;
3854 				} else if (rs_type ==
3855 					 CS_RAIDSET_PERSONALITY_RAID1){
3856 					max_active_luns = 30;
3857 				} else {
3858 					/* XXX KDM now what?? */
3859 				}
3860 			}
3861 		}
3862 		break;
3863 	default:
3864 		/*
3865 		 * In this case, we have an unknown configuration, so we
3866 		 * just use the default from above.
3867 		 */
3868 		break;
3869 	}
3870 
3871 	page->max_active_luns = max_active_luns;
3872 #if 0
3873 	printk("%s: total_luns = %d, max_active_luns = %d\n", __func__,
3874 	       page->total_luns, page->max_active_luns);
3875 #endif
3876 }
3877 #endif /* NEEDTOPORT */
3878 
3879 /*
3880  * This routine could be used in the future to load default and/or saved
3881  * mode page parameters for a particuar lun.
3882  */
3883 static int
3884 ctl_init_page_index(struct ctl_lun *lun)
3885 {
3886 	int i;
3887 	struct ctl_page_index *page_index;
3888 	struct ctl_softc *softc;
3889 
3890 	memcpy(&lun->mode_pages.index, page_index_template,
3891 	       sizeof(page_index_template));
3892 
3893 	softc = lun->ctl_softc;
3894 
3895 	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
3896 
3897 		page_index = &lun->mode_pages.index[i];
3898 		/*
3899 		 * If this is a disk-only mode page, there's no point in
3900 		 * setting it up.  For some pages, we have to have some
3901 		 * basic information about the disk in order to calculate the
3902 		 * mode page data.
3903 		 */
3904 		if ((lun->be_lun->lun_type != T_DIRECT)
3905 		 && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
3906 			continue;
3907 
3908 		switch (page_index->page_code & SMPH_PC_MASK) {
3909 		case SMS_FORMAT_DEVICE_PAGE: {
3910 			struct scsi_format_page *format_page;
3911 
3912 			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3913 				panic("subpage is incorrect!");
3914 
3915 			/*
3916 			 * Sectors per track are set above.  Bytes per
3917 			 * sector need to be set here on a per-LUN basis.
3918 			 */
3919 			memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
3920 			       &format_page_default,
3921 			       sizeof(format_page_default));
3922 			memcpy(&lun->mode_pages.format_page[
3923 			       CTL_PAGE_CHANGEABLE], &format_page_changeable,
3924 			       sizeof(format_page_changeable));
3925 			memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
3926 			       &format_page_default,
3927 			       sizeof(format_page_default));
3928 			memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
3929 			       &format_page_default,
3930 			       sizeof(format_page_default));
3931 
3932 			format_page = &lun->mode_pages.format_page[
3933 				CTL_PAGE_CURRENT];
3934 			scsi_ulto2b(lun->be_lun->blocksize,
3935 				    format_page->bytes_per_sector);
3936 
3937 			format_page = &lun->mode_pages.format_page[
3938 				CTL_PAGE_DEFAULT];
3939 			scsi_ulto2b(lun->be_lun->blocksize,
3940 				    format_page->bytes_per_sector);
3941 
3942 			format_page = &lun->mode_pages.format_page[
3943 				CTL_PAGE_SAVED];
3944 			scsi_ulto2b(lun->be_lun->blocksize,
3945 				    format_page->bytes_per_sector);
3946 
3947 			page_index->page_data =
3948 				(uint8_t *)lun->mode_pages.format_page;
3949 			break;
3950 		}
3951 		case SMS_RIGID_DISK_PAGE: {
3952 			struct scsi_rigid_disk_page *rigid_disk_page;
3953 			uint32_t sectors_per_cylinder;
3954 			uint64_t cylinders;
3955 #ifndef	__XSCALE__
3956 			int shift;
3957 #endif /* !__XSCALE__ */
3958 
3959 			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3960 				panic("invalid subpage value %d",
3961 				      page_index->subpage);
3962 
3963 			/*
3964 			 * Rotation rate and sectors per track are set
3965 			 * above.  We calculate the cylinders here based on
3966 			 * capacity.  Due to the number of heads and
3967 			 * sectors per track we're using, smaller arrays
3968 			 * may turn out to have 0 cylinders.  Linux and
3969 			 * FreeBSD don't pay attention to these mode pages
3970 			 * to figure out capacity, but Solaris does.  It
3971 			 * seems to deal with 0 cylinders just fine, and
3972 			 * works out a fake geometry based on the capacity.
3973 			 */
3974 			memcpy(&lun->mode_pages.rigid_disk_page[
3975 			       CTL_PAGE_CURRENT], &rigid_disk_page_default,
3976 			       sizeof(rigid_disk_page_default));
3977 			memcpy(&lun->mode_pages.rigid_disk_page[
3978 			       CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
3979 			       sizeof(rigid_disk_page_changeable));
3980 			memcpy(&lun->mode_pages.rigid_disk_page[
3981 			       CTL_PAGE_DEFAULT], &rigid_disk_page_default,
3982 			       sizeof(rigid_disk_page_default));
3983 			memcpy(&lun->mode_pages.rigid_disk_page[
3984 			       CTL_PAGE_SAVED], &rigid_disk_page_default,
3985 			       sizeof(rigid_disk_page_default));
3986 
3987 			sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
3988 				CTL_DEFAULT_HEADS;
3989 
3990 			/*
3991 			 * The divide method here will be more accurate,
3992 			 * probably, but results in floating point being
3993 			 * used in the kernel on i386 (__udivdi3()).  On the
3994 			 * XScale, though, __udivdi3() is implemented in
3995 			 * software.
3996 			 *
3997 			 * The shift method for cylinder calculation is
3998 			 * accurate if sectors_per_cylinder is a power of
3999 			 * 2.  Otherwise it might be slightly off -- you
4000 			 * might have a bit of a truncation problem.
4001 			 */
4002 #ifdef	__XSCALE__
4003 			cylinders = (lun->be_lun->maxlba + 1) /
4004 				sectors_per_cylinder;
4005 #else
4006 			for (shift = 31; shift > 0; shift--) {
4007 				if (sectors_per_cylinder & (1 << shift))
4008 					break;
4009 			}
4010 			cylinders = (lun->be_lun->maxlba + 1) >> shift;
4011 #endif
4012 
4013 			/*
4014 			 * We've basically got 3 bytes, or 24 bits for the
4015 			 * cylinder size in the mode page.  If we're over,
4016 			 * just round down to 2^24.
4017 			 */
4018 			if (cylinders > 0xffffff)
4019 				cylinders = 0xffffff;
4020 
4021 			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4022 				CTL_PAGE_CURRENT];
4023 			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4024 
4025 			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4026 				CTL_PAGE_DEFAULT];
4027 			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4028 
4029 			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4030 				CTL_PAGE_SAVED];
4031 			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4032 
4033 			page_index->page_data =
4034 				(uint8_t *)lun->mode_pages.rigid_disk_page;
4035 			break;
4036 		}
4037 		case SMS_CACHING_PAGE: {
4038 
4039 			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4040 				panic("invalid subpage value %d",
4041 				      page_index->subpage);
4042 			/*
4043 			 * Defaults should be okay here, no calculations
4044 			 * needed.
4045 			 */
4046 			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4047 			       &caching_page_default,
4048 			       sizeof(caching_page_default));
4049 			memcpy(&lun->mode_pages.caching_page[
4050 			       CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4051 			       sizeof(caching_page_changeable));
4052 			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4053 			       &caching_page_default,
4054 			       sizeof(caching_page_default));
4055 			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4056 			       &caching_page_default,
4057 			       sizeof(caching_page_default));
4058 			page_index->page_data =
4059 				(uint8_t *)lun->mode_pages.caching_page;
4060 			break;
4061 		}
4062 		case SMS_CONTROL_MODE_PAGE: {
4063 
4064 			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4065 				panic("invalid subpage value %d",
4066 				      page_index->subpage);
4067 
4068 			/*
4069 			 * Defaults should be okay here, no calculations
4070 			 * needed.
4071 			 */
4072 			memcpy(&lun->mode_pages.control_page[CTL_PAGE_CURRENT],
4073 			       &control_page_default,
4074 			       sizeof(control_page_default));
4075 			memcpy(&lun->mode_pages.control_page[
4076 			       CTL_PAGE_CHANGEABLE], &control_page_changeable,
4077 			       sizeof(control_page_changeable));
4078 			memcpy(&lun->mode_pages.control_page[CTL_PAGE_DEFAULT],
4079 			       &control_page_default,
4080 			       sizeof(control_page_default));
4081 			memcpy(&lun->mode_pages.control_page[CTL_PAGE_SAVED],
4082 			       &control_page_default,
4083 			       sizeof(control_page_default));
4084 			page_index->page_data =
4085 				(uint8_t *)lun->mode_pages.control_page;
4086 			break;
4087 
4088 		}
4089 		case SMS_VENDOR_SPECIFIC_PAGE:{
4090 			switch (page_index->subpage) {
4091 			case PWR_SUBPAGE_CODE: {
4092 				struct copan_power_subpage *current_page,
4093 							   *saved_page;
4094 
4095 				memcpy(&lun->mode_pages.power_subpage[
4096 				       CTL_PAGE_CURRENT],
4097 				       &power_page_default,
4098 				       sizeof(power_page_default));
4099 				memcpy(&lun->mode_pages.power_subpage[
4100 				       CTL_PAGE_CHANGEABLE],
4101 				       &power_page_changeable,
4102 				       sizeof(power_page_changeable));
4103 				memcpy(&lun->mode_pages.power_subpage[
4104 				       CTL_PAGE_DEFAULT],
4105 				       &power_page_default,
4106 				       sizeof(power_page_default));
4107 				memcpy(&lun->mode_pages.power_subpage[
4108 				       CTL_PAGE_SAVED],
4109 				       &power_page_default,
4110 				       sizeof(power_page_default));
4111 				page_index->page_data =
4112 				    (uint8_t *)lun->mode_pages.power_subpage;
4113 
4114 				current_page = (struct copan_power_subpage *)
4115 					(page_index->page_data +
4116 					 (page_index->page_len *
4117 					  CTL_PAGE_CURRENT));
4118 			        saved_page = (struct copan_power_subpage *)
4119 				        (page_index->page_data +
4120 					 (page_index->page_len *
4121 					  CTL_PAGE_SAVED));
4122 				break;
4123 			}
4124 			case APS_SUBPAGE_CODE: {
4125 				struct copan_aps_subpage *current_page,
4126 							 *saved_page;
4127 
4128 				// This gets set multiple times but
4129 				// it should always be the same. It's
4130 				// only done during init so who cares.
4131 				index_to_aps_page = i;
4132 
4133 				memcpy(&lun->mode_pages.aps_subpage[
4134 				       CTL_PAGE_CURRENT],
4135 				       &aps_page_default,
4136 				       sizeof(aps_page_default));
4137 				memcpy(&lun->mode_pages.aps_subpage[
4138 				       CTL_PAGE_CHANGEABLE],
4139 				       &aps_page_changeable,
4140 				       sizeof(aps_page_changeable));
4141 				memcpy(&lun->mode_pages.aps_subpage[
4142 				       CTL_PAGE_DEFAULT],
4143 				       &aps_page_default,
4144 				       sizeof(aps_page_default));
4145 				memcpy(&lun->mode_pages.aps_subpage[
4146 				       CTL_PAGE_SAVED],
4147 				       &aps_page_default,
4148 				       sizeof(aps_page_default));
4149 				page_index->page_data =
4150 					(uint8_t *)lun->mode_pages.aps_subpage;
4151 
4152 				current_page = (struct copan_aps_subpage *)
4153 					(page_index->page_data +
4154 					 (page_index->page_len *
4155 					  CTL_PAGE_CURRENT));
4156 				saved_page = (struct copan_aps_subpage *)
4157 					(page_index->page_data +
4158 					 (page_index->page_len *
4159 					  CTL_PAGE_SAVED));
4160 				break;
4161 			}
4162 			case DBGCNF_SUBPAGE_CODE: {
4163 				struct copan_debugconf_subpage *current_page,
4164 							       *saved_page;
4165 
4166 				memcpy(&lun->mode_pages.debugconf_subpage[
4167 				       CTL_PAGE_CURRENT],
4168 				       &debugconf_page_default,
4169 				       sizeof(debugconf_page_default));
4170 				memcpy(&lun->mode_pages.debugconf_subpage[
4171 				       CTL_PAGE_CHANGEABLE],
4172 				       &debugconf_page_changeable,
4173 				       sizeof(debugconf_page_changeable));
4174 				memcpy(&lun->mode_pages.debugconf_subpage[
4175 				       CTL_PAGE_DEFAULT],
4176 				       &debugconf_page_default,
4177 				       sizeof(debugconf_page_default));
4178 				memcpy(&lun->mode_pages.debugconf_subpage[
4179 				       CTL_PAGE_SAVED],
4180 				       &debugconf_page_default,
4181 				       sizeof(debugconf_page_default));
4182 				page_index->page_data =
4183 					(uint8_t *)lun->mode_pages.debugconf_subpage;
4184 
4185 				current_page = (struct copan_debugconf_subpage *)
4186 					(page_index->page_data +
4187 					 (page_index->page_len *
4188 					  CTL_PAGE_CURRENT));
4189 				saved_page = (struct copan_debugconf_subpage *)
4190 					(page_index->page_data +
4191 					 (page_index->page_len *
4192 					  CTL_PAGE_SAVED));
4193 				break;
4194 			}
4195 			default:
4196 				panic("invalid subpage value %d",
4197 				      page_index->subpage);
4198 				break;
4199 			}
4200    			break;
4201 		}
4202 		default:
4203 			panic("invalid page value %d",
4204 			      page_index->page_code & SMPH_PC_MASK);
4205 			break;
4206     	}
4207 	}
4208 
4209 	return (CTL_RETVAL_COMPLETE);
4210 }
4211 
4212 /*
4213  * LUN allocation.
4214  *
4215  * Requirements:
4216  * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4217  *   wants us to allocate the LUN and he can block.
4218  * - ctl_softc is always set
4219  * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4220  *
4221  * Returns 0 for success, non-zero (errno) for failure.
4222  */
4223 static int
4224 ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4225 	      struct ctl_be_lun *const be_lun, struct ctl_id target_id)
4226 {
4227 	struct ctl_lun *nlun, *lun;
4228 	struct ctl_frontend *fe;
4229 	int lun_number, i, lun_malloced;
4230 
4231 	if (be_lun == NULL)
4232 		return (EINVAL);
4233 
4234 	/*
4235 	 * We currently only support Direct Access or Processor LUN types.
4236 	 */
4237 	switch (be_lun->lun_type) {
4238 	case T_DIRECT:
4239 		break;
4240 	case T_PROCESSOR:
4241 		break;
4242 	case T_SEQUENTIAL:
4243 	case T_CHANGER:
4244 	default:
4245 		be_lun->lun_config_status(be_lun->be_lun,
4246 					  CTL_LUN_CONFIG_FAILURE);
4247 		break;
4248 	}
4249 	if (ctl_lun == NULL) {
4250 		lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4251 		lun_malloced = 1;
4252 	} else {
4253 		lun_malloced = 0;
4254 		lun = ctl_lun;
4255 	}
4256 
4257 	memset(lun, 0, sizeof(*lun));
4258 	if (lun_malloced)
4259 		lun->flags = CTL_LUN_MALLOCED;
4260 
4261 	mtx_lock(&ctl_softc->ctl_lock);
4262 	/*
4263 	 * See if the caller requested a particular LUN number.  If so, see
4264 	 * if it is available.  Otherwise, allocate the first available LUN.
4265 	 */
4266 	if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4267 		if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4268 		 || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4269 			mtx_unlock(&ctl_softc->ctl_lock);
4270 			if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4271 				printf("ctl: requested LUN ID %d is higher "
4272 				       "than CTL_MAX_LUNS - 1 (%d)\n",
4273 				       be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4274 			} else {
4275 				/*
4276 				 * XXX KDM return an error, or just assign
4277 				 * another LUN ID in this case??
4278 				 */
4279 				printf("ctl: requested LUN ID %d is already "
4280 				       "in use\n", be_lun->req_lun_id);
4281 			}
4282 			if (lun->flags & CTL_LUN_MALLOCED)
4283 				free(lun, M_CTL);
4284 			be_lun->lun_config_status(be_lun->be_lun,
4285 						  CTL_LUN_CONFIG_FAILURE);
4286 			return (ENOSPC);
4287 		}
4288 		lun_number = be_lun->req_lun_id;
4289 	} else {
4290 		lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, CTL_MAX_LUNS);
4291 		if (lun_number == -1) {
4292 			mtx_unlock(&ctl_softc->ctl_lock);
4293 			printf("ctl: can't allocate LUN on target %ju, out of "
4294 			       "LUNs\n", (uintmax_t)target_id.id);
4295 			if (lun->flags & CTL_LUN_MALLOCED)
4296 				free(lun, M_CTL);
4297 			be_lun->lun_config_status(be_lun->be_lun,
4298 						  CTL_LUN_CONFIG_FAILURE);
4299 			return (ENOSPC);
4300 		}
4301 	}
4302 	ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4303 
4304 	lun->target = target_id;
4305 	lun->lun = lun_number;
4306 	lun->be_lun = be_lun;
4307 	/*
4308 	 * The processor LUN is always enabled.  Disk LUNs come on line
4309 	 * disabled, and must be enabled by the backend.
4310 	 */
4311 	lun->flags |= CTL_LUN_DISABLED;
4312 	lun->backend = be_lun->be;
4313 	be_lun->ctl_lun = lun;
4314 	be_lun->lun_id = lun_number;
4315 	atomic_add_int(&be_lun->be->num_luns, 1);
4316 	if (be_lun->flags & CTL_LUN_FLAG_POWERED_OFF)
4317 		lun->flags |= CTL_LUN_STOPPED;
4318 
4319 	if (be_lun->flags & CTL_LUN_FLAG_INOPERABLE)
4320 		lun->flags |= CTL_LUN_INOPERABLE;
4321 
4322 	if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4323 		lun->flags |= CTL_LUN_PRIMARY_SC;
4324 
4325 	lun->ctl_softc = ctl_softc;
4326 	TAILQ_INIT(&lun->ooa_queue);
4327 	TAILQ_INIT(&lun->blocked_queue);
4328 	STAILQ_INIT(&lun->error_list);
4329 
4330 	/*
4331 	 * Initialize the mode page index.
4332 	 */
4333 	ctl_init_page_index(lun);
4334 
4335 	/*
4336 	 * Set the poweron UA for all initiators on this LUN only.
4337 	 */
4338 	for (i = 0; i < CTL_MAX_INITIATORS; i++)
4339 		lun->pending_sense[i].ua_pending = CTL_UA_POWERON;
4340 
4341 	/*
4342 	 * Now, before we insert this lun on the lun list, set the lun
4343 	 * inventory changed UA for all other luns.
4344 	 */
4345 	STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4346 		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
4347 			nlun->pending_sense[i].ua_pending |= CTL_UA_LUN_CHANGE;
4348 		}
4349 	}
4350 
4351 	STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4352 
4353 	ctl_softc->ctl_luns[lun_number] = lun;
4354 
4355 	ctl_softc->num_luns++;
4356 
4357 	/* Setup statistics gathering */
4358 	lun->stats.device_type = be_lun->lun_type;
4359 	lun->stats.lun_number = lun_number;
4360 	if (lun->stats.device_type == T_DIRECT)
4361 		lun->stats.blocksize = be_lun->blocksize;
4362 	else
4363 		lun->stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4364 	for (i = 0;i < CTL_MAX_PORTS;i++)
4365 		lun->stats.ports[i].targ_port = i;
4366 
4367 	mtx_unlock(&ctl_softc->ctl_lock);
4368 
4369 	lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4370 
4371 	/*
4372 	 * Run through each registered FETD and bring it online if it isn't
4373 	 * already.  Enable the target ID if it hasn't been enabled, and
4374 	 * enable this particular LUN.
4375 	 */
4376 	STAILQ_FOREACH(fe, &ctl_softc->fe_list, links) {
4377 		int retval;
4378 
4379 		/*
4380 		 * XXX KDM this only works for ONE TARGET ID.  We'll need
4381 		 * to do things differently if we go to a multiple target
4382 		 * ID scheme.
4383 		 */
4384 		if ((fe->status & CTL_PORT_STATUS_TARG_ONLINE) == 0) {
4385 
4386 			retval = fe->targ_enable(fe->targ_lun_arg, target_id);
4387 			if (retval != 0) {
4388 				printf("ctl_alloc_lun: FETD %s port %d "
4389 				       "returned error %d for targ_enable on "
4390 				       "target %ju\n", fe->port_name,
4391 				       fe->targ_port, retval,
4392 				       (uintmax_t)target_id.id);
4393 			} else
4394 				fe->status |= CTL_PORT_STATUS_TARG_ONLINE;
4395 		}
4396 
4397 		retval = fe->lun_enable(fe->targ_lun_arg, target_id,lun_number);
4398 		if (retval != 0) {
4399 			printf("ctl_alloc_lun: FETD %s port %d returned error "
4400 			       "%d for lun_enable on target %ju lun %d\n",
4401 			       fe->port_name, fe->targ_port, retval,
4402 			       (uintmax_t)target_id.id, lun_number);
4403 		} else
4404 			fe->status |= CTL_PORT_STATUS_LUN_ONLINE;
4405 	}
4406 	return (0);
4407 }
4408 
4409 /*
4410  * Delete a LUN.
4411  * Assumptions:
4412  * - LUN has already been marked invalid and any pending I/O has been taken
4413  *   care of.
4414  */
4415 static int
4416 ctl_free_lun(struct ctl_lun *lun)
4417 {
4418 	struct ctl_softc *softc;
4419 #if 0
4420 	struct ctl_frontend *fe;
4421 #endif
4422 	struct ctl_lun *nlun;
4423 	union ctl_io *io, *next_io;
4424 	int i;
4425 
4426 	softc = lun->ctl_softc;
4427 
4428 	mtx_assert(&softc->ctl_lock, MA_OWNED);
4429 
4430 	STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4431 
4432 	ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4433 
4434 	softc->ctl_luns[lun->lun] = NULL;
4435 
4436 	if (TAILQ_FIRST(&lun->ooa_queue) != NULL) {
4437 		printf("ctl_free_lun: aieee!! freeing a LUN with "
4438 		       "outstanding I/O!!\n");
4439 	}
4440 
4441 	/*
4442 	 * If we have anything pending on the RtR queue, remove it.
4443 	 */
4444 	for (io = (union ctl_io *)STAILQ_FIRST(&softc->rtr_queue); io != NULL;
4445 	     io = next_io) {
4446 		uint32_t targ_lun;
4447 
4448 		next_io = (union ctl_io *)STAILQ_NEXT(&io->io_hdr, links);
4449 		targ_lun = io->io_hdr.nexus.targ_lun;
4450 		if (io->io_hdr.nexus.lun_map_fn != NULL)
4451 			targ_lun = io->io_hdr.nexus.lun_map_fn(io->io_hdr.nexus.lun_map_arg, targ_lun);
4452 		if ((io->io_hdr.nexus.targ_target.id == lun->target.id)
4453 		 && (targ_lun == lun->lun))
4454 			STAILQ_REMOVE(&softc->rtr_queue, &io->io_hdr,
4455 				      ctl_io_hdr, links);
4456 	}
4457 
4458 	/*
4459 	 * Then remove everything from the blocked queue.
4460 	 */
4461 	for (io = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue); io != NULL;
4462 	     io = next_io) {
4463 		next_io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,blocked_links);
4464 		TAILQ_REMOVE(&lun->blocked_queue, &io->io_hdr, blocked_links);
4465 		io->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
4466 	}
4467 
4468 	/*
4469 	 * Now clear out the OOA queue, and free all the I/O.
4470 	 * XXX KDM should we notify the FETD here?  We probably need to
4471 	 * quiesce the LUN before deleting it.
4472 	 */
4473 	for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); io != NULL;
4474 	     io = next_io) {
4475 		next_io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr, ooa_links);
4476 		TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
4477 		ctl_free_io_internal(io, /*have_lock*/ 1);
4478 	}
4479 
4480 	softc->num_luns--;
4481 
4482 	/*
4483 	 * XXX KDM this scheme only works for a single target/multiple LUN
4484 	 * setup.  It needs to be revamped for a multiple target scheme.
4485 	 *
4486 	 * XXX KDM this results in fe->lun_disable() getting called twice,
4487 	 * once when ctl_disable_lun() is called, and a second time here.
4488 	 * We really need to re-think the LUN disable semantics.  There
4489 	 * should probably be several steps/levels to LUN removal:
4490 	 *  - disable
4491 	 *  - invalidate
4492 	 *  - free
4493  	 *
4494 	 * Right now we only have a disable method when communicating to
4495 	 * the front end ports, at least for individual LUNs.
4496 	 */
4497 #if 0
4498 	STAILQ_FOREACH(fe, &softc->fe_list, links) {
4499 		int retval;
4500 
4501 		retval = fe->lun_disable(fe->targ_lun_arg, lun->target,
4502 					 lun->lun);
4503 		if (retval != 0) {
4504 			printf("ctl_free_lun: FETD %s port %d returned error "
4505 			       "%d for lun_disable on target %ju lun %jd\n",
4506 			       fe->port_name, fe->targ_port, retval,
4507 			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4508 		}
4509 
4510 		if (STAILQ_FIRST(&softc->lun_list) == NULL) {
4511 			fe->status &= ~CTL_PORT_STATUS_LUN_ONLINE;
4512 
4513 			retval = fe->targ_disable(fe->targ_lun_arg,lun->target);
4514 			if (retval != 0) {
4515 				printf("ctl_free_lun: FETD %s port %d "
4516 				       "returned error %d for targ_disable on "
4517 				       "target %ju\n", fe->port_name,
4518 				       fe->targ_port, retval,
4519 				       (uintmax_t)lun->target.id);
4520 			} else
4521 				fe->status &= ~CTL_PORT_STATUS_TARG_ONLINE;
4522 
4523 			if ((fe->status & CTL_PORT_STATUS_TARG_ONLINE) != 0)
4524 				continue;
4525 
4526 #if 0
4527 			fe->port_offline(fe->onoff_arg);
4528 			fe->status &= ~CTL_PORT_STATUS_ONLINE;
4529 #endif
4530 		}
4531 	}
4532 #endif
4533 
4534 	/*
4535 	 * Tell the backend to free resources, if this LUN has a backend.
4536 	 */
4537 	atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4538 	lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4539 
4540 	if (lun->flags & CTL_LUN_MALLOCED)
4541 		free(lun, M_CTL);
4542 
4543 	STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4544 		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
4545 			nlun->pending_sense[i].ua_pending |= CTL_UA_LUN_CHANGE;
4546 		}
4547 	}
4548 
4549 	return (0);
4550 }
4551 
4552 static void
4553 ctl_create_lun(struct ctl_be_lun *be_lun)
4554 {
4555 	struct ctl_softc *ctl_softc;
4556 
4557 	ctl_softc = control_softc;
4558 
4559 	/*
4560 	 * ctl_alloc_lun() should handle all potential failure cases.
4561 	 */
4562 	ctl_alloc_lun(ctl_softc, NULL, be_lun, ctl_softc->target);
4563 }
4564 
4565 int
4566 ctl_add_lun(struct ctl_be_lun *be_lun)
4567 {
4568 	struct ctl_softc *ctl_softc;
4569 
4570 	ctl_softc = control_softc;
4571 
4572 	mtx_lock(&ctl_softc->ctl_lock);
4573 	STAILQ_INSERT_TAIL(&ctl_softc->pending_lun_queue, be_lun, links);
4574 	mtx_unlock(&ctl_softc->ctl_lock);
4575 
4576 	ctl_wakeup_thread();
4577 
4578 	return (0);
4579 }
4580 
4581 int
4582 ctl_enable_lun(struct ctl_be_lun *be_lun)
4583 {
4584 	struct ctl_softc *ctl_softc;
4585 	struct ctl_frontend *fe, *nfe;
4586 	struct ctl_lun *lun;
4587 	int retval;
4588 
4589 	ctl_softc = control_softc;
4590 
4591 	lun = (struct ctl_lun *)be_lun->ctl_lun;
4592 
4593 	mtx_lock(&ctl_softc->ctl_lock);
4594 	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4595 		/*
4596 		 * eh?  Why did we get called if the LUN is already
4597 		 * enabled?
4598 		 */
4599 		mtx_unlock(&ctl_softc->ctl_lock);
4600 		return (0);
4601 	}
4602 	lun->flags &= ~CTL_LUN_DISABLED;
4603 
4604 	for (fe = STAILQ_FIRST(&ctl_softc->fe_list); fe != NULL; fe = nfe) {
4605 		nfe = STAILQ_NEXT(fe, links);
4606 
4607 		/*
4608 		 * Drop the lock while we call the FETD's enable routine.
4609 		 * This can lead to a callback into CTL (at least in the
4610 		 * case of the internal initiator frontend.
4611 		 */
4612 		mtx_unlock(&ctl_softc->ctl_lock);
4613 		retval = fe->lun_enable(fe->targ_lun_arg, lun->target,lun->lun);
4614 		mtx_lock(&ctl_softc->ctl_lock);
4615 		if (retval != 0) {
4616 			printf("%s: FETD %s port %d returned error "
4617 			       "%d for lun_enable on target %ju lun %jd\n",
4618 			       __func__, fe->port_name, fe->targ_port, retval,
4619 			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4620 		}
4621 #if 0
4622 		 else {
4623             /* NOTE:  TODO:  why does lun enable affect port status? */
4624 			fe->status |= CTL_PORT_STATUS_LUN_ONLINE;
4625 		}
4626 #endif
4627 	}
4628 
4629 	mtx_unlock(&ctl_softc->ctl_lock);
4630 
4631 	return (0);
4632 }
4633 
4634 int
4635 ctl_disable_lun(struct ctl_be_lun *be_lun)
4636 {
4637 	struct ctl_softc *ctl_softc;
4638 	struct ctl_frontend *fe;
4639 	struct ctl_lun *lun;
4640 	int retval;
4641 
4642 	ctl_softc = control_softc;
4643 
4644 	lun = (struct ctl_lun *)be_lun->ctl_lun;
4645 
4646 	mtx_lock(&ctl_softc->ctl_lock);
4647 
4648 	if (lun->flags & CTL_LUN_DISABLED) {
4649 		mtx_unlock(&ctl_softc->ctl_lock);
4650 		return (0);
4651 	}
4652 	lun->flags |= CTL_LUN_DISABLED;
4653 
4654 	STAILQ_FOREACH(fe, &ctl_softc->fe_list, links) {
4655 		mtx_unlock(&ctl_softc->ctl_lock);
4656 		/*
4657 		 * Drop the lock before we call the frontend's disable
4658 		 * routine, to avoid lock order reversals.
4659 		 *
4660 		 * XXX KDM what happens if the frontend list changes while
4661 		 * we're traversing it?  It's unlikely, but should be handled.
4662 		 */
4663 		retval = fe->lun_disable(fe->targ_lun_arg, lun->target,
4664 					 lun->lun);
4665 		mtx_lock(&ctl_softc->ctl_lock);
4666 		if (retval != 0) {
4667 			printf("ctl_alloc_lun: FETD %s port %d returned error "
4668 			       "%d for lun_disable on target %ju lun %jd\n",
4669 			       fe->port_name, fe->targ_port, retval,
4670 			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4671 		}
4672 	}
4673 
4674 	mtx_unlock(&ctl_softc->ctl_lock);
4675 
4676 	return (0);
4677 }
4678 
4679 int
4680 ctl_start_lun(struct ctl_be_lun *be_lun)
4681 {
4682 	struct ctl_softc *ctl_softc;
4683 	struct ctl_lun *lun;
4684 
4685 	ctl_softc = control_softc;
4686 
4687 	lun = (struct ctl_lun *)be_lun->ctl_lun;
4688 
4689 	mtx_lock(&ctl_softc->ctl_lock);
4690 	lun->flags &= ~CTL_LUN_STOPPED;
4691 	mtx_unlock(&ctl_softc->ctl_lock);
4692 
4693 	return (0);
4694 }
4695 
4696 int
4697 ctl_stop_lun(struct ctl_be_lun *be_lun)
4698 {
4699 	struct ctl_softc *ctl_softc;
4700 	struct ctl_lun *lun;
4701 
4702 	ctl_softc = control_softc;
4703 
4704 	lun = (struct ctl_lun *)be_lun->ctl_lun;
4705 
4706 	mtx_lock(&ctl_softc->ctl_lock);
4707 	lun->flags |= CTL_LUN_STOPPED;
4708 	mtx_unlock(&ctl_softc->ctl_lock);
4709 
4710 	return (0);
4711 }
4712 
4713 int
4714 ctl_lun_offline(struct ctl_be_lun *be_lun)
4715 {
4716 	struct ctl_softc *ctl_softc;
4717 	struct ctl_lun *lun;
4718 
4719 	ctl_softc = control_softc;
4720 
4721 	lun = (struct ctl_lun *)be_lun->ctl_lun;
4722 
4723 	mtx_lock(&ctl_softc->ctl_lock);
4724 	lun->flags |= CTL_LUN_OFFLINE;
4725 	mtx_unlock(&ctl_softc->ctl_lock);
4726 
4727 	return (0);
4728 }
4729 
4730 int
4731 ctl_lun_online(struct ctl_be_lun *be_lun)
4732 {
4733 	struct ctl_softc *ctl_softc;
4734 	struct ctl_lun *lun;
4735 
4736 	ctl_softc = control_softc;
4737 
4738 	lun = (struct ctl_lun *)be_lun->ctl_lun;
4739 
4740 	mtx_lock(&ctl_softc->ctl_lock);
4741 	lun->flags &= ~CTL_LUN_OFFLINE;
4742 	mtx_unlock(&ctl_softc->ctl_lock);
4743 
4744 	return (0);
4745 }
4746 
4747 int
4748 ctl_invalidate_lun(struct ctl_be_lun *be_lun)
4749 {
4750 	struct ctl_softc *ctl_softc;
4751 	struct ctl_lun *lun;
4752 
4753 	ctl_softc = control_softc;
4754 
4755 	lun = (struct ctl_lun *)be_lun->ctl_lun;
4756 
4757 	mtx_lock(&ctl_softc->ctl_lock);
4758 
4759 	/*
4760 	 * The LUN needs to be disabled before it can be marked invalid.
4761 	 */
4762 	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4763 		mtx_unlock(&ctl_softc->ctl_lock);
4764 		return (-1);
4765 	}
4766 	/*
4767 	 * Mark the LUN invalid.
4768 	 */
4769 	lun->flags |= CTL_LUN_INVALID;
4770 
4771 	/*
4772 	 * If there is nothing in the OOA queue, go ahead and free the LUN.
4773 	 * If we have something in the OOA queue, we'll free it when the
4774 	 * last I/O completes.
4775 	 */
4776 	if (TAILQ_FIRST(&lun->ooa_queue) == NULL)
4777 		ctl_free_lun(lun);
4778 	mtx_unlock(&ctl_softc->ctl_lock);
4779 
4780 	return (0);
4781 }
4782 
4783 int
4784 ctl_lun_inoperable(struct ctl_be_lun *be_lun)
4785 {
4786 	struct ctl_softc *ctl_softc;
4787 	struct ctl_lun *lun;
4788 
4789 	ctl_softc = control_softc;
4790 	lun = (struct ctl_lun *)be_lun->ctl_lun;
4791 
4792 	mtx_lock(&ctl_softc->ctl_lock);
4793 	lun->flags |= CTL_LUN_INOPERABLE;
4794 	mtx_unlock(&ctl_softc->ctl_lock);
4795 
4796 	return (0);
4797 }
4798 
4799 int
4800 ctl_lun_operable(struct ctl_be_lun *be_lun)
4801 {
4802 	struct ctl_softc *ctl_softc;
4803 	struct ctl_lun *lun;
4804 
4805 	ctl_softc = control_softc;
4806 	lun = (struct ctl_lun *)be_lun->ctl_lun;
4807 
4808 	mtx_lock(&ctl_softc->ctl_lock);
4809 	lun->flags &= ~CTL_LUN_INOPERABLE;
4810 	mtx_unlock(&ctl_softc->ctl_lock);
4811 
4812 	return (0);
4813 }
4814 
4815 int
4816 ctl_lun_power_lock(struct ctl_be_lun *be_lun, struct ctl_nexus *nexus,
4817 		   int lock)
4818 {
4819 	struct ctl_softc *softc;
4820 	struct ctl_lun *lun;
4821 	struct copan_aps_subpage *current_sp;
4822 	struct ctl_page_index *page_index;
4823 	int i;
4824 
4825 	softc = control_softc;
4826 
4827 	mtx_lock(&softc->ctl_lock);
4828 
4829 	lun = (struct ctl_lun *)be_lun->ctl_lun;
4830 
4831 	page_index = NULL;
4832 	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
4833 		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
4834 		     APS_PAGE_CODE)
4835 			continue;
4836 
4837 		if (lun->mode_pages.index[i].subpage != APS_SUBPAGE_CODE)
4838 			continue;
4839 		page_index = &lun->mode_pages.index[i];
4840 	}
4841 
4842 	if (page_index == NULL) {
4843 		mtx_unlock(&softc->ctl_lock);
4844 		printf("%s: APS subpage not found for lun %ju!\n", __func__,
4845 		       (uintmax_t)lun->lun);
4846 		return (1);
4847 	}
4848 #if 0
4849 	if ((softc->aps_locked_lun != 0)
4850 	 && (softc->aps_locked_lun != lun->lun)) {
4851 		printf("%s: attempt to lock LUN %llu when %llu is already "
4852 		       "locked\n");
4853 		mtx_unlock(&softc->ctl_lock);
4854 		return (1);
4855 	}
4856 #endif
4857 
4858 	current_sp = (struct copan_aps_subpage *)(page_index->page_data +
4859 		(page_index->page_len * CTL_PAGE_CURRENT));
4860 
4861 	if (lock != 0) {
4862 		current_sp->lock_active = APS_LOCK_ACTIVE;
4863 		softc->aps_locked_lun = lun->lun;
4864 	} else {
4865 		current_sp->lock_active = 0;
4866 		softc->aps_locked_lun = 0;
4867 	}
4868 
4869 
4870 	/*
4871 	 * If we're in HA mode, try to send the lock message to the other
4872 	 * side.
4873 	 */
4874 	if (ctl_is_single == 0) {
4875 		int isc_retval;
4876 		union ctl_ha_msg lock_msg;
4877 
4878 		lock_msg.hdr.nexus = *nexus;
4879 		lock_msg.hdr.msg_type = CTL_MSG_APS_LOCK;
4880 		if (lock != 0)
4881 			lock_msg.aps.lock_flag = 1;
4882 		else
4883 			lock_msg.aps.lock_flag = 0;
4884 		isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &lock_msg,
4885 					 sizeof(lock_msg), 0);
4886 		if (isc_retval > CTL_HA_STATUS_SUCCESS) {
4887 			printf("%s: APS (lock=%d) error returned from "
4888 			       "ctl_ha_msg_send: %d\n", __func__, lock, isc_retval);
4889 			mtx_unlock(&softc->ctl_lock);
4890 			return (1);
4891 		}
4892 	}
4893 
4894 	mtx_unlock(&softc->ctl_lock);
4895 
4896 	return (0);
4897 }
4898 
4899 void
4900 ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
4901 {
4902 	struct ctl_lun *lun;
4903 	struct ctl_softc *softc;
4904 	int i;
4905 
4906 	softc = control_softc;
4907 
4908 	mtx_lock(&softc->ctl_lock);
4909 
4910 	lun = (struct ctl_lun *)be_lun->ctl_lun;
4911 
4912 	for (i = 0; i < CTL_MAX_INITIATORS; i++)
4913 		lun->pending_sense[i].ua_pending |= CTL_UA_CAPACITY_CHANGED;
4914 
4915 	mtx_unlock(&softc->ctl_lock);
4916 }
4917 
4918 /*
4919  * Backend "memory move is complete" callback for requests that never
4920  * make it down to say RAIDCore's configuration code.
4921  */
4922 int
4923 ctl_config_move_done(union ctl_io *io)
4924 {
4925 	int retval;
4926 
4927 	retval = CTL_RETVAL_COMPLETE;
4928 
4929 
4930 	CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
4931 	/*
4932 	 * XXX KDM this shouldn't happen, but what if it does?
4933 	 */
4934 	if (io->io_hdr.io_type != CTL_IO_SCSI)
4935 		panic("I/O type isn't CTL_IO_SCSI!");
4936 
4937 	if ((io->io_hdr.port_status == 0)
4938 	 && ((io->io_hdr.flags & CTL_FLAG_ABORT) == 0)
4939 	 && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE))
4940 		io->io_hdr.status = CTL_SUCCESS;
4941 	else if ((io->io_hdr.port_status != 0)
4942 	      && ((io->io_hdr.flags & CTL_FLAG_ABORT) == 0)
4943 	      && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE)){
4944 		/*
4945 		 * For hardware error sense keys, the sense key
4946 		 * specific value is defined to be a retry count,
4947 		 * but we use it to pass back an internal FETD
4948 		 * error code.  XXX KDM  Hopefully the FETD is only
4949 		 * using 16 bits for an error code, since that's
4950 		 * all the space we have in the sks field.
4951 		 */
4952 		ctl_set_internal_failure(&io->scsiio,
4953 					 /*sks_valid*/ 1,
4954 					 /*retry_count*/
4955 					 io->io_hdr.port_status);
4956 		free(io->scsiio.kern_data_ptr, M_CTL);
4957 		ctl_done(io);
4958 		goto bailout;
4959 	}
4960 
4961 	if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
4962 	 || ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)
4963 	 || ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
4964 		/*
4965 		 * XXX KDM just assuming a single pointer here, and not a
4966 		 * S/G list.  If we start using S/G lists for config data,
4967 		 * we'll need to know how to clean them up here as well.
4968 		 */
4969 		free(io->scsiio.kern_data_ptr, M_CTL);
4970 		/* Hopefully the user has already set the status... */
4971 		ctl_done(io);
4972 	} else {
4973 		/*
4974 		 * XXX KDM now we need to continue data movement.  Some
4975 		 * options:
4976 		 * - call ctl_scsiio() again?  We don't do this for data
4977 		 *   writes, because for those at least we know ahead of
4978 		 *   time where the write will go and how long it is.  For
4979 		 *   config writes, though, that information is largely
4980 		 *   contained within the write itself, thus we need to
4981 		 *   parse out the data again.
4982 		 *
4983 		 * - Call some other function once the data is in?
4984 		 */
4985 
4986 		/*
4987 		 * XXX KDM call ctl_scsiio() again for now, and check flag
4988 		 * bits to see whether we're allocated or not.
4989 		 */
4990 		retval = ctl_scsiio(&io->scsiio);
4991 	}
4992 bailout:
4993 	return (retval);
4994 }
4995 
4996 /*
4997  * This gets called by a backend driver when it is done with a
4998  * configuration write.
4999  */
5000 void
5001 ctl_config_write_done(union ctl_io *io)
5002 {
5003 	/*
5004 	 * If the IO_CONT flag is set, we need to call the supplied
5005 	 * function to continue processing the I/O, instead of completing
5006 	 * the I/O just yet.
5007 	 *
5008 	 * If there is an error, though, we don't want to keep processing.
5009 	 * Instead, just send status back to the initiator.
5010 	 */
5011 	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT)
5012 	 && (((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE)
5013 	  || ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS))) {
5014 		io->scsiio.io_cont(io);
5015 		return;
5016 	}
5017 	/*
5018 	 * Since a configuration write can be done for commands that actually
5019 	 * have data allocated, like write buffer, and commands that have
5020 	 * no data, like start/stop unit, we need to check here.
5021 	 */
5022 	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT)
5023 		free(io->scsiio.kern_data_ptr, M_CTL);
5024 	ctl_done(io);
5025 }
5026 
5027 /*
5028  * SCSI release command.
5029  */
5030 int
5031 ctl_scsi_release(struct ctl_scsiio *ctsio)
5032 {
5033 	int length, longid, thirdparty_id, resv_id;
5034 	struct ctl_softc *ctl_softc;
5035 	struct ctl_lun *lun;
5036 
5037 	length = 0;
5038 	resv_id = 0;
5039 
5040 	CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5041 
5042 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5043 	ctl_softc = control_softc;
5044 
5045 	switch (ctsio->cdb[0]) {
5046 	case RELEASE: {
5047 		struct scsi_release *cdb;
5048 
5049 		cdb = (struct scsi_release *)ctsio->cdb;
5050 		if ((cdb->byte2 & 0x1f) != 0) {
5051 			ctl_set_invalid_field(ctsio,
5052 					      /*sks_valid*/ 1,
5053 					      /*command*/ 1,
5054 					      /*field*/ 1,
5055 					      /*bit_valid*/ 0,
5056 					      /*bit*/ 0);
5057 			ctl_done((union ctl_io *)ctsio);
5058 			return (CTL_RETVAL_COMPLETE);
5059 		}
5060 		break;
5061 	}
5062 	case RELEASE_10: {
5063 		struct scsi_release_10 *cdb;
5064 
5065 		cdb = (struct scsi_release_10 *)ctsio->cdb;
5066 
5067 		if ((cdb->byte2 & SR10_EXTENT) != 0) {
5068 			ctl_set_invalid_field(ctsio,
5069 					      /*sks_valid*/ 1,
5070 					      /*command*/ 1,
5071 					      /*field*/ 1,
5072 					      /*bit_valid*/ 1,
5073 					      /*bit*/ 0);
5074 			ctl_done((union ctl_io *)ctsio);
5075 			return (CTL_RETVAL_COMPLETE);
5076 
5077 		}
5078 
5079 		if ((cdb->byte2 & SR10_3RDPTY) != 0) {
5080 			ctl_set_invalid_field(ctsio,
5081 					      /*sks_valid*/ 1,
5082 					      /*command*/ 1,
5083 					      /*field*/ 1,
5084 					      /*bit_valid*/ 1,
5085 					      /*bit*/ 4);
5086 			ctl_done((union ctl_io *)ctsio);
5087 			return (CTL_RETVAL_COMPLETE);
5088 		}
5089 
5090 		if (cdb->byte2 & SR10_LONGID)
5091 			longid = 1;
5092 		else
5093 			thirdparty_id = cdb->thirdparty_id;
5094 
5095 		resv_id = cdb->resv_id;
5096 		length = scsi_2btoul(cdb->length);
5097 		break;
5098 	}
5099 	}
5100 
5101 
5102 	/*
5103 	 * XXX KDM right now, we only support LUN reservation.  We don't
5104 	 * support 3rd party reservations, or extent reservations, which
5105 	 * might actually need the parameter list.  If we've gotten this
5106 	 * far, we've got a LUN reservation.  Anything else got kicked out
5107 	 * above.  So, according to SPC, ignore the length.
5108 	 */
5109 	length = 0;
5110 
5111 	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5112 	 && (length > 0)) {
5113 		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5114 		ctsio->kern_data_len = length;
5115 		ctsio->kern_total_len = length;
5116 		ctsio->kern_data_resid = 0;
5117 		ctsio->kern_rel_offset = 0;
5118 		ctsio->kern_sg_entries = 0;
5119 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5120 		ctsio->be_move_done = ctl_config_move_done;
5121 		ctl_datamove((union ctl_io *)ctsio);
5122 
5123 		return (CTL_RETVAL_COMPLETE);
5124 	}
5125 
5126 	if (length > 0)
5127 		thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5128 
5129 	mtx_lock(&ctl_softc->ctl_lock);
5130 
5131 	/*
5132 	 * According to SPC, it is not an error for an intiator to attempt
5133 	 * to release a reservation on a LUN that isn't reserved, or that
5134 	 * is reserved by another initiator.  The reservation can only be
5135 	 * released, though, by the initiator who made it or by one of
5136 	 * several reset type events.
5137 	 */
5138 	if (lun->flags & CTL_LUN_RESERVED) {
5139 		if ((ctsio->io_hdr.nexus.initid.id == lun->rsv_nexus.initid.id)
5140 		 && (ctsio->io_hdr.nexus.targ_port == lun->rsv_nexus.targ_port)
5141 		 && (ctsio->io_hdr.nexus.targ_target.id ==
5142 		     lun->rsv_nexus.targ_target.id)) {
5143 			lun->flags &= ~CTL_LUN_RESERVED;
5144 		}
5145 	}
5146 
5147 	ctsio->scsi_status = SCSI_STATUS_OK;
5148 	ctsio->io_hdr.status = CTL_SUCCESS;
5149 
5150 	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5151 		free(ctsio->kern_data_ptr, M_CTL);
5152 		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5153 	}
5154 
5155 	mtx_unlock(&ctl_softc->ctl_lock);
5156 
5157 	ctl_done((union ctl_io *)ctsio);
5158 	return (CTL_RETVAL_COMPLETE);
5159 }
5160 
5161 int
5162 ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5163 {
5164 	int extent, thirdparty, longid;
5165 	int resv_id, length;
5166 	uint64_t thirdparty_id;
5167 	struct ctl_softc *ctl_softc;
5168 	struct ctl_lun *lun;
5169 
5170 	extent = 0;
5171 	thirdparty = 0;
5172 	longid = 0;
5173 	resv_id = 0;
5174 	length = 0;
5175 	thirdparty_id = 0;
5176 
5177 	CTL_DEBUG_PRINT(("ctl_reserve\n"));
5178 
5179 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5180 	ctl_softc = control_softc;
5181 
5182 	switch (ctsio->cdb[0]) {
5183 	case RESERVE: {
5184 		struct scsi_reserve *cdb;
5185 
5186 		cdb = (struct scsi_reserve *)ctsio->cdb;
5187 		if ((cdb->byte2 & 0x1f) != 0) {
5188 			ctl_set_invalid_field(ctsio,
5189 					      /*sks_valid*/ 1,
5190 					      /*command*/ 1,
5191 					      /*field*/ 1,
5192 					      /*bit_valid*/ 0,
5193 					      /*bit*/ 0);
5194 			ctl_done((union ctl_io *)ctsio);
5195 			return (CTL_RETVAL_COMPLETE);
5196 		}
5197 		resv_id = cdb->resv_id;
5198 		length = scsi_2btoul(cdb->length);
5199 		break;
5200 	}
5201 	case RESERVE_10: {
5202 		struct scsi_reserve_10 *cdb;
5203 
5204 		cdb = (struct scsi_reserve_10 *)ctsio->cdb;
5205 
5206 		if ((cdb->byte2 & SR10_EXTENT) != 0) {
5207 			ctl_set_invalid_field(ctsio,
5208 					      /*sks_valid*/ 1,
5209 					      /*command*/ 1,
5210 					      /*field*/ 1,
5211 					      /*bit_valid*/ 1,
5212 					      /*bit*/ 0);
5213 			ctl_done((union ctl_io *)ctsio);
5214 			return (CTL_RETVAL_COMPLETE);
5215 		}
5216 		if ((cdb->byte2 & SR10_3RDPTY) != 0) {
5217 			ctl_set_invalid_field(ctsio,
5218 					      /*sks_valid*/ 1,
5219 					      /*command*/ 1,
5220 					      /*field*/ 1,
5221 					      /*bit_valid*/ 1,
5222 					      /*bit*/ 4);
5223 			ctl_done((union ctl_io *)ctsio);
5224 			return (CTL_RETVAL_COMPLETE);
5225 		}
5226 		if (cdb->byte2 & SR10_LONGID)
5227 			longid = 1;
5228 		else
5229 			thirdparty_id = cdb->thirdparty_id;
5230 
5231 		resv_id = cdb->resv_id;
5232 		length = scsi_2btoul(cdb->length);
5233 		break;
5234 	}
5235 	}
5236 
5237 	/*
5238 	 * XXX KDM right now, we only support LUN reservation.  We don't
5239 	 * support 3rd party reservations, or extent reservations, which
5240 	 * might actually need the parameter list.  If we've gotten this
5241 	 * far, we've got a LUN reservation.  Anything else got kicked out
5242 	 * above.  So, according to SPC, ignore the length.
5243 	 */
5244 	length = 0;
5245 
5246 	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5247 	 && (length > 0)) {
5248 		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5249 		ctsio->kern_data_len = length;
5250 		ctsio->kern_total_len = length;
5251 		ctsio->kern_data_resid = 0;
5252 		ctsio->kern_rel_offset = 0;
5253 		ctsio->kern_sg_entries = 0;
5254 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5255 		ctsio->be_move_done = ctl_config_move_done;
5256 		ctl_datamove((union ctl_io *)ctsio);
5257 
5258 		return (CTL_RETVAL_COMPLETE);
5259 	}
5260 
5261 	if (length > 0)
5262 		thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5263 
5264 	mtx_lock(&ctl_softc->ctl_lock);
5265 	if (lun->flags & CTL_LUN_RESERVED) {
5266 		if ((ctsio->io_hdr.nexus.initid.id != lun->rsv_nexus.initid.id)
5267 		 || (ctsio->io_hdr.nexus.targ_port != lun->rsv_nexus.targ_port)
5268 		 || (ctsio->io_hdr.nexus.targ_target.id !=
5269 		     lun->rsv_nexus.targ_target.id)) {
5270 			ctsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
5271 			ctsio->io_hdr.status = CTL_SCSI_ERROR;
5272 			goto bailout;
5273 		}
5274 	}
5275 
5276 	lun->flags |= CTL_LUN_RESERVED;
5277 	lun->rsv_nexus = ctsio->io_hdr.nexus;
5278 
5279 	ctsio->scsi_status = SCSI_STATUS_OK;
5280 	ctsio->io_hdr.status = CTL_SUCCESS;
5281 
5282 bailout:
5283 	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5284 		free(ctsio->kern_data_ptr, M_CTL);
5285 		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5286 	}
5287 
5288 	mtx_unlock(&ctl_softc->ctl_lock);
5289 
5290 	ctl_done((union ctl_io *)ctsio);
5291 	return (CTL_RETVAL_COMPLETE);
5292 }
5293 
5294 int
5295 ctl_start_stop(struct ctl_scsiio *ctsio)
5296 {
5297 	struct scsi_start_stop_unit *cdb;
5298 	struct ctl_lun *lun;
5299 	struct ctl_softc *ctl_softc;
5300 	int retval;
5301 
5302 	CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5303 
5304 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5305 	ctl_softc = control_softc;
5306 	retval = 0;
5307 
5308 	cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5309 
5310 	/*
5311 	 * XXX KDM
5312 	 * We don't support the immediate bit on a stop unit.  In order to
5313 	 * do that, we would need to code up a way to know that a stop is
5314 	 * pending, and hold off any new commands until it completes, one
5315 	 * way or another.  Then we could accept or reject those commands
5316 	 * depending on its status.  We would almost need to do the reverse
5317 	 * of what we do below for an immediate start -- return the copy of
5318 	 * the ctl_io to the FETD with status to send to the host (and to
5319 	 * free the copy!) and then free the original I/O once the stop
5320 	 * actually completes.  That way, the OOA queue mechanism can work
5321 	 * to block commands that shouldn't proceed.  Another alternative
5322 	 * would be to put the copy in the queue in place of the original,
5323 	 * and return the original back to the caller.  That could be
5324 	 * slightly safer..
5325 	 */
5326 	if ((cdb->byte2 & SSS_IMMED)
5327 	 && ((cdb->how & SSS_START) == 0)) {
5328 		ctl_set_invalid_field(ctsio,
5329 				      /*sks_valid*/ 1,
5330 				      /*command*/ 1,
5331 				      /*field*/ 1,
5332 				      /*bit_valid*/ 1,
5333 				      /*bit*/ 0);
5334 		ctl_done((union ctl_io *)ctsio);
5335 		return (CTL_RETVAL_COMPLETE);
5336 	}
5337 
5338 	/*
5339 	 * We don't support the power conditions field.  We need to check
5340 	 * this prior to checking the load/eject and start/stop bits.
5341 	 */
5342 	if ((cdb->how & SSS_PC_MASK) != SSS_PC_START_VALID) {
5343 		ctl_set_invalid_field(ctsio,
5344 				      /*sks_valid*/ 1,
5345 				      /*command*/ 1,
5346 				      /*field*/ 4,
5347 				      /*bit_valid*/ 1,
5348 				      /*bit*/ 4);
5349 		ctl_done((union ctl_io *)ctsio);
5350 		return (CTL_RETVAL_COMPLETE);
5351 	}
5352 
5353 	/*
5354 	 * Media isn't removable, so we can't load or eject it.
5355 	 */
5356 	if ((cdb->how & SSS_LOEJ) != 0) {
5357 		ctl_set_invalid_field(ctsio,
5358 				      /*sks_valid*/ 1,
5359 				      /*command*/ 1,
5360 				      /*field*/ 4,
5361 				      /*bit_valid*/ 1,
5362 				      /*bit*/ 1);
5363 		ctl_done((union ctl_io *)ctsio);
5364 		return (CTL_RETVAL_COMPLETE);
5365 	}
5366 
5367 	if ((lun->flags & CTL_LUN_PR_RESERVED)
5368 	 && ((cdb->how & SSS_START)==0)) {
5369 		uint32_t residx;
5370 
5371 		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5372 		if (!lun->per_res[residx].registered
5373 		 || (lun->pr_res_idx!=residx && lun->res_type < 4)) {
5374 
5375 			ctl_set_reservation_conflict(ctsio);
5376 			ctl_done((union ctl_io *)ctsio);
5377 			return (CTL_RETVAL_COMPLETE);
5378 		}
5379 	}
5380 
5381 	/*
5382 	 * If there is no backend on this device, we can't start or stop
5383 	 * it.  In theory we shouldn't get any start/stop commands in the
5384 	 * first place at this level if the LUN doesn't have a backend.
5385 	 * That should get stopped by the command decode code.
5386 	 */
5387 	if (lun->backend == NULL) {
5388 		ctl_set_invalid_opcode(ctsio);
5389 		ctl_done((union ctl_io *)ctsio);
5390 		return (CTL_RETVAL_COMPLETE);
5391 	}
5392 
5393 	/*
5394 	 * XXX KDM Copan-specific offline behavior.
5395 	 * Figure out a reasonable way to port this?
5396 	 */
5397 #ifdef NEEDTOPORT
5398 	mtx_lock(&ctl_softc->ctl_lock);
5399 
5400 	if (((cdb->byte2 & SSS_ONOFFLINE) == 0)
5401 	 && (lun->flags & CTL_LUN_OFFLINE)) {
5402 		/*
5403 		 * If the LUN is offline, and the on/offline bit isn't set,
5404 		 * reject the start or stop.  Otherwise, let it through.
5405 		 */
5406 		mtx_unlock(&ctl_softc->ctl_lock);
5407 		ctl_set_lun_not_ready(ctsio);
5408 		ctl_done((union ctl_io *)ctsio);
5409 	} else {
5410 		mtx_unlock(&ctl_softc->ctl_lock);
5411 #endif /* NEEDTOPORT */
5412 		/*
5413 		 * This could be a start or a stop when we're online,
5414 		 * or a stop/offline or start/online.  A start or stop when
5415 		 * we're offline is covered in the case above.
5416 		 */
5417 		/*
5418 		 * In the non-immediate case, we send the request to
5419 		 * the backend and return status to the user when
5420 		 * it is done.
5421 		 *
5422 		 * In the immediate case, we allocate a new ctl_io
5423 		 * to hold a copy of the request, and send that to
5424 		 * the backend.  We then set good status on the
5425 		 * user's request and return it immediately.
5426 		 */
5427 		if (cdb->byte2 & SSS_IMMED) {
5428 			union ctl_io *new_io;
5429 
5430 			new_io = ctl_alloc_io(ctsio->io_hdr.pool);
5431 			if (new_io == NULL) {
5432 				ctl_set_busy(ctsio);
5433 				ctl_done((union ctl_io *)ctsio);
5434 			} else {
5435 				ctl_copy_io((union ctl_io *)ctsio,
5436 					    new_io);
5437 				retval = lun->backend->config_write(new_io);
5438 				ctl_set_success(ctsio);
5439 				ctl_done((union ctl_io *)ctsio);
5440 			}
5441 		} else {
5442 			retval = lun->backend->config_write(
5443 				(union ctl_io *)ctsio);
5444 		}
5445 #ifdef NEEDTOPORT
5446 	}
5447 #endif
5448 	return (retval);
5449 }
5450 
5451 /*
5452  * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5453  * we don't really do anything with the LBA and length fields if the user
5454  * passes them in.  Instead we'll just flush out the cache for the entire
5455  * LUN.
5456  */
5457 int
5458 ctl_sync_cache(struct ctl_scsiio *ctsio)
5459 {
5460 	struct ctl_lun *lun;
5461 	struct ctl_softc *ctl_softc;
5462 	uint64_t starting_lba;
5463 	uint32_t block_count;
5464 	int reladr, immed;
5465 	int retval;
5466 
5467 	CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5468 
5469 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5470 	ctl_softc = control_softc;
5471 	retval = 0;
5472 	reladr = 0;
5473 	immed = 0;
5474 
5475 	switch (ctsio->cdb[0]) {
5476 	case SYNCHRONIZE_CACHE: {
5477 		struct scsi_sync_cache *cdb;
5478 		cdb = (struct scsi_sync_cache *)ctsio->cdb;
5479 
5480 		if (cdb->byte2 & SSC_RELADR)
5481 			reladr = 1;
5482 
5483 		if (cdb->byte2 & SSC_IMMED)
5484 			immed = 1;
5485 
5486 		starting_lba = scsi_4btoul(cdb->begin_lba);
5487 		block_count = scsi_2btoul(cdb->lb_count);
5488 		break;
5489 	}
5490 	case SYNCHRONIZE_CACHE_16: {
5491 		struct scsi_sync_cache_16 *cdb;
5492 		cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5493 
5494 		if (cdb->byte2 & SSC_RELADR)
5495 			reladr = 1;
5496 
5497 		if (cdb->byte2 & SSC_IMMED)
5498 			immed = 1;
5499 
5500 		starting_lba = scsi_8btou64(cdb->begin_lba);
5501 		block_count = scsi_4btoul(cdb->lb_count);
5502 		break;
5503 	}
5504 	default:
5505 		ctl_set_invalid_opcode(ctsio);
5506 		ctl_done((union ctl_io *)ctsio);
5507 		goto bailout;
5508 		break; /* NOTREACHED */
5509 	}
5510 
5511 	if (immed) {
5512 		/*
5513 		 * We don't support the immediate bit.  Since it's in the
5514 		 * same place for the 10 and 16 byte SYNCHRONIZE CACHE
5515 		 * commands, we can just return the same error in either
5516 		 * case.
5517 		 */
5518 		ctl_set_invalid_field(ctsio,
5519 				      /*sks_valid*/ 1,
5520 				      /*command*/ 1,
5521 				      /*field*/ 1,
5522 				      /*bit_valid*/ 1,
5523 				      /*bit*/ 1);
5524 		ctl_done((union ctl_io *)ctsio);
5525 		goto bailout;
5526 	}
5527 
5528 	if (reladr) {
5529 		/*
5530 		 * We don't support the reladr bit either.  It can only be
5531 		 * used with linked commands, and we don't support linked
5532 		 * commands.  Since the bit is in the same place for the
5533 		 * 10 and 16 byte SYNCHRONIZE CACHE * commands, we can
5534 		 * just return the same error in either case.
5535 		 */
5536 		ctl_set_invalid_field(ctsio,
5537 				      /*sks_valid*/ 1,
5538 				      /*command*/ 1,
5539 				      /*field*/ 1,
5540 				      /*bit_valid*/ 1,
5541 				      /*bit*/ 0);
5542 		ctl_done((union ctl_io *)ctsio);
5543 		goto bailout;
5544 	}
5545 
5546 	/*
5547 	 * We check the LBA and length, but don't do anything with them.
5548 	 * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5549 	 * get flushed.  This check will just help satisfy anyone who wants
5550 	 * to see an error for an out of range LBA.
5551 	 */
5552 	if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5553 		ctl_set_lba_out_of_range(ctsio);
5554 		ctl_done((union ctl_io *)ctsio);
5555 		goto bailout;
5556 	}
5557 
5558 	/*
5559 	 * If this LUN has no backend, we can't flush the cache anyway.
5560 	 */
5561 	if (lun->backend == NULL) {
5562 		ctl_set_invalid_opcode(ctsio);
5563 		ctl_done((union ctl_io *)ctsio);
5564 		goto bailout;
5565 	}
5566 
5567 	/*
5568 	 * Check to see whether we're configured to send the SYNCHRONIZE
5569 	 * CACHE command directly to the back end.
5570 	 */
5571 	mtx_lock(&ctl_softc->ctl_lock);
5572 	if ((ctl_softc->flags & CTL_FLAG_REAL_SYNC)
5573 	 && (++(lun->sync_count) >= lun->sync_interval)) {
5574 		lun->sync_count = 0;
5575 		mtx_unlock(&ctl_softc->ctl_lock);
5576 		retval = lun->backend->config_write((union ctl_io *)ctsio);
5577 	} else {
5578 		mtx_unlock(&ctl_softc->ctl_lock);
5579 		ctl_set_success(ctsio);
5580 		ctl_done((union ctl_io *)ctsio);
5581 	}
5582 
5583 bailout:
5584 
5585 	return (retval);
5586 }
5587 
5588 int
5589 ctl_format(struct ctl_scsiio *ctsio)
5590 {
5591 	struct scsi_format *cdb;
5592 	struct ctl_lun *lun;
5593 	struct ctl_softc *ctl_softc;
5594 	int length, defect_list_len;
5595 
5596 	CTL_DEBUG_PRINT(("ctl_format\n"));
5597 
5598 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5599 	ctl_softc = control_softc;
5600 
5601 	cdb = (struct scsi_format *)ctsio->cdb;
5602 
5603 	length = 0;
5604 	if (cdb->byte2 & SF_FMTDATA) {
5605 		if (cdb->byte2 & SF_LONGLIST)
5606 			length = sizeof(struct scsi_format_header_long);
5607 		else
5608 			length = sizeof(struct scsi_format_header_short);
5609 	}
5610 
5611 	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5612 	 && (length > 0)) {
5613 		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5614 		ctsio->kern_data_len = length;
5615 		ctsio->kern_total_len = length;
5616 		ctsio->kern_data_resid = 0;
5617 		ctsio->kern_rel_offset = 0;
5618 		ctsio->kern_sg_entries = 0;
5619 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5620 		ctsio->be_move_done = ctl_config_move_done;
5621 		ctl_datamove((union ctl_io *)ctsio);
5622 
5623 		return (CTL_RETVAL_COMPLETE);
5624 	}
5625 
5626 	defect_list_len = 0;
5627 
5628 	if (cdb->byte2 & SF_FMTDATA) {
5629 		if (cdb->byte2 & SF_LONGLIST) {
5630 			struct scsi_format_header_long *header;
5631 
5632 			header = (struct scsi_format_header_long *)
5633 				ctsio->kern_data_ptr;
5634 
5635 			defect_list_len = scsi_4btoul(header->defect_list_len);
5636 			if (defect_list_len != 0) {
5637 				ctl_set_invalid_field(ctsio,
5638 						      /*sks_valid*/ 1,
5639 						      /*command*/ 0,
5640 						      /*field*/ 2,
5641 						      /*bit_valid*/ 0,
5642 						      /*bit*/ 0);
5643 				goto bailout;
5644 			}
5645 		} else {
5646 			struct scsi_format_header_short *header;
5647 
5648 			header = (struct scsi_format_header_short *)
5649 				ctsio->kern_data_ptr;
5650 
5651 			defect_list_len = scsi_2btoul(header->defect_list_len);
5652 			if (defect_list_len != 0) {
5653 				ctl_set_invalid_field(ctsio,
5654 						      /*sks_valid*/ 1,
5655 						      /*command*/ 0,
5656 						      /*field*/ 2,
5657 						      /*bit_valid*/ 0,
5658 						      /*bit*/ 0);
5659 				goto bailout;
5660 			}
5661 		}
5662 	}
5663 
5664 	/*
5665 	 * The format command will clear out the "Medium format corrupted"
5666 	 * status if set by the configuration code.  That status is really
5667 	 * just a way to notify the host that we have lost the media, and
5668 	 * get them to issue a command that will basically make them think
5669 	 * they're blowing away the media.
5670 	 */
5671 	mtx_lock(&ctl_softc->ctl_lock);
5672 	lun->flags &= ~CTL_LUN_INOPERABLE;
5673 	mtx_unlock(&ctl_softc->ctl_lock);
5674 
5675 	ctsio->scsi_status = SCSI_STATUS_OK;
5676 	ctsio->io_hdr.status = CTL_SUCCESS;
5677 bailout:
5678 
5679 	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5680 		free(ctsio->kern_data_ptr, M_CTL);
5681 		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5682 	}
5683 
5684 	ctl_done((union ctl_io *)ctsio);
5685 	return (CTL_RETVAL_COMPLETE);
5686 }
5687 
5688 int
5689 ctl_write_buffer(struct ctl_scsiio *ctsio)
5690 {
5691 	struct scsi_write_buffer *cdb;
5692 	struct copan_page_header *header;
5693 	struct ctl_lun *lun;
5694 	struct ctl_softc *ctl_softc;
5695 	int buffer_offset, len;
5696 	int retval;
5697 
5698 	header = NULL;
5699 
5700 	retval = CTL_RETVAL_COMPLETE;
5701 
5702 	CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5703 
5704 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5705 	ctl_softc = control_softc;
5706 	cdb = (struct scsi_write_buffer *)ctsio->cdb;
5707 
5708 	if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA) {
5709 		ctl_set_invalid_field(ctsio,
5710 				      /*sks_valid*/ 1,
5711 				      /*command*/ 1,
5712 				      /*field*/ 1,
5713 				      /*bit_valid*/ 1,
5714 				      /*bit*/ 4);
5715 		ctl_done((union ctl_io *)ctsio);
5716 		return (CTL_RETVAL_COMPLETE);
5717 	}
5718 	if (cdb->buffer_id != 0) {
5719 		ctl_set_invalid_field(ctsio,
5720 				      /*sks_valid*/ 1,
5721 				      /*command*/ 1,
5722 				      /*field*/ 2,
5723 				      /*bit_valid*/ 0,
5724 				      /*bit*/ 0);
5725 		ctl_done((union ctl_io *)ctsio);
5726 		return (CTL_RETVAL_COMPLETE);
5727 	}
5728 
5729 	len = scsi_3btoul(cdb->length);
5730 	buffer_offset = scsi_3btoul(cdb->offset);
5731 
5732 	if (len > sizeof(lun->write_buffer)) {
5733 		ctl_set_invalid_field(ctsio,
5734 				      /*sks_valid*/ 1,
5735 				      /*command*/ 1,
5736 				      /*field*/ 6,
5737 				      /*bit_valid*/ 0,
5738 				      /*bit*/ 0);
5739 		ctl_done((union ctl_io *)ctsio);
5740 		return (CTL_RETVAL_COMPLETE);
5741 	}
5742 
5743 	if (buffer_offset != 0) {
5744 		ctl_set_invalid_field(ctsio,
5745 				      /*sks_valid*/ 1,
5746 				      /*command*/ 1,
5747 				      /*field*/ 3,
5748 				      /*bit_valid*/ 0,
5749 				      /*bit*/ 0);
5750 		ctl_done((union ctl_io *)ctsio);
5751 		return (CTL_RETVAL_COMPLETE);
5752 	}
5753 
5754 	/*
5755 	 * If we've got a kernel request that hasn't been malloced yet,
5756 	 * malloc it and tell the caller the data buffer is here.
5757 	 */
5758 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5759 		ctsio->kern_data_ptr = lun->write_buffer;
5760 		ctsio->kern_data_len = len;
5761 		ctsio->kern_total_len = len;
5762 		ctsio->kern_data_resid = 0;
5763 		ctsio->kern_rel_offset = 0;
5764 		ctsio->kern_sg_entries = 0;
5765 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5766 		ctsio->be_move_done = ctl_config_move_done;
5767 		ctl_datamove((union ctl_io *)ctsio);
5768 
5769 		return (CTL_RETVAL_COMPLETE);
5770 	}
5771 
5772 	ctl_done((union ctl_io *)ctsio);
5773 
5774 	return (CTL_RETVAL_COMPLETE);
5775 }
5776 
5777 /*
5778  * Note that this function currently doesn't actually do anything inside
5779  * CTL to enforce things if the DQue bit is turned on.
5780  *
5781  * Also note that this function can't be used in the default case, because
5782  * the DQue bit isn't set in the changeable mask for the control mode page
5783  * anyway.  This is just here as an example for how to implement a page
5784  * handler, and a placeholder in case we want to allow the user to turn
5785  * tagged queueing on and off.
5786  *
5787  * The D_SENSE bit handling is functional, however, and will turn
5788  * descriptor sense on and off for a given LUN.
5789  */
5790 int
5791 ctl_control_page_handler(struct ctl_scsiio *ctsio,
5792 			 struct ctl_page_index *page_index, uint8_t *page_ptr)
5793 {
5794 	struct scsi_control_page *current_cp, *saved_cp, *user_cp;
5795 	struct ctl_lun *lun;
5796 	struct ctl_softc *softc;
5797 	int set_ua;
5798 	uint32_t initidx;
5799 
5800 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5801 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5802 	set_ua = 0;
5803 
5804 	user_cp = (struct scsi_control_page *)page_ptr;
5805 	current_cp = (struct scsi_control_page *)
5806 		(page_index->page_data + (page_index->page_len *
5807 		CTL_PAGE_CURRENT));
5808 	saved_cp = (struct scsi_control_page *)
5809 		(page_index->page_data + (page_index->page_len *
5810 		CTL_PAGE_SAVED));
5811 
5812 	softc = control_softc;
5813 
5814 	mtx_lock(&softc->ctl_lock);
5815 	if (((current_cp->rlec & SCP_DSENSE) == 0)
5816 	 && ((user_cp->rlec & SCP_DSENSE) != 0)) {
5817 		/*
5818 		 * Descriptor sense is currently turned off and the user
5819 		 * wants to turn it on.
5820 		 */
5821 		current_cp->rlec |= SCP_DSENSE;
5822 		saved_cp->rlec |= SCP_DSENSE;
5823 		lun->flags |= CTL_LUN_SENSE_DESC;
5824 		set_ua = 1;
5825 	} else if (((current_cp->rlec & SCP_DSENSE) != 0)
5826 		&& ((user_cp->rlec & SCP_DSENSE) == 0)) {
5827 		/*
5828 		 * Descriptor sense is currently turned on, and the user
5829 		 * wants to turn it off.
5830 		 */
5831 		current_cp->rlec &= ~SCP_DSENSE;
5832 		saved_cp->rlec &= ~SCP_DSENSE;
5833 		lun->flags &= ~CTL_LUN_SENSE_DESC;
5834 		set_ua = 1;
5835 	}
5836 	if (current_cp->queue_flags & SCP_QUEUE_DQUE) {
5837 		if (user_cp->queue_flags & SCP_QUEUE_DQUE) {
5838 #ifdef NEEDTOPORT
5839 			csevent_log(CSC_CTL | CSC_SHELF_SW |
5840 				    CTL_UNTAG_TO_UNTAG,
5841 				    csevent_LogType_Trace,
5842 				    csevent_Severity_Information,
5843 				    csevent_AlertLevel_Green,
5844 				    csevent_FRU_Firmware,
5845 				    csevent_FRU_Unknown,
5846 				    "Received untagged to untagged transition");
5847 #endif /* NEEDTOPORT */
5848 		} else {
5849 #ifdef NEEDTOPORT
5850 			csevent_log(CSC_CTL | CSC_SHELF_SW |
5851 				    CTL_UNTAG_TO_TAG,
5852 				    csevent_LogType_ConfigChange,
5853 				    csevent_Severity_Information,
5854 				    csevent_AlertLevel_Green,
5855 				    csevent_FRU_Firmware,
5856 				    csevent_FRU_Unknown,
5857 				    "Received untagged to tagged "
5858 				    "queueing transition");
5859 #endif /* NEEDTOPORT */
5860 
5861 			current_cp->queue_flags &= ~SCP_QUEUE_DQUE;
5862 			saved_cp->queue_flags &= ~SCP_QUEUE_DQUE;
5863 			set_ua = 1;
5864 		}
5865 	} else {
5866 		if (user_cp->queue_flags & SCP_QUEUE_DQUE) {
5867 #ifdef NEEDTOPORT
5868 			csevent_log(CSC_CTL | CSC_SHELF_SW |
5869 				    CTL_TAG_TO_UNTAG,
5870 				    csevent_LogType_ConfigChange,
5871 				    csevent_Severity_Warning,
5872 				    csevent_AlertLevel_Yellow,
5873 				    csevent_FRU_Firmware,
5874 				    csevent_FRU_Unknown,
5875 				    "Received tagged queueing to untagged "
5876 				    "transition");
5877 #endif /* NEEDTOPORT */
5878 
5879 			current_cp->queue_flags |= SCP_QUEUE_DQUE;
5880 			saved_cp->queue_flags |= SCP_QUEUE_DQUE;
5881 			set_ua = 1;
5882 		} else {
5883 #ifdef NEEDTOPORT
5884 			csevent_log(CSC_CTL | CSC_SHELF_SW |
5885 				    CTL_TAG_TO_TAG,
5886 				    csevent_LogType_Trace,
5887 				    csevent_Severity_Information,
5888 				    csevent_AlertLevel_Green,
5889 				    csevent_FRU_Firmware,
5890 				    csevent_FRU_Unknown,
5891 				    "Received tagged queueing to tagged "
5892 				    "queueing transition");
5893 #endif /* NEEDTOPORT */
5894 		}
5895 	}
5896 	if (set_ua != 0) {
5897 		int i;
5898 		/*
5899 		 * Let other initiators know that the mode
5900 		 * parameters for this LUN have changed.
5901 		 */
5902 		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
5903 			if (i == initidx)
5904 				continue;
5905 
5906 			lun->pending_sense[i].ua_pending |=
5907 				CTL_UA_MODE_CHANGE;
5908 		}
5909 	}
5910 	mtx_unlock(&softc->ctl_lock);
5911 
5912 	return (0);
5913 }
5914 
5915 int
5916 ctl_power_sp_handler(struct ctl_scsiio *ctsio,
5917 		     struct ctl_page_index *page_index, uint8_t *page_ptr)
5918 {
5919 	return (0);
5920 }
5921 
5922 int
5923 ctl_power_sp_sense_handler(struct ctl_scsiio *ctsio,
5924 			   struct ctl_page_index *page_index, int pc)
5925 {
5926 	struct copan_power_subpage *page;
5927 
5928 	page = (struct copan_power_subpage *)page_index->page_data +
5929 		(page_index->page_len * pc);
5930 
5931 	switch (pc) {
5932 	case SMS_PAGE_CTRL_CHANGEABLE >> 6:
5933 		/*
5934 		 * We don't update the changable bits for this page.
5935 		 */
5936 		break;
5937 	case SMS_PAGE_CTRL_CURRENT >> 6:
5938 	case SMS_PAGE_CTRL_DEFAULT >> 6:
5939 	case SMS_PAGE_CTRL_SAVED >> 6:
5940 #ifdef NEEDTOPORT
5941 		ctl_update_power_subpage(page);
5942 #endif
5943 		break;
5944 	default:
5945 #ifdef NEEDTOPORT
5946 		EPRINT(0, "Invalid PC %d!!", pc);
5947 #endif
5948 		break;
5949 	}
5950 	return (0);
5951 }
5952 
5953 
5954 int
5955 ctl_aps_sp_handler(struct ctl_scsiio *ctsio,
5956 		   struct ctl_page_index *page_index, uint8_t *page_ptr)
5957 {
5958 	struct copan_aps_subpage *user_sp;
5959 	struct copan_aps_subpage *current_sp;
5960 	union ctl_modepage_info *modepage_info;
5961 	struct ctl_softc *softc;
5962 	struct ctl_lun *lun;
5963 	int retval;
5964 
5965 	retval = CTL_RETVAL_COMPLETE;
5966 	current_sp = (struct copan_aps_subpage *)(page_index->page_data +
5967 		     (page_index->page_len * CTL_PAGE_CURRENT));
5968 	softc = control_softc;
5969 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5970 
5971 	user_sp = (struct copan_aps_subpage *)page_ptr;
5972 
5973 	modepage_info = (union ctl_modepage_info *)
5974 		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
5975 
5976 	modepage_info->header.page_code = page_index->page_code & SMPH_PC_MASK;
5977 	modepage_info->header.subpage = page_index->subpage;
5978 	modepage_info->aps.lock_active = user_sp->lock_active;
5979 
5980 	mtx_lock(&softc->ctl_lock);
5981 
5982 	/*
5983 	 * If there is a request to lock the LUN and another LUN is locked
5984 	 * this is an error. If the requested LUN is already locked ignore
5985 	 * the request. If no LUN is locked attempt to lock it.
5986 	 * if there is a request to unlock the LUN and the LUN is currently
5987 	 * locked attempt to unlock it. Otherwise ignore the request. i.e.
5988 	 * if another LUN is locked or no LUN is locked.
5989 	 */
5990 	if (user_sp->lock_active & APS_LOCK_ACTIVE) {
5991 		if (softc->aps_locked_lun == lun->lun) {
5992 			/*
5993 			 * This LUN is already locked, so we're done.
5994 			 */
5995 			retval = CTL_RETVAL_COMPLETE;
5996 		} else if (softc->aps_locked_lun == 0) {
5997 			/*
5998 			 * No one has the lock, pass the request to the
5999 			 * backend.
6000 			 */
6001 			retval = lun->backend->config_write(
6002 				(union ctl_io *)ctsio);
6003 		} else {
6004 			/*
6005 			 * Someone else has the lock, throw out the request.
6006 			 */
6007 			ctl_set_already_locked(ctsio);
6008 			free(ctsio->kern_data_ptr, M_CTL);
6009 			ctl_done((union ctl_io *)ctsio);
6010 
6011 			/*
6012 			 * Set the return value so that ctl_do_mode_select()
6013 			 * won't try to complete the command.  We already
6014 			 * completed it here.
6015 			 */
6016 			retval = CTL_RETVAL_ERROR;
6017 		}
6018 	} else if (softc->aps_locked_lun == lun->lun) {
6019 		/*
6020 		 * This LUN is locked, so pass the unlock request to the
6021 		 * backend.
6022 		 */
6023 		retval = lun->backend->config_write((union ctl_io *)ctsio);
6024 	}
6025 	mtx_unlock(&softc->ctl_lock);
6026 
6027 	return (retval);
6028 }
6029 
6030 int
6031 ctl_debugconf_sp_select_handler(struct ctl_scsiio *ctsio,
6032 				struct ctl_page_index *page_index,
6033 				uint8_t *page_ptr)
6034 {
6035 	uint8_t *c;
6036 	int i;
6037 
6038 	c = ((struct copan_debugconf_subpage *)page_ptr)->ctl_time_io_secs;
6039 	ctl_time_io_secs =
6040 		(c[0] << 8) |
6041 		(c[1] << 0) |
6042 		0;
6043 	CTL_DEBUG_PRINT(("set ctl_time_io_secs to %d\n", ctl_time_io_secs));
6044 	printf("set ctl_time_io_secs to %d\n", ctl_time_io_secs);
6045 	printf("page data:");
6046 	for (i=0; i<8; i++)
6047 		printf(" %.2x",page_ptr[i]);
6048 	printf("\n");
6049 	return (0);
6050 }
6051 
6052 int
6053 ctl_debugconf_sp_sense_handler(struct ctl_scsiio *ctsio,
6054 			       struct ctl_page_index *page_index,
6055 			       int pc)
6056 {
6057 	struct copan_debugconf_subpage *page;
6058 
6059 	page = (struct copan_debugconf_subpage *)page_index->page_data +
6060 		(page_index->page_len * pc);
6061 
6062 	switch (pc) {
6063 	case SMS_PAGE_CTRL_CHANGEABLE >> 6:
6064 	case SMS_PAGE_CTRL_DEFAULT >> 6:
6065 	case SMS_PAGE_CTRL_SAVED >> 6:
6066 		/*
6067 		 * We don't update the changable or default bits for this page.
6068 		 */
6069 		break;
6070 	case SMS_PAGE_CTRL_CURRENT >> 6:
6071 		page->ctl_time_io_secs[0] = ctl_time_io_secs >> 8;
6072 		page->ctl_time_io_secs[1] = ctl_time_io_secs >> 0;
6073 		break;
6074 	default:
6075 #ifdef NEEDTOPORT
6076 		EPRINT(0, "Invalid PC %d!!", pc);
6077 #endif /* NEEDTOPORT */
6078 		break;
6079 	}
6080 	return (0);
6081 }
6082 
6083 
6084 static int
6085 ctl_do_mode_select(union ctl_io *io)
6086 {
6087 	struct scsi_mode_page_header *page_header;
6088 	struct ctl_page_index *page_index;
6089 	struct ctl_scsiio *ctsio;
6090 	int control_dev, page_len;
6091 	int page_len_offset, page_len_size;
6092 	union ctl_modepage_info *modepage_info;
6093 	struct ctl_lun *lun;
6094 	int *len_left, *len_used;
6095 	int retval, i;
6096 
6097 	ctsio = &io->scsiio;
6098 	page_index = NULL;
6099 	page_len = 0;
6100 	retval = CTL_RETVAL_COMPLETE;
6101 
6102 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6103 
6104 	if (lun->be_lun->lun_type != T_DIRECT)
6105 		control_dev = 1;
6106 	else
6107 		control_dev = 0;
6108 
6109 	modepage_info = (union ctl_modepage_info *)
6110 		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6111 	len_left = &modepage_info->header.len_left;
6112 	len_used = &modepage_info->header.len_used;
6113 
6114 do_next_page:
6115 
6116 	page_header = (struct scsi_mode_page_header *)
6117 		(ctsio->kern_data_ptr + *len_used);
6118 
6119 	if (*len_left == 0) {
6120 		free(ctsio->kern_data_ptr, M_CTL);
6121 		ctl_set_success(ctsio);
6122 		ctl_done((union ctl_io *)ctsio);
6123 		return (CTL_RETVAL_COMPLETE);
6124 	} else if (*len_left < sizeof(struct scsi_mode_page_header)) {
6125 
6126 		free(ctsio->kern_data_ptr, M_CTL);
6127 		ctl_set_param_len_error(ctsio);
6128 		ctl_done((union ctl_io *)ctsio);
6129 		return (CTL_RETVAL_COMPLETE);
6130 
6131 	} else if ((page_header->page_code & SMPH_SPF)
6132 		&& (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
6133 
6134 		free(ctsio->kern_data_ptr, M_CTL);
6135 		ctl_set_param_len_error(ctsio);
6136 		ctl_done((union ctl_io *)ctsio);
6137 		return (CTL_RETVAL_COMPLETE);
6138 	}
6139 
6140 
6141 	/*
6142 	 * XXX KDM should we do something with the block descriptor?
6143 	 */
6144 	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6145 
6146 		if ((control_dev != 0)
6147 		 && (lun->mode_pages.index[i].page_flags &
6148 		     CTL_PAGE_FLAG_DISK_ONLY))
6149 			continue;
6150 
6151 		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
6152 		    (page_header->page_code & SMPH_PC_MASK))
6153 			continue;
6154 
6155 		/*
6156 		 * If neither page has a subpage code, then we've got a
6157 		 * match.
6158 		 */
6159 		if (((lun->mode_pages.index[i].page_code & SMPH_SPF) == 0)
6160 		 && ((page_header->page_code & SMPH_SPF) == 0)) {
6161 			page_index = &lun->mode_pages.index[i];
6162 			page_len = page_header->page_length;
6163 			break;
6164 		}
6165 
6166 		/*
6167 		 * If both pages have subpages, then the subpage numbers
6168 		 * have to match.
6169 		 */
6170 		if ((lun->mode_pages.index[i].page_code & SMPH_SPF)
6171 		  && (page_header->page_code & SMPH_SPF)) {
6172 			struct scsi_mode_page_header_sp *sph;
6173 
6174 			sph = (struct scsi_mode_page_header_sp *)page_header;
6175 
6176 			if (lun->mode_pages.index[i].subpage ==
6177 			    sph->subpage) {
6178 				page_index = &lun->mode_pages.index[i];
6179 				page_len = scsi_2btoul(sph->page_length);
6180 				break;
6181 			}
6182 		}
6183 	}
6184 
6185 	/*
6186 	 * If we couldn't find the page, or if we don't have a mode select
6187 	 * handler for it, send back an error to the user.
6188 	 */
6189 	if ((page_index == NULL)
6190 	 || (page_index->select_handler == NULL)) {
6191 		ctl_set_invalid_field(ctsio,
6192 				      /*sks_valid*/ 1,
6193 				      /*command*/ 0,
6194 				      /*field*/ *len_used,
6195 				      /*bit_valid*/ 0,
6196 				      /*bit*/ 0);
6197 		free(ctsio->kern_data_ptr, M_CTL);
6198 		ctl_done((union ctl_io *)ctsio);
6199 		return (CTL_RETVAL_COMPLETE);
6200 	}
6201 
6202 	if (page_index->page_code & SMPH_SPF) {
6203 		page_len_offset = 2;
6204 		page_len_size = 2;
6205 	} else {
6206 		page_len_size = 1;
6207 		page_len_offset = 1;
6208 	}
6209 
6210 	/*
6211 	 * If the length the initiator gives us isn't the one we specify in
6212 	 * the mode page header, or if they didn't specify enough data in
6213 	 * the CDB to avoid truncating this page, kick out the request.
6214 	 */
6215 	if ((page_len != (page_index->page_len - page_len_offset -
6216 			  page_len_size))
6217 	 || (*len_left < page_index->page_len)) {
6218 
6219 
6220 		ctl_set_invalid_field(ctsio,
6221 				      /*sks_valid*/ 1,
6222 				      /*command*/ 0,
6223 				      /*field*/ *len_used + page_len_offset,
6224 				      /*bit_valid*/ 0,
6225 				      /*bit*/ 0);
6226 		free(ctsio->kern_data_ptr, M_CTL);
6227 		ctl_done((union ctl_io *)ctsio);
6228 		return (CTL_RETVAL_COMPLETE);
6229 	}
6230 
6231 	/*
6232 	 * Run through the mode page, checking to make sure that the bits
6233 	 * the user changed are actually legal for him to change.
6234 	 */
6235 	for (i = 0; i < page_index->page_len; i++) {
6236 		uint8_t *user_byte, *change_mask, *current_byte;
6237 		int bad_bit;
6238 		int j;
6239 
6240 		user_byte = (uint8_t *)page_header + i;
6241 		change_mask = page_index->page_data +
6242 			      (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6243 		current_byte = page_index->page_data +
6244 			       (page_index->page_len * CTL_PAGE_CURRENT) + i;
6245 
6246 		/*
6247 		 * Check to see whether the user set any bits in this byte
6248 		 * that he is not allowed to set.
6249 		 */
6250 		if ((*user_byte & ~(*change_mask)) ==
6251 		    (*current_byte & ~(*change_mask)))
6252 			continue;
6253 
6254 		/*
6255 		 * Go through bit by bit to determine which one is illegal.
6256 		 */
6257 		bad_bit = 0;
6258 		for (j = 7; j >= 0; j--) {
6259 			if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6260 			    (((1 << i) & ~(*change_mask)) & *current_byte)) {
6261 				bad_bit = i;
6262 				break;
6263 			}
6264 		}
6265 		ctl_set_invalid_field(ctsio,
6266 				      /*sks_valid*/ 1,
6267 				      /*command*/ 0,
6268 				      /*field*/ *len_used + i,
6269 				      /*bit_valid*/ 1,
6270 				      /*bit*/ bad_bit);
6271 		free(ctsio->kern_data_ptr, M_CTL);
6272 		ctl_done((union ctl_io *)ctsio);
6273 		return (CTL_RETVAL_COMPLETE);
6274 	}
6275 
6276 	/*
6277 	 * Decrement these before we call the page handler, since we may
6278 	 * end up getting called back one way or another before the handler
6279 	 * returns to this context.
6280 	 */
6281 	*len_left -= page_index->page_len;
6282 	*len_used += page_index->page_len;
6283 
6284 	retval = page_index->select_handler(ctsio, page_index,
6285 					    (uint8_t *)page_header);
6286 
6287 	/*
6288 	 * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6289 	 * wait until this queued command completes to finish processing
6290 	 * the mode page.  If it returns anything other than
6291 	 * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6292 	 * already set the sense information, freed the data pointer, and
6293 	 * completed the io for us.
6294 	 */
6295 	if (retval != CTL_RETVAL_COMPLETE)
6296 		goto bailout_no_done;
6297 
6298 	/*
6299 	 * If the initiator sent us more than one page, parse the next one.
6300 	 */
6301 	if (*len_left > 0)
6302 		goto do_next_page;
6303 
6304 	ctl_set_success(ctsio);
6305 	free(ctsio->kern_data_ptr, M_CTL);
6306 	ctl_done((union ctl_io *)ctsio);
6307 
6308 bailout_no_done:
6309 
6310 	return (CTL_RETVAL_COMPLETE);
6311 
6312 }
6313 
6314 int
6315 ctl_mode_select(struct ctl_scsiio *ctsio)
6316 {
6317 	int param_len, pf, sp;
6318 	int header_size, bd_len;
6319 	int len_left, len_used;
6320 	struct ctl_page_index *page_index;
6321 	struct ctl_lun *lun;
6322 	int control_dev, page_len;
6323 	union ctl_modepage_info *modepage_info;
6324 	int retval;
6325 
6326 	pf = 0;
6327 	sp = 0;
6328 	page_len = 0;
6329 	len_used = 0;
6330 	len_left = 0;
6331 	retval = 0;
6332 	bd_len = 0;
6333 	page_index = NULL;
6334 
6335 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6336 
6337 	if (lun->be_lun->lun_type != T_DIRECT)
6338 		control_dev = 1;
6339 	else
6340 		control_dev = 0;
6341 
6342 	switch (ctsio->cdb[0]) {
6343 	case MODE_SELECT_6: {
6344 		struct scsi_mode_select_6 *cdb;
6345 
6346 		cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6347 
6348 		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6349 		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6350 
6351 		param_len = cdb->length;
6352 		header_size = sizeof(struct scsi_mode_header_6);
6353 		break;
6354 	}
6355 	case MODE_SELECT_10: {
6356 		struct scsi_mode_select_10 *cdb;
6357 
6358 		cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6359 
6360 		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6361 		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6362 
6363 		param_len = scsi_2btoul(cdb->length);
6364 		header_size = sizeof(struct scsi_mode_header_10);
6365 		break;
6366 	}
6367 	default:
6368 		ctl_set_invalid_opcode(ctsio);
6369 		ctl_done((union ctl_io *)ctsio);
6370 		return (CTL_RETVAL_COMPLETE);
6371 		break; /* NOTREACHED */
6372 	}
6373 
6374 	/*
6375 	 * From SPC-3:
6376 	 * "A parameter list length of zero indicates that the Data-Out Buffer
6377 	 * shall be empty. This condition shall not be considered as an error."
6378 	 */
6379 	if (param_len == 0) {
6380 		ctl_set_success(ctsio);
6381 		ctl_done((union ctl_io *)ctsio);
6382 		return (CTL_RETVAL_COMPLETE);
6383 	}
6384 
6385 	/*
6386 	 * Since we'll hit this the first time through, prior to
6387 	 * allocation, we don't need to free a data buffer here.
6388 	 */
6389 	if (param_len < header_size) {
6390 		ctl_set_param_len_error(ctsio);
6391 		ctl_done((union ctl_io *)ctsio);
6392 		return (CTL_RETVAL_COMPLETE);
6393 	}
6394 
6395 	/*
6396 	 * Allocate the data buffer and grab the user's data.  In theory,
6397 	 * we shouldn't have to sanity check the parameter list length here
6398 	 * because the maximum size is 64K.  We should be able to malloc
6399 	 * that much without too many problems.
6400 	 */
6401 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6402 		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6403 		ctsio->kern_data_len = param_len;
6404 		ctsio->kern_total_len = param_len;
6405 		ctsio->kern_data_resid = 0;
6406 		ctsio->kern_rel_offset = 0;
6407 		ctsio->kern_sg_entries = 0;
6408 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6409 		ctsio->be_move_done = ctl_config_move_done;
6410 		ctl_datamove((union ctl_io *)ctsio);
6411 
6412 		return (CTL_RETVAL_COMPLETE);
6413 	}
6414 
6415 	switch (ctsio->cdb[0]) {
6416 	case MODE_SELECT_6: {
6417 		struct scsi_mode_header_6 *mh6;
6418 
6419 		mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6420 		bd_len = mh6->blk_desc_len;
6421 		break;
6422 	}
6423 	case MODE_SELECT_10: {
6424 		struct scsi_mode_header_10 *mh10;
6425 
6426 		mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6427 		bd_len = scsi_2btoul(mh10->blk_desc_len);
6428 		break;
6429 	}
6430 	default:
6431 		panic("Invalid CDB type %#x", ctsio->cdb[0]);
6432 		break;
6433 	}
6434 
6435 	if (param_len < (header_size + bd_len)) {
6436 		free(ctsio->kern_data_ptr, M_CTL);
6437 		ctl_set_param_len_error(ctsio);
6438 		ctl_done((union ctl_io *)ctsio);
6439 		return (CTL_RETVAL_COMPLETE);
6440 	}
6441 
6442 	/*
6443 	 * Set the IO_CONT flag, so that if this I/O gets passed to
6444 	 * ctl_config_write_done(), it'll get passed back to
6445 	 * ctl_do_mode_select() for further processing, or completion if
6446 	 * we're all done.
6447 	 */
6448 	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6449 	ctsio->io_cont = ctl_do_mode_select;
6450 
6451 	modepage_info = (union ctl_modepage_info *)
6452 		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6453 
6454 	memset(modepage_info, 0, sizeof(*modepage_info));
6455 
6456 	len_left = param_len - header_size - bd_len;
6457 	len_used = header_size + bd_len;
6458 
6459 	modepage_info->header.len_left = len_left;
6460 	modepage_info->header.len_used = len_used;
6461 
6462 	return (ctl_do_mode_select((union ctl_io *)ctsio));
6463 }
6464 
6465 int
6466 ctl_mode_sense(struct ctl_scsiio *ctsio)
6467 {
6468 	struct ctl_lun *lun;
6469 	int pc, page_code, dbd, llba, subpage;
6470 	int alloc_len, page_len, header_len, total_len;
6471 	struct scsi_mode_block_descr *block_desc;
6472 	struct ctl_page_index *page_index;
6473 	int control_dev;
6474 
6475 	dbd = 0;
6476 	llba = 0;
6477 	block_desc = NULL;
6478 	page_index = NULL;
6479 
6480 	CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6481 
6482 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6483 
6484 	if (lun->be_lun->lun_type != T_DIRECT)
6485 		control_dev = 1;
6486 	else
6487 		control_dev = 0;
6488 
6489 	switch (ctsio->cdb[0]) {
6490 	case MODE_SENSE_6: {
6491 		struct scsi_mode_sense_6 *cdb;
6492 
6493 		cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6494 
6495 		header_len = sizeof(struct scsi_mode_hdr_6);
6496 		if (cdb->byte2 & SMS_DBD)
6497 			dbd = 1;
6498 		else
6499 			header_len += sizeof(struct scsi_mode_block_descr);
6500 
6501 		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6502 		page_code = cdb->page & SMS_PAGE_CODE;
6503 		subpage = cdb->subpage;
6504 		alloc_len = cdb->length;
6505 		break;
6506 	}
6507 	case MODE_SENSE_10: {
6508 		struct scsi_mode_sense_10 *cdb;
6509 
6510 		cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6511 
6512 		header_len = sizeof(struct scsi_mode_hdr_10);
6513 
6514 		if (cdb->byte2 & SMS_DBD)
6515 			dbd = 1;
6516 		else
6517 			header_len += sizeof(struct scsi_mode_block_descr);
6518 		if (cdb->byte2 & SMS10_LLBAA)
6519 			llba = 1;
6520 		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6521 		page_code = cdb->page & SMS_PAGE_CODE;
6522 		subpage = cdb->subpage;
6523 		alloc_len = scsi_2btoul(cdb->length);
6524 		break;
6525 	}
6526 	default:
6527 		ctl_set_invalid_opcode(ctsio);
6528 		ctl_done((union ctl_io *)ctsio);
6529 		return (CTL_RETVAL_COMPLETE);
6530 		break; /* NOTREACHED */
6531 	}
6532 
6533 	/*
6534 	 * We have to make a first pass through to calculate the size of
6535 	 * the pages that match the user's query.  Then we allocate enough
6536 	 * memory to hold it, and actually copy the data into the buffer.
6537 	 */
6538 	switch (page_code) {
6539 	case SMS_ALL_PAGES_PAGE: {
6540 		int i;
6541 
6542 		page_len = 0;
6543 
6544 		/*
6545 		 * At the moment, values other than 0 and 0xff here are
6546 		 * reserved according to SPC-3.
6547 		 */
6548 		if ((subpage != SMS_SUBPAGE_PAGE_0)
6549 		 && (subpage != SMS_SUBPAGE_ALL)) {
6550 			ctl_set_invalid_field(ctsio,
6551 					      /*sks_valid*/ 1,
6552 					      /*command*/ 1,
6553 					      /*field*/ 3,
6554 					      /*bit_valid*/ 0,
6555 					      /*bit*/ 0);
6556 			ctl_done((union ctl_io *)ctsio);
6557 			return (CTL_RETVAL_COMPLETE);
6558 		}
6559 
6560 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6561 			if ((control_dev != 0)
6562 			 && (lun->mode_pages.index[i].page_flags &
6563 			     CTL_PAGE_FLAG_DISK_ONLY))
6564 				continue;
6565 
6566 			/*
6567 			 * We don't use this subpage if the user didn't
6568 			 * request all subpages.
6569 			 */
6570 			if ((lun->mode_pages.index[i].subpage != 0)
6571 			 && (subpage == SMS_SUBPAGE_PAGE_0))
6572 				continue;
6573 
6574 #if 0
6575 			printf("found page %#x len %d\n",
6576 			       lun->mode_pages.index[i].page_code &
6577 			       SMPH_PC_MASK,
6578 			       lun->mode_pages.index[i].page_len);
6579 #endif
6580 			page_len += lun->mode_pages.index[i].page_len;
6581 		}
6582 		break;
6583 	}
6584 	default: {
6585 		int i;
6586 
6587 		page_len = 0;
6588 
6589 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6590 			/* Look for the right page code */
6591 			if ((lun->mode_pages.index[i].page_code &
6592 			     SMPH_PC_MASK) != page_code)
6593 				continue;
6594 
6595 			/* Look for the right subpage or the subpage wildcard*/
6596 			if ((lun->mode_pages.index[i].subpage != subpage)
6597 			 && (subpage != SMS_SUBPAGE_ALL))
6598 				continue;
6599 
6600 			/* Make sure the page is supported for this dev type */
6601 			if ((control_dev != 0)
6602 			 && (lun->mode_pages.index[i].page_flags &
6603 			     CTL_PAGE_FLAG_DISK_ONLY))
6604 				continue;
6605 
6606 #if 0
6607 			printf("found page %#x len %d\n",
6608 			       lun->mode_pages.index[i].page_code &
6609 			       SMPH_PC_MASK,
6610 			       lun->mode_pages.index[i].page_len);
6611 #endif
6612 
6613 			page_len += lun->mode_pages.index[i].page_len;
6614 		}
6615 
6616 		if (page_len == 0) {
6617 			ctl_set_invalid_field(ctsio,
6618 					      /*sks_valid*/ 1,
6619 					      /*command*/ 1,
6620 					      /*field*/ 2,
6621 					      /*bit_valid*/ 1,
6622 					      /*bit*/ 5);
6623 			ctl_done((union ctl_io *)ctsio);
6624 			return (CTL_RETVAL_COMPLETE);
6625 		}
6626 		break;
6627 	}
6628 	}
6629 
6630 	total_len = header_len + page_len;
6631 #if 0
6632 	printf("header_len = %d, page_len = %d, total_len = %d\n",
6633 	       header_len, page_len, total_len);
6634 #endif
6635 
6636 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6637 	ctsio->kern_sg_entries = 0;
6638 	ctsio->kern_data_resid = 0;
6639 	ctsio->kern_rel_offset = 0;
6640 	if (total_len < alloc_len) {
6641 		ctsio->residual = alloc_len - total_len;
6642 		ctsio->kern_data_len = total_len;
6643 		ctsio->kern_total_len = total_len;
6644 	} else {
6645 		ctsio->residual = 0;
6646 		ctsio->kern_data_len = alloc_len;
6647 		ctsio->kern_total_len = alloc_len;
6648 	}
6649 
6650 	switch (ctsio->cdb[0]) {
6651 	case MODE_SENSE_6: {
6652 		struct scsi_mode_hdr_6 *header;
6653 
6654 		header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6655 
6656 		header->datalen = ctl_min(total_len - 1, 254);
6657 
6658 		if (dbd)
6659 			header->block_descr_len = 0;
6660 		else
6661 			header->block_descr_len =
6662 				sizeof(struct scsi_mode_block_descr);
6663 		block_desc = (struct scsi_mode_block_descr *)&header[1];
6664 		break;
6665 	}
6666 	case MODE_SENSE_10: {
6667 		struct scsi_mode_hdr_10 *header;
6668 		int datalen;
6669 
6670 		header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6671 
6672 		datalen = ctl_min(total_len - 2, 65533);
6673 		scsi_ulto2b(datalen, header->datalen);
6674 		if (dbd)
6675 			scsi_ulto2b(0, header->block_descr_len);
6676 		else
6677 			scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
6678 				    header->block_descr_len);
6679 		block_desc = (struct scsi_mode_block_descr *)&header[1];
6680 		break;
6681 	}
6682 	default:
6683 		panic("invalid CDB type %#x", ctsio->cdb[0]);
6684 		break; /* NOTREACHED */
6685 	}
6686 
6687 	/*
6688 	 * If we've got a disk, use its blocksize in the block
6689 	 * descriptor.  Otherwise, just set it to 0.
6690 	 */
6691 	if (dbd == 0) {
6692 		if (control_dev != 0)
6693 			scsi_ulto3b(lun->be_lun->blocksize,
6694 				    block_desc->block_len);
6695 		else
6696 			scsi_ulto3b(0, block_desc->block_len);
6697 	}
6698 
6699 	switch (page_code) {
6700 	case SMS_ALL_PAGES_PAGE: {
6701 		int i, data_used;
6702 
6703 		data_used = header_len;
6704 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6705 			struct ctl_page_index *page_index;
6706 
6707 			page_index = &lun->mode_pages.index[i];
6708 
6709 			if ((control_dev != 0)
6710 			 && (page_index->page_flags &
6711 			    CTL_PAGE_FLAG_DISK_ONLY))
6712 				continue;
6713 
6714 			/*
6715 			 * We don't use this subpage if the user didn't
6716 			 * request all subpages.  We already checked (above)
6717 			 * to make sure the user only specified a subpage
6718 			 * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
6719 			 */
6720 			if ((page_index->subpage != 0)
6721 			 && (subpage == SMS_SUBPAGE_PAGE_0))
6722 				continue;
6723 
6724 			/*
6725 			 * Call the handler, if it exists, to update the
6726 			 * page to the latest values.
6727 			 */
6728 			if (page_index->sense_handler != NULL)
6729 				page_index->sense_handler(ctsio, page_index,pc);
6730 
6731 			memcpy(ctsio->kern_data_ptr + data_used,
6732 			       page_index->page_data +
6733 			       (page_index->page_len * pc),
6734 			       page_index->page_len);
6735 			data_used += page_index->page_len;
6736 		}
6737 		break;
6738 	}
6739 	default: {
6740 		int i, data_used;
6741 
6742 		data_used = header_len;
6743 
6744 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6745 			struct ctl_page_index *page_index;
6746 
6747 			page_index = &lun->mode_pages.index[i];
6748 
6749 			/* Look for the right page code */
6750 			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6751 				continue;
6752 
6753 			/* Look for the right subpage or the subpage wildcard*/
6754 			if ((page_index->subpage != subpage)
6755 			 && (subpage != SMS_SUBPAGE_ALL))
6756 				continue;
6757 
6758 			/* Make sure the page is supported for this dev type */
6759 			if ((control_dev != 0)
6760 			 && (page_index->page_flags &
6761 			     CTL_PAGE_FLAG_DISK_ONLY))
6762 				continue;
6763 
6764 			/*
6765 			 * Call the handler, if it exists, to update the
6766 			 * page to the latest values.
6767 			 */
6768 			if (page_index->sense_handler != NULL)
6769 				page_index->sense_handler(ctsio, page_index,pc);
6770 
6771 			memcpy(ctsio->kern_data_ptr + data_used,
6772 			       page_index->page_data +
6773 			       (page_index->page_len * pc),
6774 			       page_index->page_len);
6775 			data_used += page_index->page_len;
6776 		}
6777 		break;
6778 	}
6779 	}
6780 
6781 	ctsio->scsi_status = SCSI_STATUS_OK;
6782 
6783 	ctsio->be_move_done = ctl_config_move_done;
6784 	ctl_datamove((union ctl_io *)ctsio);
6785 
6786 	return (CTL_RETVAL_COMPLETE);
6787 }
6788 
6789 int
6790 ctl_read_capacity(struct ctl_scsiio *ctsio)
6791 {
6792 	struct scsi_read_capacity *cdb;
6793 	struct scsi_read_capacity_data *data;
6794 	struct ctl_lun *lun;
6795 	uint32_t lba;
6796 
6797 	CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
6798 
6799 	cdb = (struct scsi_read_capacity *)ctsio->cdb;
6800 
6801 	lba = scsi_4btoul(cdb->addr);
6802 	if (((cdb->pmi & SRC_PMI) == 0)
6803 	 && (lba != 0)) {
6804 		ctl_set_invalid_field(/*ctsio*/ ctsio,
6805 				      /*sks_valid*/ 1,
6806 				      /*command*/ 1,
6807 				      /*field*/ 2,
6808 				      /*bit_valid*/ 0,
6809 				      /*bit*/ 0);
6810 		ctl_done((union ctl_io *)ctsio);
6811 		return (CTL_RETVAL_COMPLETE);
6812 	}
6813 
6814 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6815 
6816 	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
6817 	data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
6818 	ctsio->residual = 0;
6819 	ctsio->kern_data_len = sizeof(*data);
6820 	ctsio->kern_total_len = sizeof(*data);
6821 	ctsio->kern_data_resid = 0;
6822 	ctsio->kern_rel_offset = 0;
6823 	ctsio->kern_sg_entries = 0;
6824 
6825 	/*
6826 	 * If the maximum LBA is greater than 0xfffffffe, the user must
6827 	 * issue a SERVICE ACTION IN (16) command, with the read capacity
6828 	 * serivce action set.
6829 	 */
6830 	if (lun->be_lun->maxlba > 0xfffffffe)
6831 		scsi_ulto4b(0xffffffff, data->addr);
6832 	else
6833 		scsi_ulto4b(lun->be_lun->maxlba, data->addr);
6834 
6835 	/*
6836 	 * XXX KDM this may not be 512 bytes...
6837 	 */
6838 	scsi_ulto4b(lun->be_lun->blocksize, data->length);
6839 
6840 	ctsio->scsi_status = SCSI_STATUS_OK;
6841 
6842 	ctsio->be_move_done = ctl_config_move_done;
6843 	ctl_datamove((union ctl_io *)ctsio);
6844 
6845 	return (CTL_RETVAL_COMPLETE);
6846 }
6847 
6848 static int
6849 ctl_read_capacity_16(struct ctl_scsiio *ctsio)
6850 {
6851 	struct scsi_read_capacity_16 *cdb;
6852 	struct scsi_read_capacity_data_long *data;
6853 	struct ctl_lun *lun;
6854 	uint64_t lba;
6855 	uint32_t alloc_len;
6856 
6857 	CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
6858 
6859 	cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
6860 
6861 	alloc_len = scsi_4btoul(cdb->alloc_len);
6862 	lba = scsi_8btou64(cdb->addr);
6863 
6864 	if ((cdb->reladr & SRC16_PMI)
6865 	 && (lba != 0)) {
6866 		ctl_set_invalid_field(/*ctsio*/ ctsio,
6867 				      /*sks_valid*/ 1,
6868 				      /*command*/ 1,
6869 				      /*field*/ 2,
6870 				      /*bit_valid*/ 0,
6871 				      /*bit*/ 0);
6872 		ctl_done((union ctl_io *)ctsio);
6873 		return (CTL_RETVAL_COMPLETE);
6874 	}
6875 
6876 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6877 
6878 	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
6879 	data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
6880 
6881 	if (sizeof(*data) < alloc_len) {
6882 		ctsio->residual = alloc_len - sizeof(*data);
6883 		ctsio->kern_data_len = sizeof(*data);
6884 		ctsio->kern_total_len = sizeof(*data);
6885 	} else {
6886 		ctsio->residual = 0;
6887 		ctsio->kern_data_len = alloc_len;
6888 		ctsio->kern_total_len = alloc_len;
6889 	}
6890 	ctsio->kern_data_resid = 0;
6891 	ctsio->kern_rel_offset = 0;
6892 	ctsio->kern_sg_entries = 0;
6893 
6894 	scsi_u64to8b(lun->be_lun->maxlba, data->addr);
6895 	/* XXX KDM this may not be 512 bytes... */
6896 	scsi_ulto4b(lun->be_lun->blocksize, data->length);
6897 
6898 	ctsio->scsi_status = SCSI_STATUS_OK;
6899 
6900 	ctsio->be_move_done = ctl_config_move_done;
6901 	ctl_datamove((union ctl_io *)ctsio);
6902 
6903 	return (CTL_RETVAL_COMPLETE);
6904 }
6905 
6906 int
6907 ctl_service_action_in(struct ctl_scsiio *ctsio)
6908 {
6909 	struct scsi_service_action_in *cdb;
6910 	int retval;
6911 
6912 	CTL_DEBUG_PRINT(("ctl_service_action_in\n"));
6913 
6914 	cdb = (struct scsi_service_action_in *)ctsio->cdb;
6915 
6916 	retval = CTL_RETVAL_COMPLETE;
6917 
6918 	switch (cdb->service_action) {
6919 	case SRC16_SERVICE_ACTION:
6920 		retval = ctl_read_capacity_16(ctsio);
6921 		break;
6922 	default:
6923 		ctl_set_invalid_field(/*ctsio*/ ctsio,
6924 				      /*sks_valid*/ 1,
6925 				      /*command*/ 1,
6926 				      /*field*/ 1,
6927 				      /*bit_valid*/ 1,
6928 				      /*bit*/ 4);
6929 		ctl_done((union ctl_io *)ctsio);
6930 		break;
6931 	}
6932 
6933 	return (retval);
6934 }
6935 
6936 int
6937 ctl_maintenance_in(struct ctl_scsiio *ctsio)
6938 {
6939 	struct scsi_maintenance_in *cdb;
6940 	int retval;
6941 	int alloc_len, total_len = 0;
6942 	int num_target_port_groups, single;
6943 	struct ctl_lun *lun;
6944 	struct ctl_softc *softc;
6945 	struct scsi_target_group_data *rtg_ptr;
6946 	struct scsi_target_port_group_descriptor *tpg_desc_ptr1, *tpg_desc_ptr2;
6947 	struct scsi_target_port_descriptor  *tp_desc_ptr1_1, *tp_desc_ptr1_2,
6948 	                                    *tp_desc_ptr2_1, *tp_desc_ptr2_2;
6949 
6950 	CTL_DEBUG_PRINT(("ctl_maintenance_in\n"));
6951 
6952 	cdb = (struct scsi_maintenance_in *)ctsio->cdb;
6953 	softc = control_softc;
6954 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6955 
6956 	retval = CTL_RETVAL_COMPLETE;
6957 
6958 	if ((cdb->byte2 & SERVICE_ACTION_MASK) != SA_RPRT_TRGT_GRP) {
6959 		ctl_set_invalid_field(/*ctsio*/ ctsio,
6960 				      /*sks_valid*/ 1,
6961 				      /*command*/ 1,
6962 				      /*field*/ 1,
6963 				      /*bit_valid*/ 1,
6964 				      /*bit*/ 4);
6965 		ctl_done((union ctl_io *)ctsio);
6966 		return(retval);
6967 	}
6968 
6969 	mtx_lock(&softc->ctl_lock);
6970 	single = ctl_is_single;
6971 	mtx_unlock(&softc->ctl_lock);
6972 
6973 	if (single)
6974         	num_target_port_groups = NUM_TARGET_PORT_GROUPS - 1;
6975 	else
6976         	num_target_port_groups = NUM_TARGET_PORT_GROUPS;
6977 
6978 	total_len = sizeof(struct scsi_target_group_data) +
6979 		sizeof(struct scsi_target_port_group_descriptor) *
6980 		num_target_port_groups +
6981 		sizeof(struct scsi_target_port_descriptor) *
6982 		NUM_PORTS_PER_GRP * num_target_port_groups;
6983 
6984 	alloc_len = scsi_4btoul(cdb->length);
6985 
6986 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6987 
6988 	ctsio->kern_sg_entries = 0;
6989 
6990 	if (total_len < alloc_len) {
6991 		ctsio->residual = alloc_len - total_len;
6992 		ctsio->kern_data_len = total_len;
6993 		ctsio->kern_total_len = total_len;
6994 	} else {
6995 		ctsio->residual = 0;
6996 		ctsio->kern_data_len = alloc_len;
6997 		ctsio->kern_total_len = alloc_len;
6998 	}
6999 	ctsio->kern_data_resid = 0;
7000 	ctsio->kern_rel_offset = 0;
7001 
7002 	rtg_ptr = (struct scsi_target_group_data *)ctsio->kern_data_ptr;
7003 
7004 	tpg_desc_ptr1 = &rtg_ptr->groups[0];
7005 	tp_desc_ptr1_1 = &tpg_desc_ptr1->descriptors[0];
7006 	tp_desc_ptr1_2 = (struct scsi_target_port_descriptor *)
7007 	        &tp_desc_ptr1_1->desc_list[0];
7008 
7009 	if (single == 0) {
7010 		tpg_desc_ptr2 = (struct scsi_target_port_group_descriptor *)
7011 	                &tp_desc_ptr1_2->desc_list[0];
7012 		tp_desc_ptr2_1 = &tpg_desc_ptr2->descriptors[0];
7013 		tp_desc_ptr2_2 = (struct scsi_target_port_descriptor *)
7014 	        	&tp_desc_ptr2_1->desc_list[0];
7015         } else {
7016 		tpg_desc_ptr2 = NULL;
7017 		tp_desc_ptr2_1 = NULL;
7018 		tp_desc_ptr2_2 = NULL;
7019 	}
7020 
7021 	scsi_ulto4b(total_len - 4, rtg_ptr->length);
7022 	if (single == 0) {
7023         	if (ctsio->io_hdr.nexus.targ_port < CTL_MAX_PORTS) {
7024 			if (lun->flags & CTL_LUN_PRIMARY_SC) {
7025 				tpg_desc_ptr1->pref_state = TPG_PRIMARY;
7026 				tpg_desc_ptr2->pref_state =
7027 					TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7028 			} else {
7029 				tpg_desc_ptr1->pref_state =
7030 					TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7031 				tpg_desc_ptr2->pref_state = TPG_PRIMARY;
7032 			}
7033 		} else {
7034 			if (lun->flags & CTL_LUN_PRIMARY_SC) {
7035 				tpg_desc_ptr1->pref_state =
7036 					TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7037 				tpg_desc_ptr2->pref_state = TPG_PRIMARY;
7038 			} else {
7039 				tpg_desc_ptr1->pref_state = TPG_PRIMARY;
7040 				tpg_desc_ptr2->pref_state =
7041 					TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7042 			}
7043 		}
7044 	} else {
7045 		tpg_desc_ptr1->pref_state = TPG_PRIMARY;
7046 	}
7047 	tpg_desc_ptr1->support = 0;
7048 	tpg_desc_ptr1->target_port_group[1] = 1;
7049 	tpg_desc_ptr1->status = TPG_IMPLICIT;
7050 	tpg_desc_ptr1->target_port_count= NUM_PORTS_PER_GRP;
7051 
7052 	if (single == 0) {
7053 		tpg_desc_ptr2->support = 0;
7054 		tpg_desc_ptr2->target_port_group[1] = 2;
7055 		tpg_desc_ptr2->status = TPG_IMPLICIT;
7056 		tpg_desc_ptr2->target_port_count = NUM_PORTS_PER_GRP;
7057 
7058 		tp_desc_ptr1_1->relative_target_port_identifier[1] = 1;
7059 		tp_desc_ptr1_2->relative_target_port_identifier[1] = 2;
7060 
7061 		tp_desc_ptr2_1->relative_target_port_identifier[1] = 9;
7062 		tp_desc_ptr2_2->relative_target_port_identifier[1] = 10;
7063 	} else {
7064         	if (ctsio->io_hdr.nexus.targ_port < CTL_MAX_PORTS) {
7065 			tp_desc_ptr1_1->relative_target_port_identifier[1] = 1;
7066 			tp_desc_ptr1_2->relative_target_port_identifier[1] = 2;
7067 		} else {
7068 			tp_desc_ptr1_1->relative_target_port_identifier[1] = 9;
7069 			tp_desc_ptr1_2->relative_target_port_identifier[1] = 10;
7070 		}
7071 	}
7072 
7073 	ctsio->be_move_done = ctl_config_move_done;
7074 
7075 	CTL_DEBUG_PRINT(("buf = %x %x %x %x %x %x %x %x\n",
7076 			 ctsio->kern_data_ptr[0], ctsio->kern_data_ptr[1],
7077 			 ctsio->kern_data_ptr[2], ctsio->kern_data_ptr[3],
7078 			 ctsio->kern_data_ptr[4], ctsio->kern_data_ptr[5],
7079 			 ctsio->kern_data_ptr[6], ctsio->kern_data_ptr[7]));
7080 
7081 	ctl_datamove((union ctl_io *)ctsio);
7082 	return(retval);
7083 }
7084 
7085 int
7086 ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7087 {
7088 	struct scsi_per_res_in *cdb;
7089 	int alloc_len, total_len = 0;
7090 	/* struct scsi_per_res_in_rsrv in_data; */
7091 	struct ctl_lun *lun;
7092 	struct ctl_softc *softc;
7093 
7094 	CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7095 
7096 	softc = control_softc;
7097 
7098 	cdb = (struct scsi_per_res_in *)ctsio->cdb;
7099 
7100 	alloc_len = scsi_2btoul(cdb->length);
7101 
7102 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7103 
7104 retry:
7105 	mtx_lock(&softc->ctl_lock);
7106 	switch (cdb->action) {
7107 	case SPRI_RK: /* read keys */
7108 		total_len = sizeof(struct scsi_per_res_in_keys) +
7109 			lun->pr_key_count *
7110 			sizeof(struct scsi_per_res_key);
7111 		break;
7112 	case SPRI_RR: /* read reservation */
7113 		if (lun->flags & CTL_LUN_PR_RESERVED)
7114 			total_len = sizeof(struct scsi_per_res_in_rsrv);
7115 		else
7116 			total_len = sizeof(struct scsi_per_res_in_header);
7117 		break;
7118 	case SPRI_RC: /* report capabilities */
7119 		total_len = sizeof(struct scsi_per_res_cap);
7120 		break;
7121 	case SPRI_RS: /* read full status */
7122 	default:
7123 		mtx_unlock(&softc->ctl_lock);
7124 		ctl_set_invalid_field(ctsio,
7125 				      /*sks_valid*/ 1,
7126 				      /*command*/ 1,
7127 				      /*field*/ 1,
7128 				      /*bit_valid*/ 1,
7129 				      /*bit*/ 0);
7130 		ctl_done((union ctl_io *)ctsio);
7131 		return (CTL_RETVAL_COMPLETE);
7132 		break; /* NOTREACHED */
7133 	}
7134 	mtx_unlock(&softc->ctl_lock);
7135 
7136 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7137 
7138 	if (total_len < alloc_len) {
7139 		ctsio->residual = alloc_len - total_len;
7140 		ctsio->kern_data_len = total_len;
7141 		ctsio->kern_total_len = total_len;
7142 	} else {
7143 		ctsio->residual = 0;
7144 		ctsio->kern_data_len = alloc_len;
7145 		ctsio->kern_total_len = alloc_len;
7146 	}
7147 
7148 	ctsio->kern_data_resid = 0;
7149 	ctsio->kern_rel_offset = 0;
7150 	ctsio->kern_sg_entries = 0;
7151 
7152 	mtx_lock(&softc->ctl_lock);
7153 	switch (cdb->action) {
7154 	case SPRI_RK: { // read keys
7155         struct scsi_per_res_in_keys *res_keys;
7156 		int i, key_count;
7157 
7158 		res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7159 
7160 		/*
7161 		 * We had to drop the lock to allocate our buffer, which
7162 		 * leaves time for someone to come in with another
7163 		 * persistent reservation.  (That is unlikely, though,
7164 		 * since this should be the only persistent reservation
7165 		 * command active right now.)
7166 		 */
7167 		if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7168 		    (lun->pr_key_count *
7169 		     sizeof(struct scsi_per_res_key)))){
7170 			mtx_unlock(&softc->ctl_lock);
7171 			free(ctsio->kern_data_ptr, M_CTL);
7172 			printf("%s: reservation length changed, retrying\n",
7173 			       __func__);
7174 			goto retry;
7175 		}
7176 
7177 		scsi_ulto4b(lun->PRGeneration, res_keys->header.generation);
7178 
7179 		scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7180 			     lun->pr_key_count, res_keys->header.length);
7181 
7182 		for (i = 0, key_count = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7183 			if (!lun->per_res[i].registered)
7184 				continue;
7185 
7186 			/*
7187 			 * We used lun->pr_key_count to calculate the
7188 			 * size to allocate.  If it turns out the number of
7189 			 * initiators with the registered flag set is
7190 			 * larger than that (i.e. they haven't been kept in
7191 			 * sync), we've got a problem.
7192 			 */
7193 			if (key_count >= lun->pr_key_count) {
7194 #ifdef NEEDTOPORT
7195 				csevent_log(CSC_CTL | CSC_SHELF_SW |
7196 					    CTL_PR_ERROR,
7197 					    csevent_LogType_Fault,
7198 					    csevent_AlertLevel_Yellow,
7199 					    csevent_FRU_ShelfController,
7200 					    csevent_FRU_Firmware,
7201 				        csevent_FRU_Unknown,
7202 					    "registered keys %d >= key "
7203 					    "count %d", key_count,
7204 					    lun->pr_key_count);
7205 #endif
7206 				key_count++;
7207 				continue;
7208 			}
7209 			memcpy(res_keys->keys[key_count].key,
7210 			       lun->per_res[i].res_key.key,
7211 			       ctl_min(sizeof(res_keys->keys[key_count].key),
7212 			       sizeof(lun->per_res[i].res_key)));
7213 			key_count++;
7214 		}
7215 		break;
7216 	}
7217 	case SPRI_RR: { // read reservation
7218 		struct scsi_per_res_in_rsrv *res;
7219 		int tmp_len, header_only;
7220 
7221 		res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7222 
7223 		scsi_ulto4b(lun->PRGeneration, res->header.generation);
7224 
7225 		if (lun->flags & CTL_LUN_PR_RESERVED)
7226 		{
7227 			tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7228 			scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7229 				    res->header.length);
7230 			header_only = 0;
7231 		} else {
7232 			tmp_len = sizeof(struct scsi_per_res_in_header);
7233 			scsi_ulto4b(0, res->header.length);
7234 			header_only = 1;
7235 		}
7236 
7237 		/*
7238 		 * We had to drop the lock to allocate our buffer, which
7239 		 * leaves time for someone to come in with another
7240 		 * persistent reservation.  (That is unlikely, though,
7241 		 * since this should be the only persistent reservation
7242 		 * command active right now.)
7243 		 */
7244 		if (tmp_len != total_len) {
7245 			mtx_unlock(&softc->ctl_lock);
7246 			free(ctsio->kern_data_ptr, M_CTL);
7247 			printf("%s: reservation status changed, retrying\n",
7248 			       __func__);
7249 			goto retry;
7250 		}
7251 
7252 		/*
7253 		 * No reservation held, so we're done.
7254 		 */
7255 		if (header_only != 0)
7256 			break;
7257 
7258 		/*
7259 		 * If the registration is an All Registrants type, the key
7260 		 * is 0, since it doesn't really matter.
7261 		 */
7262 		if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7263 			memcpy(res->data.reservation,
7264 			       &lun->per_res[lun->pr_res_idx].res_key,
7265 			       sizeof(struct scsi_per_res_key));
7266 		}
7267 		res->data.scopetype = lun->res_type;
7268 		break;
7269 	}
7270 	case SPRI_RC:     //report capabilities
7271 	{
7272 		struct scsi_per_res_cap *res_cap;
7273 		uint16_t type_mask;
7274 
7275 		res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7276 		scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7277 		res_cap->flags2 |= SPRI_TMV;
7278 		type_mask = SPRI_TM_WR_EX_AR |
7279 			    SPRI_TM_EX_AC_RO |
7280 			    SPRI_TM_WR_EX_RO |
7281 			    SPRI_TM_EX_AC |
7282 			    SPRI_TM_WR_EX |
7283 			    SPRI_TM_EX_AC_AR;
7284 		scsi_ulto2b(type_mask, res_cap->type_mask);
7285 		break;
7286 	}
7287 	case SPRI_RS: //read full status
7288 	default:
7289 		/*
7290 		 * This is a bug, because we just checked for this above,
7291 		 * and should have returned an error.
7292 		 */
7293 		panic("Invalid PR type %x", cdb->action);
7294 		break; /* NOTREACHED */
7295 	}
7296 	mtx_unlock(&softc->ctl_lock);
7297 
7298 	ctsio->be_move_done = ctl_config_move_done;
7299 
7300 	CTL_DEBUG_PRINT(("buf = %x %x %x %x %x %x %x %x\n",
7301 			 ctsio->kern_data_ptr[0], ctsio->kern_data_ptr[1],
7302 			 ctsio->kern_data_ptr[2], ctsio->kern_data_ptr[3],
7303 			 ctsio->kern_data_ptr[4], ctsio->kern_data_ptr[5],
7304 			 ctsio->kern_data_ptr[6], ctsio->kern_data_ptr[7]));
7305 
7306 	ctl_datamove((union ctl_io *)ctsio);
7307 
7308 	return (CTL_RETVAL_COMPLETE);
7309 }
7310 
7311 /*
7312  * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
7313  * it should return.
7314  */
7315 static int
7316 ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
7317 		uint64_t sa_res_key, uint8_t type, uint32_t residx,
7318 		struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
7319 		struct scsi_per_res_out_parms* param)
7320 {
7321 	union ctl_ha_msg persis_io;
7322 	int retval, i;
7323 	int isc_retval;
7324 
7325 	retval = 0;
7326 
7327 	if (sa_res_key == 0) {
7328 		mtx_lock(&softc->ctl_lock);
7329 		if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
7330 			/* validate scope and type */
7331 			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7332 			     SPR_LU_SCOPE) {
7333 				mtx_unlock(&softc->ctl_lock);
7334 				ctl_set_invalid_field(/*ctsio*/ ctsio,
7335 						      /*sks_valid*/ 1,
7336 						      /*command*/ 1,
7337 						      /*field*/ 2,
7338 						      /*bit_valid*/ 1,
7339 						      /*bit*/ 4);
7340 				ctl_done((union ctl_io *)ctsio);
7341 				return (1);
7342 			}
7343 
7344 		        if (type>8 || type==2 || type==4 || type==0) {
7345 				mtx_unlock(&softc->ctl_lock);
7346 				ctl_set_invalid_field(/*ctsio*/ ctsio,
7347        	           				      /*sks_valid*/ 1,
7348 						      /*command*/ 1,
7349 						      /*field*/ 2,
7350 						      /*bit_valid*/ 1,
7351 						      /*bit*/ 0);
7352 				ctl_done((union ctl_io *)ctsio);
7353 				return (1);
7354 		        }
7355 
7356 			/* temporarily unregister this nexus */
7357 			lun->per_res[residx].registered = 0;
7358 
7359 			/*
7360 			 * Unregister everybody else and build UA for
7361 			 * them
7362 			 */
7363 			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
7364 				if (lun->per_res[i].registered == 0)
7365 					continue;
7366 
7367 				if (!persis_offset
7368 				 && i <CTL_MAX_INITIATORS)
7369 					lun->pending_sense[i].ua_pending |=
7370 						CTL_UA_REG_PREEMPT;
7371 				else if (persis_offset
7372 				      && i >= persis_offset)
7373 					lun->pending_sense[i-persis_offset
7374 						].ua_pending |=
7375 						CTL_UA_REG_PREEMPT;
7376 				lun->per_res[i].registered = 0;
7377 				memset(&lun->per_res[i].res_key, 0,
7378 				       sizeof(struct scsi_per_res_key));
7379 			}
7380 			lun->per_res[residx].registered = 1;
7381 			lun->pr_key_count = 1;
7382 			lun->res_type = type;
7383 			if (lun->res_type != SPR_TYPE_WR_EX_AR
7384 			 && lun->res_type != SPR_TYPE_EX_AC_AR)
7385 				lun->pr_res_idx = residx;
7386 
7387 			mtx_unlock(&softc->ctl_lock);
7388 			/* send msg to other side */
7389 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7390 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7391 			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7392 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
7393 			persis_io.pr.pr_info.res_type = type;
7394 			memcpy(persis_io.pr.pr_info.sa_res_key,
7395 			       param->serv_act_res_key,
7396 			       sizeof(param->serv_act_res_key));
7397 			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
7398 			     &persis_io, sizeof(persis_io), 0)) >
7399 			     CTL_HA_STATUS_SUCCESS) {
7400 				printf("CTL:Persis Out error returned "
7401 				       "from ctl_ha_msg_send %d\n",
7402 				       isc_retval);
7403 			}
7404 		} else {
7405 			/* not all registrants */
7406 			mtx_unlock(&softc->ctl_lock);
7407 			free(ctsio->kern_data_ptr, M_CTL);
7408 			ctl_set_invalid_field(ctsio,
7409 					      /*sks_valid*/ 1,
7410 					      /*command*/ 0,
7411 					      /*field*/ 8,
7412 					      /*bit_valid*/ 0,
7413 					      /*bit*/ 0);
7414 			ctl_done((union ctl_io *)ctsio);
7415 			return (1);
7416 		}
7417 	} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
7418 		|| !(lun->flags & CTL_LUN_PR_RESERVED)) {
7419 		int found = 0;
7420 
7421 		mtx_lock(&softc->ctl_lock);
7422 		if (res_key == sa_res_key) {
7423 			/* special case */
7424 			/*
7425 			 * The spec implies this is not good but doesn't
7426 			 * say what to do. There are two choices either
7427 			 * generate a res conflict or check condition
7428 			 * with illegal field in parameter data. Since
7429 			 * that is what is done when the sa_res_key is
7430 			 * zero I'll take that approach since this has
7431 			 * to do with the sa_res_key.
7432 			 */
7433 			mtx_unlock(&softc->ctl_lock);
7434 			free(ctsio->kern_data_ptr, M_CTL);
7435 			ctl_set_invalid_field(ctsio,
7436 					      /*sks_valid*/ 1,
7437 					      /*command*/ 0,
7438 					      /*field*/ 8,
7439 					      /*bit_valid*/ 0,
7440 					      /*bit*/ 0);
7441 			ctl_done((union ctl_io *)ctsio);
7442 			return (1);
7443 		}
7444 
7445 		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
7446 			if (lun->per_res[i].registered
7447 			 && memcmp(param->serv_act_res_key,
7448 			    lun->per_res[i].res_key.key,
7449 			    sizeof(struct scsi_per_res_key)) != 0)
7450 				continue;
7451 
7452 			found = 1;
7453 			lun->per_res[i].registered = 0;
7454 			memset(&lun->per_res[i].res_key, 0,
7455 			       sizeof(struct scsi_per_res_key));
7456 			lun->pr_key_count--;
7457 
7458 			if (!persis_offset
7459 			 && i < CTL_MAX_INITIATORS)
7460 				lun->pending_sense[i].ua_pending |=
7461 					CTL_UA_REG_PREEMPT;
7462 			else if (persis_offset
7463 			      && i >= persis_offset)
7464 				lun->pending_sense[i-persis_offset].ua_pending|=
7465 					CTL_UA_REG_PREEMPT;
7466 		}
7467 		mtx_unlock(&softc->ctl_lock);
7468 		if (!found) {
7469 			free(ctsio->kern_data_ptr, M_CTL);
7470 			ctl_set_reservation_conflict(ctsio);
7471 			ctl_done((union ctl_io *)ctsio);
7472 			return (CTL_RETVAL_COMPLETE);
7473 		}
7474 		/* send msg to other side */
7475 		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7476 		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7477 		persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7478 		persis_io.pr.pr_info.residx = lun->pr_res_idx;
7479 		persis_io.pr.pr_info.res_type = type;
7480 		memcpy(persis_io.pr.pr_info.sa_res_key,
7481 		       param->serv_act_res_key,
7482 		       sizeof(param->serv_act_res_key));
7483 		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
7484 		     &persis_io, sizeof(persis_io), 0)) >
7485 		     CTL_HA_STATUS_SUCCESS) {
7486 			printf("CTL:Persis Out error returned from "
7487 			       "ctl_ha_msg_send %d\n", isc_retval);
7488 		}
7489 	} else {
7490 		/* Reserved but not all registrants */
7491 		/* sa_res_key is res holder */
7492 		if (memcmp(param->serv_act_res_key,
7493                    lun->per_res[lun->pr_res_idx].res_key.key,
7494                    sizeof(struct scsi_per_res_key)) == 0) {
7495 			/* validate scope and type */
7496 			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7497 			     SPR_LU_SCOPE) {
7498 				ctl_set_invalid_field(/*ctsio*/ ctsio,
7499 						      /*sks_valid*/ 1,
7500 						      /*command*/ 1,
7501 						      /*field*/ 2,
7502 						      /*bit_valid*/ 1,
7503 						      /*bit*/ 4);
7504 				ctl_done((union ctl_io *)ctsio);
7505 				return (1);
7506 			}
7507 
7508 			if (type>8 || type==2 || type==4 || type==0) {
7509 				ctl_set_invalid_field(/*ctsio*/ ctsio,
7510 						      /*sks_valid*/ 1,
7511 						      /*command*/ 1,
7512 						      /*field*/ 2,
7513 						      /*bit_valid*/ 1,
7514 						      /*bit*/ 0);
7515 				ctl_done((union ctl_io *)ctsio);
7516 				return (1);
7517 			}
7518 
7519 			/*
7520 			 * Do the following:
7521 			 * if sa_res_key != res_key remove all
7522 			 * registrants w/sa_res_key and generate UA
7523 			 * for these registrants(Registrations
7524 			 * Preempted) if it wasn't an exclusive
7525 			 * reservation generate UA(Reservations
7526 			 * Preempted) for all other registered nexuses
7527 			 * if the type has changed. Establish the new
7528 			 * reservation and holder. If res_key and
7529 			 * sa_res_key are the same do the above
7530 			 * except don't unregister the res holder.
7531 			 */
7532 
7533 			/*
7534 			 * Temporarily unregister so it won't get
7535 			 * removed or UA generated
7536 			 */
7537 			lun->per_res[residx].registered = 0;
7538 			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
7539 				if (lun->per_res[i].registered == 0)
7540 					continue;
7541 
7542 				if (memcmp(param->serv_act_res_key,
7543 				    lun->per_res[i].res_key.key,
7544 				    sizeof(struct scsi_per_res_key)) == 0) {
7545 					lun->per_res[i].registered = 0;
7546 					memset(&lun->per_res[i].res_key,
7547 					       0,
7548 					       sizeof(struct scsi_per_res_key));
7549 					lun->pr_key_count--;
7550 
7551 					if (!persis_offset
7552 					 && i < CTL_MAX_INITIATORS)
7553 						lun->pending_sense[i
7554 							].ua_pending |=
7555 							CTL_UA_REG_PREEMPT;
7556 					else if (persis_offset
7557 					      && i >= persis_offset)
7558 						lun->pending_sense[
7559 						  i-persis_offset].ua_pending |=
7560 						  CTL_UA_REG_PREEMPT;
7561 				} else if (type != lun->res_type
7562 					&& (lun->res_type == SPR_TYPE_WR_EX_RO
7563 					 || lun->res_type ==SPR_TYPE_EX_AC_RO)){
7564 						if (!persis_offset
7565 						 && i < CTL_MAX_INITIATORS)
7566 							lun->pending_sense[i
7567 							].ua_pending |=
7568 							CTL_UA_RES_RELEASE;
7569 						else if (persis_offset
7570 						      && i >= persis_offset)
7571 							lun->pending_sense[
7572 							i-persis_offset
7573 							].ua_pending |=
7574 							CTL_UA_RES_RELEASE;
7575 				}
7576 			}
7577 			lun->per_res[residx].registered = 1;
7578 			lun->res_type = type;
7579 			if (lun->res_type != SPR_TYPE_WR_EX_AR
7580 			 && lun->res_type != SPR_TYPE_EX_AC_AR)
7581 				lun->pr_res_idx = residx;
7582 			else
7583 				lun->pr_res_idx =
7584 					CTL_PR_ALL_REGISTRANTS;
7585 
7586 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7587 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7588 			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7589 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
7590 			persis_io.pr.pr_info.res_type = type;
7591 			memcpy(persis_io.pr.pr_info.sa_res_key,
7592 			       param->serv_act_res_key,
7593 			       sizeof(param->serv_act_res_key));
7594 			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
7595 			     &persis_io, sizeof(persis_io), 0)) >
7596 			     CTL_HA_STATUS_SUCCESS) {
7597 				printf("CTL:Persis Out error returned "
7598 				       "from ctl_ha_msg_send %d\n",
7599 				       isc_retval);
7600 			}
7601 		} else {
7602 			/*
7603 			 * sa_res_key is not the res holder just
7604 			 * remove registrants
7605 			 */
7606 			int found=0;
7607 			mtx_lock(&softc->ctl_lock);
7608 
7609 			for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
7610 				if (memcmp(param->serv_act_res_key,
7611 				    lun->per_res[i].res_key.key,
7612 				    sizeof(struct scsi_per_res_key)) != 0)
7613 					continue;
7614 
7615 				found = 1;
7616 				lun->per_res[i].registered = 0;
7617 				memset(&lun->per_res[i].res_key, 0,
7618 				       sizeof(struct scsi_per_res_key));
7619 				lun->pr_key_count--;
7620 
7621 				if (!persis_offset
7622 				 && i < CTL_MAX_INITIATORS)
7623 					lun->pending_sense[i].ua_pending |=
7624 						CTL_UA_REG_PREEMPT;
7625 				else if (persis_offset
7626 				      && i >= persis_offset)
7627 					lun->pending_sense[
7628 						i-persis_offset].ua_pending |=
7629 						CTL_UA_REG_PREEMPT;
7630 			}
7631 
7632 			if (!found) {
7633 				mtx_unlock(&softc->ctl_lock);
7634 				free(ctsio->kern_data_ptr, M_CTL);
7635 				ctl_set_reservation_conflict(ctsio);
7636 				ctl_done((union ctl_io *)ctsio);
7637 		        	return (1);
7638 			}
7639 			mtx_unlock(&softc->ctl_lock);
7640 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7641 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7642 			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7643 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
7644 			persis_io.pr.pr_info.res_type = type;
7645 			memcpy(persis_io.pr.pr_info.sa_res_key,
7646 			       param->serv_act_res_key,
7647 			       sizeof(param->serv_act_res_key));
7648 			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
7649 			     &persis_io, sizeof(persis_io), 0)) >
7650 			     CTL_HA_STATUS_SUCCESS) {
7651 				printf("CTL:Persis Out error returned "
7652 				       "from ctl_ha_msg_send %d\n",
7653 				isc_retval);
7654 			}
7655 		}
7656 	}
7657 
7658 	lun->PRGeneration++;
7659 
7660 	return (retval);
7661 }
7662 
7663 static void
7664 ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
7665 {
7666 	int i;
7667 
7668 	if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
7669 	 || lun->pr_res_idx == CTL_PR_NO_RESERVATION
7670 	 || memcmp(&lun->per_res[lun->pr_res_idx].res_key,
7671 		   msg->pr.pr_info.sa_res_key,
7672 		   sizeof(struct scsi_per_res_key)) != 0) {
7673 		uint64_t sa_res_key;
7674 		sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
7675 
7676 		if (sa_res_key == 0) {
7677 			/* temporarily unregister this nexus */
7678 			lun->per_res[msg->pr.pr_info.residx].registered = 0;
7679 
7680 			/*
7681 			 * Unregister everybody else and build UA for
7682 			 * them
7683 			 */
7684 			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
7685 				if (lun->per_res[i].registered == 0)
7686 					continue;
7687 
7688 				if (!persis_offset
7689 				 && i < CTL_MAX_INITIATORS)
7690 					lun->pending_sense[i].ua_pending |=
7691 						CTL_UA_REG_PREEMPT;
7692 				else if (persis_offset && i >= persis_offset)
7693 					lun->pending_sense[i -
7694 						persis_offset].ua_pending |=
7695 						CTL_UA_REG_PREEMPT;
7696 				lun->per_res[i].registered = 0;
7697 				memset(&lun->per_res[i].res_key, 0,
7698 				       sizeof(struct scsi_per_res_key));
7699 			}
7700 
7701 			lun->per_res[msg->pr.pr_info.residx].registered = 1;
7702 			lun->pr_key_count = 1;
7703 			lun->res_type = msg->pr.pr_info.res_type;
7704 			if (lun->res_type != SPR_TYPE_WR_EX_AR
7705 			 && lun->res_type != SPR_TYPE_EX_AC_AR)
7706 				lun->pr_res_idx = msg->pr.pr_info.residx;
7707 		} else {
7708 		        for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
7709 				if (memcmp(msg->pr.pr_info.sa_res_key,
7710 		                   lun->per_res[i].res_key.key,
7711 		                   sizeof(struct scsi_per_res_key)) != 0)
7712 					continue;
7713 
7714 				lun->per_res[i].registered = 0;
7715 				memset(&lun->per_res[i].res_key, 0,
7716 				       sizeof(struct scsi_per_res_key));
7717 				lun->pr_key_count--;
7718 
7719 				if (!persis_offset
7720 				 && i < persis_offset)
7721 					lun->pending_sense[i].ua_pending |=
7722 						CTL_UA_REG_PREEMPT;
7723 				else if (persis_offset
7724 				      && i >= persis_offset)
7725 					lun->pending_sense[i -
7726 						persis_offset].ua_pending |=
7727 						CTL_UA_REG_PREEMPT;
7728 			}
7729 		}
7730 	} else {
7731 		/*
7732 		 * Temporarily unregister so it won't get removed
7733 		 * or UA generated
7734 		 */
7735 		lun->per_res[msg->pr.pr_info.residx].registered = 0;
7736 		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
7737 			if (lun->per_res[i].registered == 0)
7738 				continue;
7739 
7740 			if (memcmp(msg->pr.pr_info.sa_res_key,
7741 	                   lun->per_res[i].res_key.key,
7742 	                   sizeof(struct scsi_per_res_key)) == 0) {
7743 				lun->per_res[i].registered = 0;
7744 				memset(&lun->per_res[i].res_key, 0,
7745 				       sizeof(struct scsi_per_res_key));
7746 				lun->pr_key_count--;
7747 				if (!persis_offset
7748 				 && i < CTL_MAX_INITIATORS)
7749 					lun->pending_sense[i].ua_pending |=
7750 						CTL_UA_REG_PREEMPT;
7751 				else if (persis_offset
7752 				      && i >= persis_offset)
7753 					lun->pending_sense[i -
7754 						persis_offset].ua_pending |=
7755 						CTL_UA_REG_PREEMPT;
7756 			} else if (msg->pr.pr_info.res_type != lun->res_type
7757 				&& (lun->res_type == SPR_TYPE_WR_EX_RO
7758 				 || lun->res_type == SPR_TYPE_EX_AC_RO)) {
7759 					if (!persis_offset
7760 					 && i < persis_offset)
7761 						lun->pending_sense[i
7762 							].ua_pending |=
7763 							CTL_UA_RES_RELEASE;
7764 					else if (persis_offset
7765 					      && i >= persis_offset)
7766 					lun->pending_sense[i -
7767 						persis_offset].ua_pending |=
7768 						CTL_UA_RES_RELEASE;
7769 			}
7770 		}
7771 		lun->per_res[msg->pr.pr_info.residx].registered = 1;
7772 		lun->res_type = msg->pr.pr_info.res_type;
7773 		if (lun->res_type != SPR_TYPE_WR_EX_AR
7774 		 && lun->res_type != SPR_TYPE_EX_AC_AR)
7775 			lun->pr_res_idx = msg->pr.pr_info.residx;
7776 		else
7777 			lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
7778 	}
7779 	lun->PRGeneration++;
7780 
7781 }
7782 
7783 
7784 int
7785 ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
7786 {
7787 	int retval;
7788 	int isc_retval;
7789 	u_int32_t param_len;
7790 	struct scsi_per_res_out *cdb;
7791 	struct ctl_lun *lun;
7792 	struct scsi_per_res_out_parms* param;
7793 	struct ctl_softc *softc;
7794 	uint32_t residx;
7795 	uint64_t res_key, sa_res_key;
7796 	uint8_t type;
7797 	union ctl_ha_msg persis_io;
7798 	int    i;
7799 
7800 	CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
7801 
7802 	retval = CTL_RETVAL_COMPLETE;
7803 
7804 	softc = control_softc;
7805 
7806 	cdb = (struct scsi_per_res_out *)ctsio->cdb;
7807 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7808 
7809 	/*
7810 	 * We only support whole-LUN scope.  The scope & type are ignored for
7811 	 * register, register and ignore existing key and clear.
7812 	 * We sometimes ignore scope and type on preempts too!!
7813 	 * Verify reservation type here as well.
7814 	 */
7815 	type = cdb->scope_type & SPR_TYPE_MASK;
7816 	if ((cdb->action == SPRO_RESERVE)
7817 	 || (cdb->action == SPRO_RELEASE)) {
7818 		if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
7819 			ctl_set_invalid_field(/*ctsio*/ ctsio,
7820 					      /*sks_valid*/ 1,
7821 					      /*command*/ 1,
7822 					      /*field*/ 2,
7823 					      /*bit_valid*/ 1,
7824 					      /*bit*/ 4);
7825 			ctl_done((union ctl_io *)ctsio);
7826 			return (CTL_RETVAL_COMPLETE);
7827 		}
7828 
7829 		if (type>8 || type==2 || type==4 || type==0) {
7830 			ctl_set_invalid_field(/*ctsio*/ ctsio,
7831 					      /*sks_valid*/ 1,
7832 					      /*command*/ 1,
7833 					      /*field*/ 2,
7834 					      /*bit_valid*/ 1,
7835 					      /*bit*/ 0);
7836 			ctl_done((union ctl_io *)ctsio);
7837 			return (CTL_RETVAL_COMPLETE);
7838 		}
7839 	}
7840 
7841 	switch (cdb->action & SPRO_ACTION_MASK) {
7842 	case SPRO_REGISTER:
7843 	case SPRO_RESERVE:
7844 	case SPRO_RELEASE:
7845 	case SPRO_CLEAR:
7846 	case SPRO_PREEMPT:
7847 	case SPRO_REG_IGNO:
7848 		break;
7849 	case SPRO_REG_MOVE:
7850 	case SPRO_PRE_ABO:
7851 	default:
7852 		ctl_set_invalid_field(/*ctsio*/ ctsio,
7853 				      /*sks_valid*/ 1,
7854 				      /*command*/ 1,
7855 				      /*field*/ 1,
7856 				      /*bit_valid*/ 1,
7857 				      /*bit*/ 0);
7858 		ctl_done((union ctl_io *)ctsio);
7859 		return (CTL_RETVAL_COMPLETE);
7860 		break; /* NOTREACHED */
7861 	}
7862 
7863 	param_len = scsi_4btoul(cdb->length);
7864 
7865 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
7866 		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
7867 		ctsio->kern_data_len = param_len;
7868 		ctsio->kern_total_len = param_len;
7869 		ctsio->kern_data_resid = 0;
7870 		ctsio->kern_rel_offset = 0;
7871 		ctsio->kern_sg_entries = 0;
7872 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7873 		ctsio->be_move_done = ctl_config_move_done;
7874 		ctl_datamove((union ctl_io *)ctsio);
7875 
7876 		return (CTL_RETVAL_COMPLETE);
7877 	}
7878 
7879 	param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
7880 
7881 	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
7882 	res_key = scsi_8btou64(param->res_key.key);
7883 	sa_res_key = scsi_8btou64(param->serv_act_res_key);
7884 
7885 	/*
7886 	 * Validate the reservation key here except for SPRO_REG_IGNO
7887 	 * This must be done for all other service actions
7888 	 */
7889 	if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
7890 		mtx_lock(&softc->ctl_lock);
7891 		if (lun->per_res[residx].registered) {
7892 		    if (memcmp(param->res_key.key,
7893 			       lun->per_res[residx].res_key.key,
7894 			       ctl_min(sizeof(param->res_key),
7895 			       sizeof(lun->per_res[residx].res_key))) != 0) {
7896 				/*
7897 				 * The current key passed in doesn't match
7898 				 * the one the initiator previously
7899 				 * registered.
7900 				 */
7901 				mtx_unlock(&softc->ctl_lock);
7902 				free(ctsio->kern_data_ptr, M_CTL);
7903 				ctl_set_reservation_conflict(ctsio);
7904 				ctl_done((union ctl_io *)ctsio);
7905 				return (CTL_RETVAL_COMPLETE);
7906 			}
7907 		} else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
7908 			/*
7909 			 * We are not registered
7910 			 */
7911 			mtx_unlock(&softc->ctl_lock);
7912 			free(ctsio->kern_data_ptr, M_CTL);
7913 			ctl_set_reservation_conflict(ctsio);
7914 			ctl_done((union ctl_io *)ctsio);
7915 			return (CTL_RETVAL_COMPLETE);
7916 		} else if (res_key != 0) {
7917 			/*
7918 			 * We are not registered and trying to register but
7919 			 * the register key isn't zero.
7920 			 */
7921 			mtx_unlock(&softc->ctl_lock);
7922 			free(ctsio->kern_data_ptr, M_CTL);
7923 			ctl_set_reservation_conflict(ctsio);
7924 			ctl_done((union ctl_io *)ctsio);
7925 			return (CTL_RETVAL_COMPLETE);
7926 		}
7927 		mtx_unlock(&softc->ctl_lock);
7928 	}
7929 
7930 	switch (cdb->action & SPRO_ACTION_MASK) {
7931 	case SPRO_REGISTER:
7932 	case SPRO_REG_IGNO: {
7933 
7934 #if 0
7935 		printf("Registration received\n");
7936 #endif
7937 
7938 		/*
7939 		 * We don't support any of these options, as we report in
7940 		 * the read capabilities request (see
7941 		 * ctl_persistent_reserve_in(), above).
7942 		 */
7943 		if ((param->flags & SPR_SPEC_I_PT)
7944 		 || (param->flags & SPR_ALL_TG_PT)
7945 		 || (param->flags & SPR_APTPL)) {
7946 			int bit_ptr;
7947 
7948 			if (param->flags & SPR_APTPL)
7949 				bit_ptr = 0;
7950 			else if (param->flags & SPR_ALL_TG_PT)
7951 				bit_ptr = 2;
7952 			else /* SPR_SPEC_I_PT */
7953 				bit_ptr = 3;
7954 
7955 			free(ctsio->kern_data_ptr, M_CTL);
7956 			ctl_set_invalid_field(ctsio,
7957 					      /*sks_valid*/ 1,
7958 					      /*command*/ 0,
7959 					      /*field*/ 20,
7960 					      /*bit_valid*/ 1,
7961 					      /*bit*/ bit_ptr);
7962 			ctl_done((union ctl_io *)ctsio);
7963 			return (CTL_RETVAL_COMPLETE);
7964 		}
7965 
7966 		mtx_lock(&softc->ctl_lock);
7967 
7968 		/*
7969 		 * The initiator wants to clear the
7970 		 * key/unregister.
7971 		 */
7972 		if (sa_res_key == 0) {
7973 			if ((res_key == 0
7974 			  && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
7975 			 || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
7976 			  && !lun->per_res[residx].registered)) {
7977 				mtx_unlock(&softc->ctl_lock);
7978 				goto done;
7979 			}
7980 
7981 			lun->per_res[residx].registered = 0;
7982 			memset(&lun->per_res[residx].res_key,
7983 			       0, sizeof(lun->per_res[residx].res_key));
7984 			lun->pr_key_count--;
7985 
7986 			if (residx == lun->pr_res_idx) {
7987 				lun->flags &= ~CTL_LUN_PR_RESERVED;
7988 				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
7989 
7990 				if ((lun->res_type == SPR_TYPE_WR_EX_RO
7991 				  || lun->res_type == SPR_TYPE_EX_AC_RO)
7992 				 && lun->pr_key_count) {
7993 					/*
7994 					 * If the reservation is a registrants
7995 					 * only type we need to generate a UA
7996 					 * for other registered inits.  The
7997 					 * sense code should be RESERVATIONS
7998 					 * RELEASED
7999 					 */
8000 
8001 					for (i = 0; i < CTL_MAX_INITIATORS;i++){
8002 						if (lun->per_res[
8003 						    i+persis_offset].registered
8004 						    == 0)
8005 							continue;
8006 						lun->pending_sense[i
8007 							].ua_pending |=
8008 							CTL_UA_RES_RELEASE;
8009 					}
8010 				}
8011 				lun->res_type = 0;
8012 			} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8013 				if (lun->pr_key_count==0) {
8014 					lun->flags &= ~CTL_LUN_PR_RESERVED;
8015 					lun->res_type = 0;
8016 					lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8017 				}
8018 			}
8019 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8020 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8021 			persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8022 			persis_io.pr.pr_info.residx = residx;
8023 			if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8024 			     &persis_io, sizeof(persis_io), 0 )) >
8025 			     CTL_HA_STATUS_SUCCESS) {
8026 				printf("CTL:Persis Out error returned from "
8027 				       "ctl_ha_msg_send %d\n", isc_retval);
8028 			}
8029 			mtx_unlock(&softc->ctl_lock);
8030 		} else /* sa_res_key != 0 */ {
8031 
8032 			/*
8033 			 * If we aren't registered currently then increment
8034 			 * the key count and set the registered flag.
8035 			 */
8036 			if (!lun->per_res[residx].registered) {
8037 				lun->pr_key_count++;
8038 				lun->per_res[residx].registered = 1;
8039 			}
8040 
8041 			memcpy(&lun->per_res[residx].res_key,
8042 			       param->serv_act_res_key,
8043 			       ctl_min(sizeof(param->serv_act_res_key),
8044 			       sizeof(lun->per_res[residx].res_key)));
8045 
8046 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8047 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8048 			persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8049 			persis_io.pr.pr_info.residx = residx;
8050 			memcpy(persis_io.pr.pr_info.sa_res_key,
8051 			       param->serv_act_res_key,
8052 			       sizeof(param->serv_act_res_key));
8053 			mtx_unlock(&softc->ctl_lock);
8054 			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8055 			     &persis_io, sizeof(persis_io), 0)) >
8056 			     CTL_HA_STATUS_SUCCESS) {
8057 				printf("CTL:Persis Out error returned from "
8058 				       "ctl_ha_msg_send %d\n", isc_retval);
8059 			}
8060 		}
8061 		lun->PRGeneration++;
8062 
8063 		break;
8064 	}
8065 	case SPRO_RESERVE:
8066 #if 0
8067                 printf("Reserve executed type %d\n", type);
8068 #endif
8069 		mtx_lock(&softc->ctl_lock);
8070 		if (lun->flags & CTL_LUN_PR_RESERVED) {
8071 			/*
8072 			 * if this isn't the reservation holder and it's
8073 			 * not a "all registrants" type or if the type is
8074 			 * different then we have a conflict
8075 			 */
8076 			if ((lun->pr_res_idx != residx
8077 			  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8078 			 || lun->res_type != type) {
8079 				mtx_unlock(&softc->ctl_lock);
8080 				free(ctsio->kern_data_ptr, M_CTL);
8081 				ctl_set_reservation_conflict(ctsio);
8082 				ctl_done((union ctl_io *)ctsio);
8083 				return (CTL_RETVAL_COMPLETE);
8084 			}
8085 		} else /* create a reservation */ {
8086 			/*
8087 			 * If it's not an "all registrants" type record
8088 			 * reservation holder
8089 			 */
8090 			if (type != SPR_TYPE_WR_EX_AR
8091 			 && type != SPR_TYPE_EX_AC_AR)
8092 				lun->pr_res_idx = residx; /* Res holder */
8093 			else
8094 				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8095 
8096 			lun->flags |= CTL_LUN_PR_RESERVED;
8097 			lun->res_type = type;
8098 
8099 			mtx_unlock(&softc->ctl_lock);
8100 
8101 			/* send msg to other side */
8102 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8103 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8104 			persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8105 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8106 			persis_io.pr.pr_info.res_type = type;
8107 			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8108 			     &persis_io, sizeof(persis_io), 0)) >
8109 			     CTL_HA_STATUS_SUCCESS) {
8110 				printf("CTL:Persis Out error returned from "
8111 				       "ctl_ha_msg_send %d\n", isc_retval);
8112 			}
8113 		}
8114 		break;
8115 
8116 	case SPRO_RELEASE:
8117 		mtx_lock(&softc->ctl_lock);
8118 		if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8119 			/* No reservation exists return good status */
8120 			mtx_unlock(&softc->ctl_lock);
8121 			goto done;
8122 		}
8123 		/*
8124 		 * Is this nexus a reservation holder?
8125 		 */
8126 		if (lun->pr_res_idx != residx
8127 		 && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8128 			/*
8129 			 * not a res holder return good status but
8130 			 * do nothing
8131 			 */
8132 			mtx_unlock(&softc->ctl_lock);
8133 			goto done;
8134 		}
8135 
8136 		if (lun->res_type != type) {
8137 			mtx_unlock(&softc->ctl_lock);
8138 			free(ctsio->kern_data_ptr, M_CTL);
8139 			ctl_set_illegal_pr_release(ctsio);
8140 			ctl_done((union ctl_io *)ctsio);
8141 			return (CTL_RETVAL_COMPLETE);
8142 		}
8143 
8144 		/* okay to release */
8145 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8146 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8147 		lun->res_type = 0;
8148 
8149 		/*
8150 		 * if this isn't an exclusive access
8151 		 * res generate UA for all other
8152 		 * registrants.
8153 		 */
8154 		if (type != SPR_TYPE_EX_AC
8155 		 && type != SPR_TYPE_WR_EX) {
8156 			/*
8157 			 * temporarily unregister so we don't generate UA
8158 			 */
8159 			lun->per_res[residx].registered = 0;
8160 
8161 			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8162 				if (lun->per_res[i+persis_offset].registered
8163 				    == 0)
8164 					continue;
8165 				lun->pending_sense[i].ua_pending |=
8166 					CTL_UA_RES_RELEASE;
8167 			}
8168 
8169 			lun->per_res[residx].registered = 1;
8170 		}
8171 		mtx_unlock(&softc->ctl_lock);
8172 		/* Send msg to other side */
8173 		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8174 		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8175 		persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8176 		if ((isc_retval=ctl_ha_msg_send( CTL_HA_CHAN_CTL, &persis_io,
8177 		     sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8178 			printf("CTL:Persis Out error returned from "
8179 			       "ctl_ha_msg_send %d\n", isc_retval);
8180 		}
8181 		break;
8182 
8183 	case SPRO_CLEAR:
8184 		/* send msg to other side */
8185 
8186 		mtx_lock(&softc->ctl_lock);
8187 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8188 		lun->res_type = 0;
8189 		lun->pr_key_count = 0;
8190 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8191 
8192 
8193 		memset(&lun->per_res[residx].res_key,
8194 		       0, sizeof(lun->per_res[residx].res_key));
8195 		lun->per_res[residx].registered = 0;
8196 
8197 		for (i=0; i < 2*CTL_MAX_INITIATORS; i++)
8198 			if (lun->per_res[i].registered) {
8199 				if (!persis_offset && i < CTL_MAX_INITIATORS)
8200 					lun->pending_sense[i].ua_pending |=
8201 						CTL_UA_RES_PREEMPT;
8202 				else if (persis_offset && i >= persis_offset)
8203 					lun->pending_sense[i-persis_offset
8204 					    ].ua_pending |= CTL_UA_RES_PREEMPT;
8205 
8206 				memset(&lun->per_res[i].res_key,
8207 				       0, sizeof(struct scsi_per_res_key));
8208 				lun->per_res[i].registered = 0;
8209 			}
8210 		lun->PRGeneration++;
8211 		mtx_unlock(&softc->ctl_lock);
8212 		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8213 		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8214 		persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8215 		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8216 		     sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8217 			printf("CTL:Persis Out error returned from "
8218 			       "ctl_ha_msg_send %d\n", isc_retval);
8219 		}
8220 		break;
8221 
8222 	case SPRO_PREEMPT: {
8223 		int nretval;
8224 
8225 		nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8226 					  residx, ctsio, cdb, param);
8227 		if (nretval != 0)
8228 			return (CTL_RETVAL_COMPLETE);
8229 		break;
8230 	}
8231 	case SPRO_REG_MOVE:
8232 	case SPRO_PRE_ABO:
8233 	default:
8234 		free(ctsio->kern_data_ptr, M_CTL);
8235 		ctl_set_invalid_field(/*ctsio*/ ctsio,
8236 				      /*sks_valid*/ 1,
8237 				      /*command*/ 1,
8238 				      /*field*/ 1,
8239 				      /*bit_valid*/ 1,
8240 				      /*bit*/ 0);
8241 		ctl_done((union ctl_io *)ctsio);
8242 		return (CTL_RETVAL_COMPLETE);
8243 		break; /* NOTREACHED */
8244 	}
8245 
8246 done:
8247 	free(ctsio->kern_data_ptr, M_CTL);
8248 	ctl_set_success(ctsio);
8249 	ctl_done((union ctl_io *)ctsio);
8250 
8251 	return (retval);
8252 }
8253 
8254 /*
8255  * This routine is for handling a message from the other SC pertaining to
8256  * persistent reserve out. All the error checking will have been done
8257  * so only perorming the action need be done here to keep the two
8258  * in sync.
8259  */
8260 static void
8261 ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg)
8262 {
8263 	struct ctl_lun *lun;
8264 	struct ctl_softc *softc;
8265 	int i;
8266 	uint32_t targ_lun;
8267 
8268 	softc = control_softc;
8269 
8270 	mtx_lock(&softc->ctl_lock);
8271 
8272 	targ_lun = msg->hdr.nexus.targ_lun;
8273 	if (msg->hdr.nexus.lun_map_fn != NULL)
8274 		targ_lun = msg->hdr.nexus.lun_map_fn(msg->hdr.nexus.lun_map_arg, targ_lun);
8275 	lun = softc->ctl_luns[targ_lun];
8276 	switch(msg->pr.pr_info.action) {
8277 	case CTL_PR_REG_KEY:
8278 		if (!lun->per_res[msg->pr.pr_info.residx].registered) {
8279 			lun->per_res[msg->pr.pr_info.residx].registered = 1;
8280 			lun->pr_key_count++;
8281 		}
8282 		lun->PRGeneration++;
8283 		memcpy(&lun->per_res[msg->pr.pr_info.residx].res_key,
8284 		       msg->pr.pr_info.sa_res_key,
8285 		       sizeof(struct scsi_per_res_key));
8286 		break;
8287 
8288 	case CTL_PR_UNREG_KEY:
8289 		lun->per_res[msg->pr.pr_info.residx].registered = 0;
8290 		memset(&lun->per_res[msg->pr.pr_info.residx].res_key,
8291 		       0, sizeof(struct scsi_per_res_key));
8292 		lun->pr_key_count--;
8293 
8294 		/* XXX Need to see if the reservation has been released */
8295 		/* if so do we need to generate UA? */
8296 		if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8297 			lun->flags &= ~CTL_LUN_PR_RESERVED;
8298 			lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8299 
8300 			if ((lun->res_type == SPR_TYPE_WR_EX_RO
8301 			  || lun->res_type == SPR_TYPE_EX_AC_RO)
8302 			 && lun->pr_key_count) {
8303 				/*
8304 				 * If the reservation is a registrants
8305 				 * only type we need to generate a UA
8306 				 * for other registered inits.  The
8307 				 * sense code should be RESERVATIONS
8308 				 * RELEASED
8309 				 */
8310 
8311 				for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8312 					if (lun->per_res[i+
8313 					    persis_offset].registered == 0)
8314 						continue;
8315 
8316 					lun->pending_sense[i
8317 						].ua_pending |=
8318 						CTL_UA_RES_RELEASE;
8319 				}
8320 			}
8321 			lun->res_type = 0;
8322 		} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8323 			if (lun->pr_key_count==0) {
8324 				lun->flags &= ~CTL_LUN_PR_RESERVED;
8325 				lun->res_type = 0;
8326 				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8327 			}
8328 		}
8329 		lun->PRGeneration++;
8330 		break;
8331 
8332 	case CTL_PR_RESERVE:
8333 		lun->flags |= CTL_LUN_PR_RESERVED;
8334 		lun->res_type = msg->pr.pr_info.res_type;
8335 		lun->pr_res_idx = msg->pr.pr_info.residx;
8336 
8337 		break;
8338 
8339 	case CTL_PR_RELEASE:
8340 		/*
8341 		 * if this isn't an exclusive access res generate UA for all
8342 		 * other registrants.
8343 		 */
8344 		if (lun->res_type != SPR_TYPE_EX_AC
8345 		 && lun->res_type != SPR_TYPE_WR_EX) {
8346 			for (i = 0; i < CTL_MAX_INITIATORS; i++)
8347 				if (lun->per_res[i+persis_offset].registered)
8348 					lun->pending_sense[i].ua_pending |=
8349 						CTL_UA_RES_RELEASE;
8350 		}
8351 
8352 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8353 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8354 		lun->res_type = 0;
8355 		break;
8356 
8357 	case CTL_PR_PREEMPT:
8358 		ctl_pro_preempt_other(lun, msg);
8359 		break;
8360 	case CTL_PR_CLEAR:
8361 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8362 		lun->res_type = 0;
8363 		lun->pr_key_count = 0;
8364 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8365 
8366 		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8367 			if (lun->per_res[i].registered == 0)
8368 				continue;
8369 			if (!persis_offset
8370 			 && i < CTL_MAX_INITIATORS)
8371 				lun->pending_sense[i].ua_pending |=
8372 					CTL_UA_RES_PREEMPT;
8373 			else if (persis_offset
8374 			      && i >= persis_offset)
8375    				lun->pending_sense[i-persis_offset].ua_pending|=
8376 					CTL_UA_RES_PREEMPT;
8377 			memset(&lun->per_res[i].res_key, 0,
8378 			       sizeof(struct scsi_per_res_key));
8379 			lun->per_res[i].registered = 0;
8380 		}
8381 		lun->PRGeneration++;
8382 		break;
8383 	}
8384 
8385 	mtx_unlock(&softc->ctl_lock);
8386 }
8387 
8388 int
8389 ctl_read_write(struct ctl_scsiio *ctsio)
8390 {
8391 	struct ctl_lun *lun;
8392 	struct ctl_lba_len lbalen;
8393 	uint64_t lba;
8394 	uint32_t num_blocks;
8395 	int reladdr, fua, dpo, ebp;
8396 	int retval;
8397 	int isread;
8398 
8399 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8400 
8401 	CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8402 
8403 	reladdr = 0;
8404 	fua = 0;
8405 	dpo = 0;
8406 	ebp = 0;
8407 
8408 	retval = CTL_RETVAL_COMPLETE;
8409 
8410 	isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8411 	      || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8412 	if (lun->flags & CTL_LUN_PR_RESERVED && isread) {
8413 		uint32_t residx;
8414 
8415 		/*
8416 		 * XXX KDM need a lock here.
8417 		 */
8418 		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
8419 		if ((lun->res_type == SPR_TYPE_EX_AC
8420 		  && residx != lun->pr_res_idx)
8421 		 || ((lun->res_type == SPR_TYPE_EX_AC_RO
8422 		   || lun->res_type == SPR_TYPE_EX_AC_AR)
8423 		  && !lun->per_res[residx].registered)) {
8424 			ctl_set_reservation_conflict(ctsio);
8425 			ctl_done((union ctl_io *)ctsio);
8426 			return (CTL_RETVAL_COMPLETE);
8427 	        }
8428 	}
8429 
8430 	switch (ctsio->cdb[0]) {
8431 	case READ_6:
8432 	case WRITE_6: {
8433 		struct scsi_rw_6 *cdb;
8434 
8435 		cdb = (struct scsi_rw_6 *)ctsio->cdb;
8436 
8437 		lba = scsi_3btoul(cdb->addr);
8438 		/* only 5 bits are valid in the most significant address byte */
8439 		lba &= 0x1fffff;
8440 		num_blocks = cdb->length;
8441 		/*
8442 		 * This is correct according to SBC-2.
8443 		 */
8444 		if (num_blocks == 0)
8445 			num_blocks = 256;
8446 		break;
8447 	}
8448 	case READ_10:
8449 	case WRITE_10: {
8450 		struct scsi_rw_10 *cdb;
8451 
8452 		cdb = (struct scsi_rw_10 *)ctsio->cdb;
8453 
8454 		if (cdb->byte2 & SRW10_RELADDR)
8455 			reladdr = 1;
8456 		if (cdb->byte2 & SRW10_FUA)
8457 			fua = 1;
8458 		if (cdb->byte2 & SRW10_DPO)
8459 			dpo = 1;
8460 
8461 		if ((cdb->opcode == WRITE_10)
8462 		 && (cdb->byte2 & SRW10_EBP))
8463 			ebp = 1;
8464 
8465 		lba = scsi_4btoul(cdb->addr);
8466 		num_blocks = scsi_2btoul(cdb->length);
8467 		break;
8468 	}
8469 	case WRITE_VERIFY_10: {
8470 		struct scsi_write_verify_10 *cdb;
8471 
8472 		cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
8473 
8474 		/*
8475 		 * XXX KDM we should do actual write verify support at some
8476 		 * point.  This is obviously fake, we're just translating
8477 		 * things to a write.  So we don't even bother checking the
8478 		 * BYTCHK field, since we don't do any verification.  If
8479 		 * the user asks for it, we'll just pretend we did it.
8480 		 */
8481 		if (cdb->byte2 & SWV_DPO)
8482 			dpo = 1;
8483 
8484 		lba = scsi_4btoul(cdb->addr);
8485 		num_blocks = scsi_2btoul(cdb->length);
8486 		break;
8487 	}
8488 	case READ_12:
8489 	case WRITE_12: {
8490 		struct scsi_rw_12 *cdb;
8491 
8492 		cdb = (struct scsi_rw_12 *)ctsio->cdb;
8493 
8494 		if (cdb->byte2 & SRW12_RELADDR)
8495 			reladdr = 1;
8496 		if (cdb->byte2 & SRW12_FUA)
8497 			fua = 1;
8498 		if (cdb->byte2 & SRW12_DPO)
8499 			dpo = 1;
8500 		lba = scsi_4btoul(cdb->addr);
8501 		num_blocks = scsi_4btoul(cdb->length);
8502 		break;
8503 	}
8504 	case WRITE_VERIFY_12: {
8505 		struct scsi_write_verify_12 *cdb;
8506 
8507 		cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
8508 
8509 		if (cdb->byte2 & SWV_DPO)
8510 			dpo = 1;
8511 
8512 		lba = scsi_4btoul(cdb->addr);
8513 		num_blocks = scsi_4btoul(cdb->length);
8514 
8515 		break;
8516 	}
8517 	case READ_16:
8518 	case WRITE_16: {
8519 		struct scsi_rw_16 *cdb;
8520 
8521 		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8522 
8523 		if (cdb->byte2 & SRW12_RELADDR)
8524 			reladdr = 1;
8525 		if (cdb->byte2 & SRW12_FUA)
8526 			fua = 1;
8527 		if (cdb->byte2 & SRW12_DPO)
8528 			dpo = 1;
8529 
8530 		lba = scsi_8btou64(cdb->addr);
8531 		num_blocks = scsi_4btoul(cdb->length);
8532 		break;
8533 	}
8534 	case WRITE_VERIFY_16: {
8535 		struct scsi_write_verify_16 *cdb;
8536 
8537 		cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
8538 
8539 		if (cdb->byte2 & SWV_DPO)
8540 			dpo = 1;
8541 
8542 		lba = scsi_8btou64(cdb->addr);
8543 		num_blocks = scsi_4btoul(cdb->length);
8544 		break;
8545 	}
8546 	default:
8547 		/*
8548 		 * We got a command we don't support.  This shouldn't
8549 		 * happen, commands should be filtered out above us.
8550 		 */
8551 		ctl_set_invalid_opcode(ctsio);
8552 		ctl_done((union ctl_io *)ctsio);
8553 
8554 		return (CTL_RETVAL_COMPLETE);
8555 		break; /* NOTREACHED */
8556 	}
8557 
8558 	/*
8559 	 * XXX KDM what do we do with the DPO and FUA bits?  FUA might be
8560 	 * interesting for us, but if RAIDCore is in write-back mode,
8561 	 * getting it to do write-through for a particular transaction may
8562 	 * not be possible.
8563 	 */
8564 	/*
8565 	 * We don't support relative addressing.  That also requires
8566 	 * supporting linked commands, which we don't do.
8567 	 */
8568 	if (reladdr != 0) {
8569 		ctl_set_invalid_field(ctsio,
8570 				      /*sks_valid*/ 1,
8571 				      /*command*/ 1,
8572 				      /*field*/ 1,
8573 				      /*bit_valid*/ 1,
8574 				      /*bit*/ 0);
8575 		ctl_done((union ctl_io *)ctsio);
8576 		return (CTL_RETVAL_COMPLETE);
8577 	}
8578 
8579 	/*
8580 	 * The first check is to make sure we're in bounds, the second
8581 	 * check is to catch wrap-around problems.  If the lba + num blocks
8582 	 * is less than the lba, then we've wrapped around and the block
8583 	 * range is invalid anyway.
8584 	 */
8585 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8586 	 || ((lba + num_blocks) < lba)) {
8587 		ctl_set_lba_out_of_range(ctsio);
8588 		ctl_done((union ctl_io *)ctsio);
8589 		return (CTL_RETVAL_COMPLETE);
8590 	}
8591 
8592 	/*
8593 	 * According to SBC-3, a transfer length of 0 is not an error.
8594 	 * Note that this cannot happen with WRITE(6) or READ(6), since 0
8595 	 * translates to 256 blocks for those commands.
8596 	 */
8597 	if (num_blocks == 0) {
8598 		ctl_set_success(ctsio);
8599 		ctl_done((union ctl_io *)ctsio);
8600 		return (CTL_RETVAL_COMPLETE);
8601 	}
8602 
8603 	lbalen.lba = lba;
8604 	lbalen.len = num_blocks;
8605 	memcpy(ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes, &lbalen,
8606 	       sizeof(lbalen));
8607 
8608 	CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
8609 
8610 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8611 
8612 	return (retval);
8613 }
8614 
8615 int
8616 ctl_report_luns(struct ctl_scsiio *ctsio)
8617 {
8618 	struct scsi_report_luns *cdb;
8619 	struct scsi_report_luns_data *lun_data;
8620 	struct ctl_lun *lun, *request_lun;
8621 	int num_luns, retval;
8622 	uint32_t alloc_len, lun_datalen;
8623 	int num_filled, well_known;
8624 	uint32_t initidx, targ_lun_id, lun_id;
8625 
8626 	retval = CTL_RETVAL_COMPLETE;
8627 	well_known = 0;
8628 
8629 	cdb = (struct scsi_report_luns *)ctsio->cdb;
8630 
8631 	CTL_DEBUG_PRINT(("ctl_report_luns\n"));
8632 
8633 	mtx_lock(&control_softc->ctl_lock);
8634 	num_luns = control_softc->num_luns;
8635 	mtx_unlock(&control_softc->ctl_lock);
8636 
8637 	switch (cdb->select_report) {
8638 	case RPL_REPORT_DEFAULT:
8639 	case RPL_REPORT_ALL:
8640 		break;
8641 	case RPL_REPORT_WELLKNOWN:
8642 		well_known = 1;
8643 		num_luns = 0;
8644 		break;
8645 	default:
8646 		ctl_set_invalid_field(ctsio,
8647 				      /*sks_valid*/ 1,
8648 				      /*command*/ 1,
8649 				      /*field*/ 2,
8650 				      /*bit_valid*/ 0,
8651 				      /*bit*/ 0);
8652 		ctl_done((union ctl_io *)ctsio);
8653 		return (retval);
8654 		break; /* NOTREACHED */
8655 	}
8656 
8657 	alloc_len = scsi_4btoul(cdb->length);
8658 	/*
8659 	 * The initiator has to allocate at least 16 bytes for this request,
8660 	 * so he can at least get the header and the first LUN.  Otherwise
8661 	 * we reject the request (per SPC-3 rev 14, section 6.21).
8662 	 */
8663 	if (alloc_len < (sizeof(struct scsi_report_luns_data) +
8664 	    sizeof(struct scsi_report_luns_lundata))) {
8665 		ctl_set_invalid_field(ctsio,
8666 				      /*sks_valid*/ 1,
8667 				      /*command*/ 1,
8668 				      /*field*/ 6,
8669 				      /*bit_valid*/ 0,
8670 				      /*bit*/ 0);
8671 		ctl_done((union ctl_io *)ctsio);
8672 		return (retval);
8673 	}
8674 
8675 	request_lun = (struct ctl_lun *)
8676 		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8677 
8678 	lun_datalen = sizeof(*lun_data) +
8679 		(num_luns * sizeof(struct scsi_report_luns_lundata));
8680 
8681 	ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
8682 	lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
8683 	ctsio->kern_sg_entries = 0;
8684 
8685 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
8686 
8687 	mtx_lock(&control_softc->ctl_lock);
8688 	for (targ_lun_id = 0, num_filled = 0; targ_lun_id < CTL_MAX_LUNS && num_filled < num_luns; targ_lun_id++) {
8689 		lun_id = targ_lun_id;
8690 		if (ctsio->io_hdr.nexus.lun_map_fn != NULL)
8691 			lun_id = ctsio->io_hdr.nexus.lun_map_fn(ctsio->io_hdr.nexus.lun_map_arg, lun_id);
8692 		if (lun_id >= CTL_MAX_LUNS)
8693 			continue;
8694 		lun = control_softc->ctl_luns[lun_id];
8695 		if (lun == NULL)
8696 			continue;
8697 
8698 		if (targ_lun_id <= 0xff) {
8699 			/*
8700 			 * Peripheral addressing method, bus number 0.
8701 			 */
8702 			lun_data->luns[num_filled].lundata[0] =
8703 				RPL_LUNDATA_ATYP_PERIPH;
8704 			lun_data->luns[num_filled].lundata[1] = targ_lun_id;
8705 			num_filled++;
8706 		} else if (targ_lun_id <= 0x3fff) {
8707 			/*
8708 			 * Flat addressing method.
8709 			 */
8710 			lun_data->luns[num_filled].lundata[0] =
8711 				RPL_LUNDATA_ATYP_FLAT |
8712 				(targ_lun_id & RPL_LUNDATA_FLAT_LUN_MASK);
8713 #ifdef OLDCTLHEADERS
8714 				(SRLD_ADDR_FLAT << SRLD_ADDR_SHIFT) |
8715 				(targ_lun_id & SRLD_BUS_LUN_MASK);
8716 #endif
8717 			lun_data->luns[num_filled].lundata[1] =
8718 #ifdef OLDCTLHEADERS
8719 				targ_lun_id >> SRLD_BUS_LUN_BITS;
8720 #endif
8721 				targ_lun_id >> RPL_LUNDATA_FLAT_LUN_BITS;
8722 			num_filled++;
8723 		} else {
8724 			printf("ctl_report_luns: bogus LUN number %jd, "
8725 			       "skipping\n", (intmax_t)targ_lun_id);
8726 		}
8727 		/*
8728 		 * According to SPC-3, rev 14 section 6.21:
8729 		 *
8730 		 * "The execution of a REPORT LUNS command to any valid and
8731 		 * installed logical unit shall clear the REPORTED LUNS DATA
8732 		 * HAS CHANGED unit attention condition for all logical
8733 		 * units of that target with respect to the requesting
8734 		 * initiator. A valid and installed logical unit is one
8735 		 * having a PERIPHERAL QUALIFIER of 000b in the standard
8736 		 * INQUIRY data (see 6.4.2)."
8737 		 *
8738 		 * If request_lun is NULL, the LUN this report luns command
8739 		 * was issued to is either disabled or doesn't exist. In that
8740 		 * case, we shouldn't clear any pending lun change unit
8741 		 * attention.
8742 		 */
8743 		if (request_lun != NULL)
8744 			lun->pending_sense[initidx].ua_pending &=
8745 				~CTL_UA_LUN_CHANGE;
8746 	}
8747 	mtx_unlock(&control_softc->ctl_lock);
8748 
8749 	/*
8750 	 * It's quite possible that we've returned fewer LUNs than we allocated
8751 	 * space for.  Trim it.
8752 	 */
8753 	lun_datalen = sizeof(*lun_data) +
8754 		(num_filled * sizeof(struct scsi_report_luns_lundata));
8755 
8756 	if (lun_datalen < alloc_len) {
8757 		ctsio->residual = alloc_len - lun_datalen;
8758 		ctsio->kern_data_len = lun_datalen;
8759 		ctsio->kern_total_len = lun_datalen;
8760 	} else {
8761 		ctsio->residual = 0;
8762 		ctsio->kern_data_len = alloc_len;
8763 		ctsio->kern_total_len = alloc_len;
8764 	}
8765 	ctsio->kern_data_resid = 0;
8766 	ctsio->kern_rel_offset = 0;
8767 	ctsio->kern_sg_entries = 0;
8768 
8769 	/*
8770 	 * We set this to the actual data length, regardless of how much
8771 	 * space we actually have to return results.  If the user looks at
8772 	 * this value, he'll know whether or not he allocated enough space
8773 	 * and reissue the command if necessary.  We don't support well
8774 	 * known logical units, so if the user asks for that, return none.
8775 	 */
8776 	scsi_ulto4b(lun_datalen - 8, lun_data->length);
8777 
8778 	/*
8779 	 * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
8780 	 * this request.
8781 	 */
8782 	ctsio->scsi_status = SCSI_STATUS_OK;
8783 
8784 	ctsio->be_move_done = ctl_config_move_done;
8785 	ctl_datamove((union ctl_io *)ctsio);
8786 
8787 	return (retval);
8788 }
8789 
8790 int
8791 ctl_request_sense(struct ctl_scsiio *ctsio)
8792 {
8793 	struct scsi_request_sense *cdb;
8794 	struct scsi_sense_data *sense_ptr;
8795 	struct ctl_lun *lun;
8796 	uint32_t initidx;
8797 	int have_error;
8798 	scsi_sense_data_type sense_format;
8799 
8800 	cdb = (struct scsi_request_sense *)ctsio->cdb;
8801 
8802 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8803 
8804 	CTL_DEBUG_PRINT(("ctl_request_sense\n"));
8805 
8806 	/*
8807 	 * Determine which sense format the user wants.
8808 	 */
8809 	if (cdb->byte2 & SRS_DESC)
8810 		sense_format = SSD_TYPE_DESC;
8811 	else
8812 		sense_format = SSD_TYPE_FIXED;
8813 
8814 	ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
8815 	sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
8816 	ctsio->kern_sg_entries = 0;
8817 
8818 	/*
8819 	 * struct scsi_sense_data, which is currently set to 256 bytes, is
8820 	 * larger than the largest allowed value for the length field in the
8821 	 * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
8822 	 */
8823 	ctsio->residual = 0;
8824 	ctsio->kern_data_len = cdb->length;
8825 	ctsio->kern_total_len = cdb->length;
8826 
8827 	ctsio->kern_data_resid = 0;
8828 	ctsio->kern_rel_offset = 0;
8829 	ctsio->kern_sg_entries = 0;
8830 
8831 	/*
8832 	 * If we don't have a LUN, we don't have any pending sense.
8833 	 */
8834 	if (lun == NULL)
8835 		goto no_sense;
8836 
8837 	have_error = 0;
8838 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
8839 	/*
8840 	 * Check for pending sense, and then for pending unit attentions.
8841 	 * Pending sense gets returned first, then pending unit attentions.
8842 	 */
8843 	mtx_lock(&lun->ctl_softc->ctl_lock);
8844 	if (ctl_is_set(lun->have_ca, initidx)) {
8845 		scsi_sense_data_type stored_format;
8846 
8847 		/*
8848 		 * Check to see which sense format was used for the stored
8849 		 * sense data.
8850 		 */
8851 		stored_format = scsi_sense_type(
8852 		    &lun->pending_sense[initidx].sense);
8853 
8854 		/*
8855 		 * If the user requested a different sense format than the
8856 		 * one we stored, then we need to convert it to the other
8857 		 * format.  If we're going from descriptor to fixed format
8858 		 * sense data, we may lose things in translation, depending
8859 		 * on what options were used.
8860 		 *
8861 		 * If the stored format is SSD_TYPE_NONE (i.e. invalid),
8862 		 * for some reason we'll just copy it out as-is.
8863 		 */
8864 		if ((stored_format == SSD_TYPE_FIXED)
8865 		 && (sense_format == SSD_TYPE_DESC))
8866 			ctl_sense_to_desc((struct scsi_sense_data_fixed *)
8867 			    &lun->pending_sense[initidx].sense,
8868 			    (struct scsi_sense_data_desc *)sense_ptr);
8869 		else if ((stored_format == SSD_TYPE_DESC)
8870 		      && (sense_format == SSD_TYPE_FIXED))
8871 			ctl_sense_to_fixed((struct scsi_sense_data_desc *)
8872 			    &lun->pending_sense[initidx].sense,
8873 			    (struct scsi_sense_data_fixed *)sense_ptr);
8874 		else
8875 			memcpy(sense_ptr, &lun->pending_sense[initidx].sense,
8876 			       ctl_min(sizeof(*sense_ptr),
8877 			       sizeof(lun->pending_sense[initidx].sense)));
8878 
8879 		ctl_clear_mask(lun->have_ca, initidx);
8880 		have_error = 1;
8881 	} else if (lun->pending_sense[initidx].ua_pending != CTL_UA_NONE) {
8882 		ctl_ua_type ua_type;
8883 
8884 		ua_type = ctl_build_ua(lun->pending_sense[initidx].ua_pending,
8885 				       sense_ptr, sense_format);
8886 		if (ua_type != CTL_UA_NONE) {
8887 			have_error = 1;
8888 			/* We're reporting this UA, so clear it */
8889 			lun->pending_sense[initidx].ua_pending &= ~ua_type;
8890 		}
8891 	}
8892 	mtx_unlock(&lun->ctl_softc->ctl_lock);
8893 
8894 	/*
8895 	 * We already have a pending error, return it.
8896 	 */
8897 	if (have_error != 0) {
8898 		/*
8899 		 * We report the SCSI status as OK, since the status of the
8900 		 * request sense command itself is OK.
8901 		 */
8902 		ctsio->scsi_status = SCSI_STATUS_OK;
8903 
8904 		/*
8905 		 * We report 0 for the sense length, because we aren't doing
8906 		 * autosense in this case.  We're reporting sense as
8907 		 * parameter data.
8908 		 */
8909 		ctsio->sense_len = 0;
8910 
8911 		ctsio->be_move_done = ctl_config_move_done;
8912 		ctl_datamove((union ctl_io *)ctsio);
8913 
8914 		return (CTL_RETVAL_COMPLETE);
8915 	}
8916 
8917 no_sense:
8918 
8919 	/*
8920 	 * No sense information to report, so we report that everything is
8921 	 * okay.
8922 	 */
8923 	ctl_set_sense_data(sense_ptr,
8924 			   lun,
8925 			   sense_format,
8926 			   /*current_error*/ 1,
8927 			   /*sense_key*/ SSD_KEY_NO_SENSE,
8928 			   /*asc*/ 0x00,
8929 			   /*ascq*/ 0x00,
8930 			   SSD_ELEM_NONE);
8931 
8932 	ctsio->scsi_status = SCSI_STATUS_OK;
8933 
8934 	/*
8935 	 * We report 0 for the sense length, because we aren't doing
8936 	 * autosense in this case.  We're reporting sense as parameter data.
8937 	 */
8938 	ctsio->sense_len = 0;
8939 	ctsio->be_move_done = ctl_config_move_done;
8940 	ctl_datamove((union ctl_io *)ctsio);
8941 
8942 	return (CTL_RETVAL_COMPLETE);
8943 }
8944 
8945 int
8946 ctl_tur(struct ctl_scsiio *ctsio)
8947 {
8948 	struct ctl_lun *lun;
8949 
8950 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8951 
8952 	CTL_DEBUG_PRINT(("ctl_tur\n"));
8953 
8954 	if (lun == NULL)
8955 		return (-EINVAL);
8956 
8957 	ctsio->scsi_status = SCSI_STATUS_OK;
8958 	ctsio->io_hdr.status = CTL_SUCCESS;
8959 
8960 	ctl_done((union ctl_io *)ctsio);
8961 
8962 	return (CTL_RETVAL_COMPLETE);
8963 }
8964 
8965 #ifdef notyet
8966 static int
8967 ctl_cmddt_inquiry(struct ctl_scsiio *ctsio)
8968 {
8969 
8970 }
8971 #endif
8972 
8973 static int
8974 ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
8975 {
8976 	struct scsi_vpd_supported_pages *pages;
8977 	int sup_page_size;
8978 	struct ctl_lun *lun;
8979 
8980 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8981 
8982 	sup_page_size = sizeof(struct scsi_vpd_supported_pages) +
8983 		SCSI_EVPD_NUM_SUPPORTED_PAGES;
8984 	ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
8985 	pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
8986 	ctsio->kern_sg_entries = 0;
8987 
8988 	if (sup_page_size < alloc_len) {
8989 		ctsio->residual = alloc_len - sup_page_size;
8990 		ctsio->kern_data_len = sup_page_size;
8991 		ctsio->kern_total_len = sup_page_size;
8992 	} else {
8993 		ctsio->residual = 0;
8994 		ctsio->kern_data_len = alloc_len;
8995 		ctsio->kern_total_len = alloc_len;
8996 	}
8997 	ctsio->kern_data_resid = 0;
8998 	ctsio->kern_rel_offset = 0;
8999 	ctsio->kern_sg_entries = 0;
9000 
9001 	/*
9002 	 * The control device is always connected.  The disk device, on the
9003 	 * other hand, may not be online all the time.  Need to change this
9004 	 * to figure out whether the disk device is actually online or not.
9005 	 */
9006 	if (lun != NULL)
9007 		pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9008 				lun->be_lun->lun_type;
9009 	else
9010 		pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9011 
9012 	pages->length = SCSI_EVPD_NUM_SUPPORTED_PAGES;
9013 	/* Supported VPD pages */
9014 	pages->page_list[0] = SVPD_SUPPORTED_PAGES;
9015 	/* Serial Number */
9016 	pages->page_list[1] = SVPD_UNIT_SERIAL_NUMBER;
9017 	/* Device Identification */
9018 	pages->page_list[2] = SVPD_DEVICE_ID;
9019 
9020 	ctsio->scsi_status = SCSI_STATUS_OK;
9021 
9022 	ctsio->be_move_done = ctl_config_move_done;
9023 	ctl_datamove((union ctl_io *)ctsio);
9024 
9025 	return (CTL_RETVAL_COMPLETE);
9026 }
9027 
9028 static int
9029 ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9030 {
9031 	struct scsi_vpd_unit_serial_number *sn_ptr;
9032 	struct ctl_lun *lun;
9033 #ifndef CTL_USE_BACKEND_SN
9034 	char tmpstr[32];
9035 #endif
9036 
9037 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9038 
9039 	ctsio->kern_data_ptr = malloc(sizeof(*sn_ptr), M_CTL, M_WAITOK | M_ZERO);
9040 	sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9041 	ctsio->kern_sg_entries = 0;
9042 
9043 	if (sizeof(*sn_ptr) < alloc_len) {
9044 		ctsio->residual = alloc_len - sizeof(*sn_ptr);
9045 		ctsio->kern_data_len = sizeof(*sn_ptr);
9046 		ctsio->kern_total_len = sizeof(*sn_ptr);
9047 	} else {
9048 		ctsio->residual = 0;
9049 		ctsio->kern_data_len = alloc_len;
9050 		ctsio->kern_total_len = alloc_len;
9051 	}
9052 	ctsio->kern_data_resid = 0;
9053 	ctsio->kern_rel_offset = 0;
9054 	ctsio->kern_sg_entries = 0;
9055 
9056 	/*
9057 	 * The control device is always connected.  The disk device, on the
9058 	 * other hand, may not be online all the time.  Need to change this
9059 	 * to figure out whether the disk device is actually online or not.
9060 	 */
9061 	if (lun != NULL)
9062 		sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9063 				  lun->be_lun->lun_type;
9064 	else
9065 		sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9066 
9067 	sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9068 	sn_ptr->length = ctl_min(sizeof(*sn_ptr) - 4, CTL_SN_LEN);
9069 #ifdef CTL_USE_BACKEND_SN
9070 	/*
9071 	 * If we don't have a LUN, we just leave the serial number as
9072 	 * all spaces.
9073 	 */
9074 	memset(sn_ptr->serial_num, 0x20, sizeof(sn_ptr->serial_num));
9075 	if (lun != NULL) {
9076 		strncpy((char *)sn_ptr->serial_num,
9077 			(char *)lun->be_lun->serial_num, CTL_SN_LEN);
9078 	}
9079 #else
9080 	/*
9081 	 * Note that we're using a non-unique serial number here,
9082 	 */
9083 	snprintf(tmpstr, sizeof(tmpstr), "MYSERIALNUMIS000");
9084 	memset(sn_ptr->serial_num, 0x20, sizeof(sn_ptr->serial_num));
9085 	strncpy(sn_ptr->serial_num, tmpstr, ctl_min(CTL_SN_LEN,
9086 		ctl_min(sizeof(tmpstr), sizeof(*sn_ptr) - 4)));
9087 #endif
9088 	ctsio->scsi_status = SCSI_STATUS_OK;
9089 
9090 	ctsio->be_move_done = ctl_config_move_done;
9091 	ctl_datamove((union ctl_io *)ctsio);
9092 
9093 	return (CTL_RETVAL_COMPLETE);
9094 }
9095 
9096 
9097 static int
9098 ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9099 {
9100 	struct scsi_vpd_device_id *devid_ptr;
9101 	struct scsi_vpd_id_descriptor *desc, *desc1;
9102 	struct scsi_vpd_id_descriptor *desc2, *desc3; /* for types 4h and 5h */
9103 	struct scsi_vpd_id_t10 *t10id;
9104 	struct ctl_softc *ctl_softc;
9105 	struct ctl_lun *lun;
9106 	struct ctl_frontend *fe;
9107 #ifndef CTL_USE_BACKEND_SN
9108 	char tmpstr[32];
9109 #endif /* CTL_USE_BACKEND_SN */
9110 	int devid_len;
9111 
9112 	ctl_softc = control_softc;
9113 
9114 	mtx_lock(&ctl_softc->ctl_lock);
9115 	fe = ctl_softc->ctl_ports[ctl_port_idx(ctsio->io_hdr.nexus.targ_port)];
9116 	mtx_unlock(&ctl_softc->ctl_lock);
9117 
9118 	if (fe->devid != NULL)
9119 		return ((fe->devid)(ctsio, alloc_len));
9120 
9121 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9122 
9123 	devid_len = sizeof(struct scsi_vpd_device_id) +
9124 		sizeof(struct scsi_vpd_id_descriptor) +
9125 		sizeof(struct scsi_vpd_id_t10) + CTL_DEVID_LEN +
9126 		sizeof(struct scsi_vpd_id_descriptor) + CTL_WWPN_LEN +
9127 		sizeof(struct scsi_vpd_id_descriptor) +
9128 		sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9129 		sizeof(struct scsi_vpd_id_descriptor) +
9130 		sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9131 
9132 	ctsio->kern_data_ptr = malloc(devid_len, M_CTL, M_WAITOK | M_ZERO);
9133 	devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9134 	ctsio->kern_sg_entries = 0;
9135 
9136 	if (devid_len < alloc_len) {
9137 		ctsio->residual = alloc_len - devid_len;
9138 		ctsio->kern_data_len = devid_len;
9139 		ctsio->kern_total_len = devid_len;
9140 	} else {
9141 		ctsio->residual = 0;
9142 		ctsio->kern_data_len = alloc_len;
9143 		ctsio->kern_total_len = alloc_len;
9144 	}
9145 	ctsio->kern_data_resid = 0;
9146 	ctsio->kern_rel_offset = 0;
9147 	ctsio->kern_sg_entries = 0;
9148 
9149 	desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
9150 	t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
9151 	desc1 = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9152 		sizeof(struct scsi_vpd_id_t10) + CTL_DEVID_LEN);
9153 	desc2 = (struct scsi_vpd_id_descriptor *)(&desc1->identifier[0] +
9154 	          CTL_WWPN_LEN);
9155 	desc3 = (struct scsi_vpd_id_descriptor *)(&desc2->identifier[0] +
9156 	         sizeof(struct scsi_vpd_id_rel_trgt_port_id));
9157 
9158 	/*
9159 	 * The control device is always connected.  The disk device, on the
9160 	 * other hand, may not be online all the time.
9161 	 */
9162 	if (lun != NULL)
9163 		devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9164 				     lun->be_lun->lun_type;
9165 	else
9166 		devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9167 
9168 	devid_ptr->page_code = SVPD_DEVICE_ID;
9169 
9170 	scsi_ulto2b(devid_len - 4, devid_ptr->length);
9171 
9172 	mtx_lock(&ctl_softc->ctl_lock);
9173 
9174 	/*
9175 	 * For Fibre channel,
9176 	 */
9177 	if (fe->port_type == CTL_PORT_FC)
9178 	{
9179 		desc->proto_codeset = (SCSI_PROTO_FC << 4) |
9180 				      SVPD_ID_CODESET_ASCII;
9181         	desc1->proto_codeset = (SCSI_PROTO_FC << 4) |
9182 		              SVPD_ID_CODESET_BINARY;
9183 	}
9184 	else
9185 	{
9186 		desc->proto_codeset = (SCSI_PROTO_SPI << 4) |
9187 				      SVPD_ID_CODESET_ASCII;
9188         	desc1->proto_codeset = (SCSI_PROTO_SPI << 4) |
9189 		              SVPD_ID_CODESET_BINARY;
9190 	}
9191 	desc2->proto_codeset = desc3->proto_codeset = desc1->proto_codeset;
9192 	mtx_unlock(&ctl_softc->ctl_lock);
9193 
9194 	/*
9195 	 * We're using a LUN association here.  i.e., this device ID is a
9196 	 * per-LUN identifier.
9197 	 */
9198 	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
9199 	desc->length = sizeof(*t10id) + CTL_DEVID_LEN;
9200 	strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
9201 
9202 	/*
9203 	 * desc1 is for the WWPN which is a port asscociation.
9204 	 */
9205 	desc1->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT | SVPD_ID_TYPE_NAA;
9206 	desc1->length = CTL_WWPN_LEN;
9207 	/* XXX Call Reggie's get_WWNN func here then add port # to the end */
9208 	/* For testing just create the WWPN */
9209 #if 0
9210 	ddb_GetWWNN((char *)desc1->identifier);
9211 
9212 	/* NOTE: if the port is 0 or 8 we don't want to subtract 1 */
9213 	/* This is so Copancontrol will return something sane */
9214 	if (ctsio->io_hdr.nexus.targ_port!=0 &&
9215 	    ctsio->io_hdr.nexus.targ_port!=8)
9216 		desc1->identifier[7] += ctsio->io_hdr.nexus.targ_port-1;
9217 	else
9218 		desc1->identifier[7] += ctsio->io_hdr.nexus.targ_port;
9219 #endif
9220 
9221 	be64enc(desc1->identifier, fe->wwpn);
9222 
9223 	/*
9224 	 * desc2 is for the Relative Target Port(type 4h) identifier
9225 	 */
9226 	desc2->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT
9227 	                 | SVPD_ID_TYPE_RELTARG;
9228 	desc2->length = 4;
9229 //#if 0
9230 	/* NOTE: if the port is 0 or 8 we don't want to subtract 1 */
9231 	/* This is so Copancontrol will return something sane */
9232 	if (ctsio->io_hdr.nexus.targ_port!=0 &&
9233 	    ctsio->io_hdr.nexus.targ_port!=8)
9234 		desc2->identifier[3] = ctsio->io_hdr.nexus.targ_port - 1;
9235 	else
9236 	        desc2->identifier[3] = ctsio->io_hdr.nexus.targ_port;
9237 //#endif
9238 
9239 	/*
9240 	 * desc3 is for the Target Port Group(type 5h) identifier
9241 	 */
9242 	desc3->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT
9243 	                 | SVPD_ID_TYPE_TPORTGRP;
9244 	desc3->length = 4;
9245 	if (ctsio->io_hdr.nexus.targ_port < CTL_MAX_PORTS || ctl_is_single)
9246 		desc3->identifier[3] = 1;
9247 	else
9248 		desc3->identifier[3] = 2;
9249 
9250 #ifdef CTL_USE_BACKEND_SN
9251 	/*
9252 	 * If we've actually got a backend, copy the device id from the
9253 	 * per-LUN data.  Otherwise, set it to all spaces.
9254 	 */
9255 	if (lun != NULL) {
9256 		/*
9257 		 * Copy the backend's LUN ID.
9258 		 */
9259 		strncpy((char *)t10id->vendor_spec_id,
9260 			(char *)lun->be_lun->device_id, CTL_DEVID_LEN);
9261 	} else {
9262 		/*
9263 		 * No backend, set this to spaces.
9264 		 */
9265 		memset(t10id->vendor_spec_id, 0x20, CTL_DEVID_LEN);
9266 	}
9267 #else
9268 	snprintf(tmpstr, sizeof(tmpstr), "MYDEVICEIDIS%4d",
9269 		 (lun != NULL) ?  (int)lun->lun : 0);
9270 	strncpy(t10id->vendor_spec_id, tmpstr, ctl_min(CTL_DEVID_LEN,
9271 		sizeof(tmpstr)));
9272 #endif
9273 
9274 	ctsio->scsi_status = SCSI_STATUS_OK;
9275 
9276 	ctsio->be_move_done = ctl_config_move_done;
9277 	ctl_datamove((union ctl_io *)ctsio);
9278 
9279 	return (CTL_RETVAL_COMPLETE);
9280 }
9281 
9282 static int
9283 ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
9284 {
9285 	struct scsi_inquiry *cdb;
9286 	int alloc_len, retval;
9287 
9288 	cdb = (struct scsi_inquiry *)ctsio->cdb;
9289 
9290 	retval = CTL_RETVAL_COMPLETE;
9291 
9292 	alloc_len = scsi_2btoul(cdb->length);
9293 
9294 	switch (cdb->page_code) {
9295 	case SVPD_SUPPORTED_PAGES:
9296 		retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
9297 		break;
9298 	case SVPD_UNIT_SERIAL_NUMBER:
9299 		retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
9300 		break;
9301 	case SVPD_DEVICE_ID:
9302 		retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
9303 		break;
9304 	default:
9305 		ctl_set_invalid_field(ctsio,
9306 				      /*sks_valid*/ 1,
9307 				      /*command*/ 1,
9308 				      /*field*/ 2,
9309 				      /*bit_valid*/ 0,
9310 				      /*bit*/ 0);
9311 		ctl_done((union ctl_io *)ctsio);
9312 		retval = CTL_RETVAL_COMPLETE;
9313 		break;
9314 	}
9315 
9316 	return (retval);
9317 }
9318 
9319 static int
9320 ctl_inquiry_std(struct ctl_scsiio *ctsio)
9321 {
9322 	struct scsi_inquiry_data *inq_ptr;
9323 	struct scsi_inquiry *cdb;
9324 	struct ctl_softc *ctl_softc;
9325 	struct ctl_lun *lun;
9326 	uint32_t alloc_len;
9327 	int is_fc;
9328 
9329 	ctl_softc = control_softc;
9330 
9331 	/*
9332 	 * Figure out whether we're talking to a Fibre Channel port or not.
9333 	 * We treat the ioctl front end, and any SCSI adapters, as packetized
9334 	 * SCSI front ends.
9335 	 */
9336 	mtx_lock(&ctl_softc->ctl_lock);
9337 	if (ctl_softc->ctl_ports[ctl_port_idx(ctsio->io_hdr.nexus.targ_port)]->port_type !=
9338 	    CTL_PORT_FC)
9339 		is_fc = 0;
9340 	else
9341 		is_fc = 1;
9342 	mtx_unlock(&ctl_softc->ctl_lock);
9343 
9344 	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9345 	cdb = (struct scsi_inquiry *)ctsio->cdb;
9346 	alloc_len = scsi_2btoul(cdb->length);
9347 
9348 	/*
9349 	 * We malloc the full inquiry data size here and fill it
9350 	 * in.  If the user only asks for less, we'll give him
9351 	 * that much.
9352 	 */
9353 	ctsio->kern_data_ptr = malloc(sizeof(*inq_ptr), M_CTL, M_WAITOK | M_ZERO);
9354 	inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
9355 	ctsio->kern_sg_entries = 0;
9356 	ctsio->kern_data_resid = 0;
9357 	ctsio->kern_rel_offset = 0;
9358 
9359 	if (sizeof(*inq_ptr) < alloc_len) {
9360 		ctsio->residual = alloc_len - sizeof(*inq_ptr);
9361 		ctsio->kern_data_len = sizeof(*inq_ptr);
9362 		ctsio->kern_total_len = sizeof(*inq_ptr);
9363 	} else {
9364 		ctsio->residual = 0;
9365 		ctsio->kern_data_len = alloc_len;
9366 		ctsio->kern_total_len = alloc_len;
9367 	}
9368 
9369 	/*
9370 	 * If we have a LUN configured, report it as connected.  Otherwise,
9371 	 * report that it is offline or no device is supported, depending
9372 	 * on the value of inquiry_pq_no_lun.
9373 	 *
9374 	 * According to the spec (SPC-4 r34), the peripheral qualifier
9375 	 * SID_QUAL_LU_OFFLINE (001b) is used in the following scenario:
9376 	 *
9377 	 * "A peripheral device having the specified peripheral device type
9378 	 * is not connected to this logical unit. However, the device
9379 	 * server is capable of supporting the specified peripheral device
9380 	 * type on this logical unit."
9381 	 *
9382 	 * According to the same spec, the peripheral qualifier
9383 	 * SID_QUAL_BAD_LU (011b) is used in this scenario:
9384 	 *
9385 	 * "The device server is not capable of supporting a peripheral
9386 	 * device on this logical unit. For this peripheral qualifier the
9387 	 * peripheral device type shall be set to 1Fh. All other peripheral
9388 	 * device type values are reserved for this peripheral qualifier."
9389 	 *
9390 	 * Given the text, it would seem that we probably want to report that
9391 	 * the LUN is offline here.  There is no LUN connected, but we can
9392 	 * support a LUN at the given LUN number.
9393 	 *
9394 	 * In the real world, though, it sounds like things are a little
9395 	 * different:
9396 	 *
9397 	 * - Linux, when presented with a LUN with the offline peripheral
9398 	 *   qualifier, will create an sg driver instance for it.  So when
9399 	 *   you attach it to CTL, you wind up with a ton of sg driver
9400 	 *   instances.  (One for every LUN that Linux bothered to probe.)
9401 	 *   Linux does this despite the fact that it issues a REPORT LUNs
9402 	 *   to LUN 0 to get the inventory of supported LUNs.
9403 	 *
9404 	 * - There is other anecdotal evidence (from Emulex folks) about
9405 	 *   arrays that use the offline peripheral qualifier for LUNs that
9406 	 *   are on the "passive" path in an active/passive array.
9407 	 *
9408 	 * So the solution is provide a hopefully reasonable default
9409 	 * (return bad/no LUN) and allow the user to change the behavior
9410 	 * with a tunable/sysctl variable.
9411 	 */
9412 	if (lun != NULL)
9413 		inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9414 				  lun->be_lun->lun_type;
9415 	else if (ctl_softc->inquiry_pq_no_lun == 0)
9416 		inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9417 	else
9418 		inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
9419 
9420 	/* RMB in byte 2 is 0 */
9421 	inq_ptr->version = SCSI_REV_SPC3;
9422 
9423 	/*
9424 	 * According to SAM-3, even if a device only supports a single
9425 	 * level of LUN addressing, it should still set the HISUP bit:
9426 	 *
9427 	 * 4.9.1 Logical unit numbers overview
9428 	 *
9429 	 * All logical unit number formats described in this standard are
9430 	 * hierarchical in structure even when only a single level in that
9431 	 * hierarchy is used. The HISUP bit shall be set to one in the
9432 	 * standard INQUIRY data (see SPC-2) when any logical unit number
9433 	 * format described in this standard is used.  Non-hierarchical
9434 	 * formats are outside the scope of this standard.
9435 	 *
9436 	 * Therefore we set the HiSup bit here.
9437 	 *
9438 	 * The reponse format is 2, per SPC-3.
9439 	 */
9440 	inq_ptr->response_format = SID_HiSup | 2;
9441 
9442 	inq_ptr->additional_length = sizeof(*inq_ptr) - 4;
9443 	CTL_DEBUG_PRINT(("additional_length = %d\n",
9444 			 inq_ptr->additional_length));
9445 
9446 	inq_ptr->spc3_flags = SPC3_SID_TPGS_IMPLICIT;
9447 	/* 16 bit addressing */
9448 	if (is_fc == 0)
9449 		inq_ptr->spc2_flags = SPC2_SID_ADDR16;
9450 	/* XXX set the SID_MultiP bit here if we're actually going to
9451 	   respond on multiple ports */
9452 	inq_ptr->spc2_flags |= SPC2_SID_MultiP;
9453 
9454 	/* 16 bit data bus, synchronous transfers */
9455 	/* XXX these flags don't apply for FC */
9456 	if (is_fc == 0)
9457 		inq_ptr->flags = SID_WBus16 | SID_Sync;
9458 	/*
9459 	 * XXX KDM do we want to support tagged queueing on the control
9460 	 * device at all?
9461 	 */
9462 	if ((lun == NULL)
9463 	 || (lun->be_lun->lun_type != T_PROCESSOR))
9464 		inq_ptr->flags |= SID_CmdQue;
9465 	/*
9466 	 * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
9467 	 * We have 8 bytes for the vendor name, and 16 bytes for the device
9468 	 * name and 4 bytes for the revision.
9469 	 */
9470 	strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
9471 	if (lun == NULL) {
9472 		strcpy(inq_ptr->product, CTL_DIRECT_PRODUCT);
9473 	} else {
9474 		switch (lun->be_lun->lun_type) {
9475 		case T_DIRECT:
9476 			strcpy(inq_ptr->product, CTL_DIRECT_PRODUCT);
9477 			break;
9478 		case T_PROCESSOR:
9479 			strcpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT);
9480 			break;
9481 		default:
9482 			strcpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT);
9483 			break;
9484 		}
9485 	}
9486 
9487 	/*
9488 	 * XXX make this a macro somewhere so it automatically gets
9489 	 * incremented when we make changes.
9490 	 */
9491 	strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
9492 
9493 	/*
9494 	 * For parallel SCSI, we support double transition and single
9495 	 * transition clocking.  We also support QAS (Quick Arbitration
9496 	 * and Selection) and Information Unit transfers on both the
9497 	 * control and array devices.
9498 	 */
9499 	if (is_fc == 0)
9500 		inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
9501 				    SID_SPI_IUS;
9502 
9503 	/* SAM-3 */
9504 	scsi_ulto2b(0x0060, inq_ptr->version1);
9505 	/* SPC-3 (no version claimed) XXX should we claim a version? */
9506 	scsi_ulto2b(0x0300, inq_ptr->version2);
9507 	if (is_fc) {
9508 		/* FCP-2 ANSI INCITS.350:2003 */
9509 		scsi_ulto2b(0x0917, inq_ptr->version3);
9510 	} else {
9511 		/* SPI-4 ANSI INCITS.362:200x */
9512 		scsi_ulto2b(0x0B56, inq_ptr->version3);
9513 	}
9514 
9515 	if (lun == NULL) {
9516 		/* SBC-2 (no version claimed) XXX should we claim a version? */
9517 		scsi_ulto2b(0x0320, inq_ptr->version4);
9518 	} else {
9519 		switch (lun->be_lun->lun_type) {
9520 		case T_DIRECT:
9521 			/*
9522 			 * SBC-2 (no version claimed) XXX should we claim a
9523 			 * version?
9524 			 */
9525 			scsi_ulto2b(0x0320, inq_ptr->version4);
9526 			break;
9527 		case T_PROCESSOR:
9528 		default:
9529 			break;
9530 		}
9531 	}
9532 
9533 	ctsio->scsi_status = SCSI_STATUS_OK;
9534 	if (ctsio->kern_data_len > 0) {
9535 		ctsio->be_move_done = ctl_config_move_done;
9536 		ctl_datamove((union ctl_io *)ctsio);
9537 	} else {
9538 		ctsio->io_hdr.status = CTL_SUCCESS;
9539 		ctl_done((union ctl_io *)ctsio);
9540 	}
9541 
9542 	return (CTL_RETVAL_COMPLETE);
9543 }
9544 
9545 int
9546 ctl_inquiry(struct ctl_scsiio *ctsio)
9547 {
9548 	struct scsi_inquiry *cdb;
9549 	int retval;
9550 
9551 	cdb = (struct scsi_inquiry *)ctsio->cdb;
9552 
9553 	retval = 0;
9554 
9555 	CTL_DEBUG_PRINT(("ctl_inquiry\n"));
9556 
9557 	/*
9558 	 * Right now, we don't support the CmdDt inquiry information.
9559 	 * This would be nice to support in the future.  When we do
9560 	 * support it, we should change this test so that it checks to make
9561 	 * sure SI_EVPD and SI_CMDDT aren't both set at the same time.
9562 	 */
9563 #ifdef notyet
9564 	if (((cdb->byte2 & SI_EVPD)
9565 	 && (cdb->byte2 & SI_CMDDT)))
9566 #endif
9567 	if (cdb->byte2 & SI_CMDDT) {
9568 		/*
9569 		 * Point to the SI_CMDDT bit.  We might change this
9570 		 * when we support SI_CMDDT, but since both bits would be
9571 		 * "wrong", this should probably just stay as-is then.
9572 		 */
9573 		ctl_set_invalid_field(ctsio,
9574 				      /*sks_valid*/ 1,
9575 				      /*command*/ 1,
9576 				      /*field*/ 1,
9577 				      /*bit_valid*/ 1,
9578 				      /*bit*/ 1);
9579 		ctl_done((union ctl_io *)ctsio);
9580 		return (CTL_RETVAL_COMPLETE);
9581 	}
9582 	if (cdb->byte2 & SI_EVPD)
9583 		retval = ctl_inquiry_evpd(ctsio);
9584 #ifdef notyet
9585 	else if (cdb->byte2 & SI_CMDDT)
9586 		retval = ctl_inquiry_cmddt(ctsio);
9587 #endif
9588 	else
9589 		retval = ctl_inquiry_std(ctsio);
9590 
9591 	return (retval);
9592 }
9593 
9594 /*
9595  * For known CDB types, parse the LBA and length.
9596  */
9597 static int
9598 ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint32_t *len)
9599 {
9600 	if (io->io_hdr.io_type != CTL_IO_SCSI)
9601 		return (1);
9602 
9603 	switch (io->scsiio.cdb[0]) {
9604 	case READ_6:
9605 	case WRITE_6: {
9606 		struct scsi_rw_6 *cdb;
9607 
9608 		cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
9609 
9610 		*lba = scsi_3btoul(cdb->addr);
9611 		/* only 5 bits are valid in the most significant address byte */
9612 		*lba &= 0x1fffff;
9613 		*len = cdb->length;
9614 		break;
9615 	}
9616 	case READ_10:
9617 	case WRITE_10: {
9618 		struct scsi_rw_10 *cdb;
9619 
9620 		cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
9621 
9622 		*lba = scsi_4btoul(cdb->addr);
9623 		*len = scsi_2btoul(cdb->length);
9624 		break;
9625 	}
9626 	case WRITE_VERIFY_10: {
9627 		struct scsi_write_verify_10 *cdb;
9628 
9629 		cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
9630 
9631 		*lba = scsi_4btoul(cdb->addr);
9632 		*len = scsi_2btoul(cdb->length);
9633 		break;
9634 	}
9635 	case READ_12:
9636 	case WRITE_12: {
9637 		struct scsi_rw_12 *cdb;
9638 
9639 		cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
9640 
9641 		*lba = scsi_4btoul(cdb->addr);
9642 		*len = scsi_4btoul(cdb->length);
9643 		break;
9644 	}
9645 	case WRITE_VERIFY_12: {
9646 		struct scsi_write_verify_12 *cdb;
9647 
9648 		cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
9649 
9650 		*lba = scsi_4btoul(cdb->addr);
9651 		*len = scsi_4btoul(cdb->length);
9652 		break;
9653 	}
9654 	case READ_16:
9655 	case WRITE_16: {
9656 		struct scsi_rw_16 *cdb;
9657 
9658 		cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
9659 
9660 		*lba = scsi_8btou64(cdb->addr);
9661 		*len = scsi_4btoul(cdb->length);
9662 		break;
9663 	}
9664 	case WRITE_VERIFY_16: {
9665 		struct scsi_write_verify_16 *cdb;
9666 
9667 		cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
9668 
9669 
9670 		*lba = scsi_8btou64(cdb->addr);
9671 		*len = scsi_4btoul(cdb->length);
9672 		break;
9673 	}
9674 	default:
9675 		return (1);
9676 		break; /* NOTREACHED */
9677 	}
9678 
9679 	return (0);
9680 }
9681 
9682 static ctl_action
9683 ctl_extent_check_lba(uint64_t lba1, uint32_t len1, uint64_t lba2, uint32_t len2)
9684 {
9685 	uint64_t endlba1, endlba2;
9686 
9687 	endlba1 = lba1 + len1 - 1;
9688 	endlba2 = lba2 + len2 - 1;
9689 
9690 	if ((endlba1 < lba2)
9691 	 || (endlba2 < lba1))
9692 		return (CTL_ACTION_PASS);
9693 	else
9694 		return (CTL_ACTION_BLOCK);
9695 }
9696 
9697 static ctl_action
9698 ctl_extent_check(union ctl_io *io1, union ctl_io *io2)
9699 {
9700 	uint64_t lba1, lba2;
9701 	uint32_t len1, len2;
9702 	int retval;
9703 
9704 	retval = ctl_get_lba_len(io1, &lba1, &len1);
9705 	if (retval != 0)
9706 		return (CTL_ACTION_ERROR);
9707 
9708 	retval = ctl_get_lba_len(io2, &lba2, &len2);
9709 	if (retval != 0)
9710 		return (CTL_ACTION_ERROR);
9711 
9712 	return (ctl_extent_check_lba(lba1, len1, lba2, len2));
9713 }
9714 
9715 static ctl_action
9716 ctl_check_for_blockage(union ctl_io *pending_io, union ctl_io *ooa_io)
9717 {
9718 	struct ctl_cmd_entry *pending_entry, *ooa_entry;
9719 	ctl_serialize_action *serialize_row;
9720 
9721 	/*
9722 	 * The initiator attempted multiple untagged commands at the same
9723 	 * time.  Can't do that.
9724 	 */
9725 	if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
9726 	 && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
9727 	 && ((pending_io->io_hdr.nexus.targ_port ==
9728 	      ooa_io->io_hdr.nexus.targ_port)
9729 	  && (pending_io->io_hdr.nexus.initid.id ==
9730 	      ooa_io->io_hdr.nexus.initid.id))
9731 	 && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
9732 		return (CTL_ACTION_OVERLAP);
9733 
9734 	/*
9735 	 * The initiator attempted to send multiple tagged commands with
9736 	 * the same ID.  (It's fine if different initiators have the same
9737 	 * tag ID.)
9738 	 *
9739 	 * Even if all of those conditions are true, we don't kill the I/O
9740 	 * if the command ahead of us has been aborted.  We won't end up
9741 	 * sending it to the FETD, and it's perfectly legal to resend a
9742 	 * command with the same tag number as long as the previous
9743 	 * instance of this tag number has been aborted somehow.
9744 	 */
9745 	if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
9746 	 && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
9747 	 && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
9748 	 && ((pending_io->io_hdr.nexus.targ_port ==
9749 	      ooa_io->io_hdr.nexus.targ_port)
9750 	  && (pending_io->io_hdr.nexus.initid.id ==
9751 	      ooa_io->io_hdr.nexus.initid.id))
9752 	 && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
9753 		return (CTL_ACTION_OVERLAP_TAG);
9754 
9755 	/*
9756 	 * If we get a head of queue tag, SAM-3 says that we should
9757 	 * immediately execute it.
9758 	 *
9759 	 * What happens if this command would normally block for some other
9760 	 * reason?  e.g. a request sense with a head of queue tag
9761 	 * immediately after a write.  Normally that would block, but this
9762 	 * will result in its getting executed immediately...
9763 	 *
9764 	 * We currently return "pass" instead of "skip", so we'll end up
9765 	 * going through the rest of the queue to check for overlapped tags.
9766 	 *
9767 	 * XXX KDM check for other types of blockage first??
9768 	 */
9769 	if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
9770 		return (CTL_ACTION_PASS);
9771 
9772 	/*
9773 	 * Ordered tags have to block until all items ahead of them
9774 	 * have completed.  If we get called with an ordered tag, we always
9775 	 * block, if something else is ahead of us in the queue.
9776 	 */
9777 	if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
9778 		return (CTL_ACTION_BLOCK);
9779 
9780 	/*
9781 	 * Simple tags get blocked until all head of queue and ordered tags
9782 	 * ahead of them have completed.  I'm lumping untagged commands in
9783 	 * with simple tags here.  XXX KDM is that the right thing to do?
9784 	 */
9785 	if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
9786 	  || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
9787 	 && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
9788 	  || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
9789 		return (CTL_ACTION_BLOCK);
9790 
9791 	pending_entry = &ctl_cmd_table[pending_io->scsiio.cdb[0]];
9792 	ooa_entry = &ctl_cmd_table[ooa_io->scsiio.cdb[0]];
9793 
9794 	serialize_row = ctl_serialize_table[ooa_entry->seridx];
9795 
9796 	switch (serialize_row[pending_entry->seridx]) {
9797 	case CTL_SER_BLOCK:
9798 		return (CTL_ACTION_BLOCK);
9799 		break; /* NOTREACHED */
9800 	case CTL_SER_EXTENT:
9801 		return (ctl_extent_check(pending_io, ooa_io));
9802 		break; /* NOTREACHED */
9803 	case CTL_SER_PASS:
9804 		return (CTL_ACTION_PASS);
9805 		break; /* NOTREACHED */
9806 	case CTL_SER_SKIP:
9807 		return (CTL_ACTION_SKIP);
9808 		break;
9809 	default:
9810 		panic("invalid serialization value %d",
9811 		      serialize_row[pending_entry->seridx]);
9812 		break; /* NOTREACHED */
9813 	}
9814 
9815 	return (CTL_ACTION_ERROR);
9816 }
9817 
9818 /*
9819  * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
9820  * Assumptions:
9821  * - pending_io is generally either incoming, or on the blocked queue
9822  * - starting I/O is the I/O we want to start the check with.
9823  */
9824 static ctl_action
9825 ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
9826 	      union ctl_io *starting_io)
9827 {
9828 	union ctl_io *ooa_io;
9829 	ctl_action action;
9830 
9831 	mtx_assert(&control_softc->ctl_lock, MA_OWNED);
9832 
9833 	/*
9834 	 * Run back along the OOA queue, starting with the current
9835 	 * blocked I/O and going through every I/O before it on the
9836 	 * queue.  If starting_io is NULL, we'll just end up returning
9837 	 * CTL_ACTION_PASS.
9838 	 */
9839 	for (ooa_io = starting_io; ooa_io != NULL;
9840 	     ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
9841 	     ooa_links)){
9842 
9843 		/*
9844 		 * This routine just checks to see whether
9845 		 * cur_blocked is blocked by ooa_io, which is ahead
9846 		 * of it in the queue.  It doesn't queue/dequeue
9847 		 * cur_blocked.
9848 		 */
9849 		action = ctl_check_for_blockage(pending_io, ooa_io);
9850 		switch (action) {
9851 		case CTL_ACTION_BLOCK:
9852 		case CTL_ACTION_OVERLAP:
9853 		case CTL_ACTION_OVERLAP_TAG:
9854 		case CTL_ACTION_SKIP:
9855 		case CTL_ACTION_ERROR:
9856 			return (action);
9857 			break; /* NOTREACHED */
9858 		case CTL_ACTION_PASS:
9859 			break;
9860 		default:
9861 			panic("invalid action %d", action);
9862 			break;  /* NOTREACHED */
9863 		}
9864 	}
9865 
9866 	return (CTL_ACTION_PASS);
9867 }
9868 
9869 /*
9870  * Assumptions:
9871  * - An I/O has just completed, and has been removed from the per-LUN OOA
9872  *   queue, so some items on the blocked queue may now be unblocked.
9873  */
9874 static int
9875 ctl_check_blocked(struct ctl_lun *lun)
9876 {
9877 	union ctl_io *cur_blocked, *next_blocked;
9878 
9879 	mtx_assert(&control_softc->ctl_lock, MA_OWNED);
9880 
9881 	/*
9882 	 * Run forward from the head of the blocked queue, checking each
9883 	 * entry against the I/Os prior to it on the OOA queue to see if
9884 	 * there is still any blockage.
9885 	 *
9886 	 * We cannot use the TAILQ_FOREACH() macro, because it can't deal
9887 	 * with our removing a variable on it while it is traversing the
9888 	 * list.
9889 	 */
9890 	for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
9891 	     cur_blocked != NULL; cur_blocked = next_blocked) {
9892 		union ctl_io *prev_ooa;
9893 		ctl_action action;
9894 
9895 		next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
9896 							  blocked_links);
9897 
9898 		prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
9899 						      ctl_ooaq, ooa_links);
9900 
9901 		/*
9902 		 * If cur_blocked happens to be the first item in the OOA
9903 		 * queue now, prev_ooa will be NULL, and the action
9904 		 * returned will just be CTL_ACTION_PASS.
9905 		 */
9906 		action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
9907 
9908 		switch (action) {
9909 		case CTL_ACTION_BLOCK:
9910 			/* Nothing to do here, still blocked */
9911 			break;
9912 		case CTL_ACTION_OVERLAP:
9913 		case CTL_ACTION_OVERLAP_TAG:
9914 			/*
9915 			 * This shouldn't happen!  In theory we've already
9916 			 * checked this command for overlap...
9917 			 */
9918 			break;
9919 		case CTL_ACTION_PASS:
9920 		case CTL_ACTION_SKIP: {
9921 			struct ctl_softc *softc;
9922 			struct ctl_cmd_entry *entry;
9923 			uint32_t initidx;
9924 			uint8_t opcode;
9925 			int isc_retval;
9926 
9927 			/*
9928 			 * The skip case shouldn't happen, this transaction
9929 			 * should have never made it onto the blocked queue.
9930 			 */
9931 			/*
9932 			 * This I/O is no longer blocked, we can remove it
9933 			 * from the blocked queue.  Since this is a TAILQ
9934 			 * (doubly linked list), we can do O(1) removals
9935 			 * from any place on the list.
9936 			 */
9937 			TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
9938 				     blocked_links);
9939 			cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
9940 
9941 			if (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC){
9942 				/*
9943 				 * Need to send IO back to original side to
9944 				 * run
9945 				 */
9946 				union ctl_ha_msg msg_info;
9947 
9948 				msg_info.hdr.original_sc =
9949 					cur_blocked->io_hdr.original_sc;
9950 				msg_info.hdr.serializing_sc = cur_blocked;
9951 				msg_info.hdr.msg_type = CTL_MSG_R2R;
9952 				if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
9953 				     &msg_info, sizeof(msg_info), 0)) >
9954 				     CTL_HA_STATUS_SUCCESS) {
9955 					printf("CTL:Check Blocked error from "
9956 					       "ctl_ha_msg_send %d\n",
9957 					       isc_retval);
9958 				}
9959 				break;
9960 			}
9961 			opcode = cur_blocked->scsiio.cdb[0];
9962 			entry = &ctl_cmd_table[opcode];
9963 			softc = control_softc;
9964 
9965 			initidx = ctl_get_initindex(&cur_blocked->io_hdr.nexus);
9966 
9967 			/*
9968 			 * Check this I/O for LUN state changes that may
9969 			 * have happened while this command was blocked.
9970 			 * The LUN state may have been changed by a command
9971 			 * ahead of us in the queue, so we need to re-check
9972 			 * for any states that can be caused by SCSI
9973 			 * commands.
9974 			 */
9975 			if (ctl_scsiio_lun_check(softc, lun, entry,
9976 						 &cur_blocked->scsiio) == 0) {
9977 				cur_blocked->io_hdr.flags |=
9978 				                      CTL_FLAG_IS_WAS_ON_RTR;
9979 				STAILQ_INSERT_TAIL(&lun->ctl_softc->rtr_queue,
9980 						   &cur_blocked->io_hdr, links);
9981 				/*
9982 				 * In the non CTL_DONE_THREAD case, we need
9983 				 * to wake up the work thread here.  When
9984 				 * we're processing completed requests from
9985 				 * the work thread context, we'll pop back
9986 				 * around and end up pulling things off the
9987 				 * RtR queue.  When we aren't processing
9988 				 * things from the work thread context,
9989 				 * though, we won't ever check the RtR queue.
9990 				 * So we need to wake up the thread to clear
9991 				 * things off the queue.  Otherwise this
9992 				 * transaction will just sit on the RtR queue
9993 				 * until a new I/O comes in.  (Which may or
9994 				 * may not happen...)
9995 				 */
9996 #ifndef CTL_DONE_THREAD
9997 				ctl_wakeup_thread();
9998 #endif
9999 			} else
10000 				ctl_done_lock(cur_blocked, /*have_lock*/ 1);
10001 			break;
10002 		}
10003 		default:
10004 			/*
10005 			 * This probably shouldn't happen -- we shouldn't
10006 			 * get CTL_ACTION_ERROR, or anything else.
10007 			 */
10008 			break;
10009 		}
10010 	}
10011 
10012 	return (CTL_RETVAL_COMPLETE);
10013 }
10014 
10015 /*
10016  * This routine (with one exception) checks LUN flags that can be set by
10017  * commands ahead of us in the OOA queue.  These flags have to be checked
10018  * when a command initially comes in, and when we pull a command off the
10019  * blocked queue and are preparing to execute it.  The reason we have to
10020  * check these flags for commands on the blocked queue is that the LUN
10021  * state may have been changed by a command ahead of us while we're on the
10022  * blocked queue.
10023  *
10024  * Ordering is somewhat important with these checks, so please pay
10025  * careful attention to the placement of any new checks.
10026  */
10027 static int
10028 ctl_scsiio_lun_check(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
10029 		     struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
10030 {
10031 	int retval;
10032 
10033 	retval = 0;
10034 
10035 	/*
10036 	 * If this shelf is a secondary shelf controller, we have to reject
10037 	 * any media access commands.
10038 	 */
10039 #if 0
10040 	/* No longer needed for HA */
10041 	if (((ctl_softc->flags & CTL_FLAG_MASTER_SHELF) == 0)
10042 	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_SECONDARY) == 0)) {
10043 		ctl_set_lun_standby(ctsio);
10044 		retval = 1;
10045 		goto bailout;
10046 	}
10047 #endif
10048 
10049 	/*
10050 	 * Check for a reservation conflict.  If this command isn't allowed
10051 	 * even on reserved LUNs, and if this initiator isn't the one who
10052 	 * reserved us, reject the command with a reservation conflict.
10053 	 */
10054 	if ((lun->flags & CTL_LUN_RESERVED)
10055 	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
10056 		if ((ctsio->io_hdr.nexus.initid.id != lun->rsv_nexus.initid.id)
10057 		 || (ctsio->io_hdr.nexus.targ_port != lun->rsv_nexus.targ_port)
10058 		 || (ctsio->io_hdr.nexus.targ_target.id !=
10059 		     lun->rsv_nexus.targ_target.id)) {
10060 			ctsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
10061 			ctsio->io_hdr.status = CTL_SCSI_ERROR;
10062 			retval = 1;
10063 			goto bailout;
10064 		}
10065 	}
10066 
10067 	if ( (lun->flags & CTL_LUN_PR_RESERVED)
10068 	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV) == 0)) {
10069 		uint32_t residx;
10070 
10071 		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
10072 		/*
10073 		 * if we aren't registered or it's a res holder type
10074 		 * reservation and this isn't the res holder then set a
10075 		 * conflict.
10076 		 * NOTE: Commands which might be allowed on write exclusive
10077 		 * type reservations are checked in the particular command
10078 		 * for a conflict. Read and SSU are the only ones.
10079 		 */
10080 		if (!lun->per_res[residx].registered
10081 		 || (residx != lun->pr_res_idx && lun->res_type < 4)) {
10082 			ctsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
10083 			ctsio->io_hdr.status = CTL_SCSI_ERROR;
10084 			retval = 1;
10085 			goto bailout;
10086 		}
10087 
10088 	}
10089 
10090 	if ((lun->flags & CTL_LUN_OFFLINE)
10091 	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_OFFLINE) == 0)) {
10092 		ctl_set_lun_not_ready(ctsio);
10093 		retval = 1;
10094 		goto bailout;
10095 	}
10096 
10097 	/*
10098 	 * If the LUN is stopped, see if this particular command is allowed
10099 	 * for a stopped lun.  Otherwise, reject it with 0x04,0x02.
10100 	 */
10101 	if ((lun->flags & CTL_LUN_STOPPED)
10102 	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_STOPPED) == 0)) {
10103 		/* "Logical unit not ready, initializing cmd. required" */
10104 		ctl_set_lun_stopped(ctsio);
10105 		retval = 1;
10106 		goto bailout;
10107 	}
10108 
10109 	if ((lun->flags & CTL_LUN_INOPERABLE)
10110 	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_INOPERABLE) == 0)) {
10111 		/* "Medium format corrupted" */
10112 		ctl_set_medium_format_corrupted(ctsio);
10113 		retval = 1;
10114 		goto bailout;
10115 	}
10116 
10117 bailout:
10118 	return (retval);
10119 
10120 }
10121 
10122 static void
10123 ctl_failover_io(union ctl_io *io, int have_lock)
10124 {
10125 	ctl_set_busy(&io->scsiio);
10126 	ctl_done_lock(io, have_lock);
10127 }
10128 
10129 static void
10130 ctl_failover(void)
10131 {
10132 	struct ctl_lun *lun;
10133 	struct ctl_softc *ctl_softc;
10134 	union ctl_io *next_io, *pending_io;
10135 	union ctl_io *io;
10136 	int lun_idx;
10137 	int i;
10138 
10139 	ctl_softc = control_softc;
10140 
10141 	mtx_lock(&ctl_softc->ctl_lock);
10142 	/*
10143 	 * Remove any cmds from the other SC from the rtr queue.  These
10144 	 * will obviously only be for LUNs for which we're the primary.
10145 	 * We can't send status or get/send data for these commands.
10146 	 * Since they haven't been executed yet, we can just remove them.
10147 	 * We'll either abort them or delete them below, depending on
10148 	 * which HA mode we're in.
10149 	 */
10150 	for (io = (union ctl_io *)STAILQ_FIRST(&ctl_softc->rtr_queue);
10151 	     io != NULL; io = next_io) {
10152 		next_io = (union ctl_io *)STAILQ_NEXT(&io->io_hdr, links);
10153 		if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
10154 			STAILQ_REMOVE(&ctl_softc->rtr_queue, &io->io_hdr,
10155 				      ctl_io_hdr, links);
10156 	}
10157 
10158 	for (lun_idx=0; lun_idx < ctl_softc->num_luns; lun_idx++) {
10159 		lun = ctl_softc->ctl_luns[lun_idx];
10160 		if (lun==NULL)
10161 			continue;
10162 
10163 		/*
10164 		 * Processor LUNs are primary on both sides.
10165 		 * XXX will this always be true?
10166 		 */
10167 		if (lun->be_lun->lun_type == T_PROCESSOR)
10168 			continue;
10169 
10170 		if ((lun->flags & CTL_LUN_PRIMARY_SC)
10171 		 && (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
10172 			printf("FAILOVER: primary lun %d\n", lun_idx);
10173 		        /*
10174 			 * Remove all commands from the other SC. First from the
10175 			 * blocked queue then from the ooa queue. Once we have
10176 			 * removed them. Call ctl_check_blocked to see if there
10177 			 * is anything that can run.
10178 			 */
10179 			for (io = (union ctl_io *)TAILQ_FIRST(
10180 			     &lun->blocked_queue); io != NULL; io = next_io) {
10181 
10182 		        	next_io = (union ctl_io *)TAILQ_NEXT(
10183 				    &io->io_hdr, blocked_links);
10184 
10185 				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
10186 					TAILQ_REMOVE(&lun->blocked_queue,
10187 						     &io->io_hdr,blocked_links);
10188 					io->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
10189 					TAILQ_REMOVE(&lun->ooa_queue,
10190 						     &io->io_hdr, ooa_links);
10191 
10192 					ctl_free_io_internal(io, 1);
10193 				}
10194 			}
10195 
10196 			for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
10197 	     		     io != NULL; io = next_io) {
10198 
10199 		        	next_io = (union ctl_io *)TAILQ_NEXT(
10200 				    &io->io_hdr, ooa_links);
10201 
10202 				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
10203 
10204 					TAILQ_REMOVE(&lun->ooa_queue,
10205 						&io->io_hdr,
10206 					     	ooa_links);
10207 
10208 					ctl_free_io_internal(io, 1);
10209 				}
10210 			}
10211 			ctl_check_blocked(lun);
10212 		} else if ((lun->flags & CTL_LUN_PRIMARY_SC)
10213 			&& (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
10214 
10215 			printf("FAILOVER: primary lun %d\n", lun_idx);
10216 			/*
10217 			 * Abort all commands from the other SC.  We can't
10218 			 * send status back for them now.  These should get
10219 			 * cleaned up when they are completed or come out
10220 			 * for a datamove operation.
10221 			 */
10222 			for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
10223 	     		     io != NULL; io = next_io) {
10224 		        	next_io = (union ctl_io *)TAILQ_NEXT(
10225 					&io->io_hdr, ooa_links);
10226 
10227 				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
10228 					io->io_hdr.flags |= CTL_FLAG_ABORT;
10229 			}
10230 		} else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
10231 			&& (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
10232 
10233 			printf("FAILOVER: secondary lun %d\n", lun_idx);
10234 
10235 			lun->flags |= CTL_LUN_PRIMARY_SC;
10236 
10237 			/*
10238 			 * We send all I/O that was sent to this controller
10239 			 * and redirected to the other side back with
10240 			 * busy status, and have the initiator retry it.
10241 			 * Figuring out how much data has been transferred,
10242 			 * etc. and picking up where we left off would be
10243 			 * very tricky.
10244 			 *
10245 			 * XXX KDM need to remove I/O from the blocked
10246 			 * queue as well!
10247 			 */
10248 			for (pending_io = (union ctl_io *)TAILQ_FIRST(
10249 			     &lun->ooa_queue); pending_io != NULL;
10250 			     pending_io = next_io) {
10251 
10252 				next_io =  (union ctl_io *)TAILQ_NEXT(
10253 					&pending_io->io_hdr, ooa_links);
10254 
10255 				pending_io->io_hdr.flags &=
10256 					~CTL_FLAG_SENT_2OTHER_SC;
10257 
10258 				if (pending_io->io_hdr.flags &
10259 				    CTL_FLAG_IO_ACTIVE) {
10260 					pending_io->io_hdr.flags |=
10261 						CTL_FLAG_FAILOVER;
10262 				} else {
10263 					ctl_set_busy(&pending_io->scsiio);
10264 					ctl_done_lock(pending_io,
10265 						      /*have_lock*/1);
10266 				}
10267 			}
10268 
10269 			/*
10270 			 * Build Unit Attention
10271 			 */
10272 			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
10273 				lun->pending_sense[i].ua_pending |=
10274 				                     CTL_UA_ASYM_ACC_CHANGE;
10275 			}
10276 		} else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
10277 			&& (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
10278 			printf("FAILOVER: secondary lun %d\n", lun_idx);
10279 			/*
10280 			 * if the first io on the OOA is not on the RtR queue
10281 			 * add it.
10282 			 */
10283 			lun->flags |= CTL_LUN_PRIMARY_SC;
10284 
10285 			pending_io = (union ctl_io *)TAILQ_FIRST(
10286 			    &lun->ooa_queue);
10287 			if (pending_io==NULL) {
10288 				printf("Nothing on OOA queue\n");
10289 				continue;
10290 			}
10291 
10292 			pending_io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
10293 			if ((pending_io->io_hdr.flags &
10294 			     CTL_FLAG_IS_WAS_ON_RTR) == 0) {
10295 				pending_io->io_hdr.flags |=
10296 				    CTL_FLAG_IS_WAS_ON_RTR;
10297 				STAILQ_INSERT_TAIL(&ctl_softc->rtr_queue,
10298 						   &pending_io->io_hdr, links);
10299 			}
10300 #if 0
10301 			else
10302 			{
10303 				printf("Tag 0x%04x is running\n",
10304 				      pending_io->scsiio.tag_num);
10305 			}
10306 #endif
10307 
10308 			next_io = (union ctl_io *)TAILQ_NEXT(
10309 			    &pending_io->io_hdr, ooa_links);
10310 			for (pending_io=next_io; pending_io != NULL;
10311 			     pending_io = next_io) {
10312 				pending_io->io_hdr.flags &=
10313 				    ~CTL_FLAG_SENT_2OTHER_SC;
10314 				next_io = (union ctl_io *)TAILQ_NEXT(
10315 					&pending_io->io_hdr, ooa_links);
10316 				if (pending_io->io_hdr.flags &
10317 				    CTL_FLAG_IS_WAS_ON_RTR) {
10318 #if 0
10319 				        printf("Tag 0x%04x is running\n",
10320 				      		pending_io->scsiio.tag_num);
10321 #endif
10322 					continue;
10323 				}
10324 
10325 				switch (ctl_check_ooa(lun, pending_io,
10326 			            (union ctl_io *)TAILQ_PREV(
10327 				    &pending_io->io_hdr, ctl_ooaq,
10328 				    ooa_links))) {
10329 
10330 				case CTL_ACTION_BLOCK:
10331 					TAILQ_INSERT_TAIL(&lun->blocked_queue,
10332 							  &pending_io->io_hdr,
10333 							  blocked_links);
10334 					pending_io->io_hdr.flags |=
10335 					    CTL_FLAG_BLOCKED;
10336 					break;
10337 				case CTL_ACTION_PASS:
10338 				case CTL_ACTION_SKIP:
10339 					pending_io->io_hdr.flags |=
10340 					    CTL_FLAG_IS_WAS_ON_RTR;
10341 					STAILQ_INSERT_TAIL(
10342 					    &ctl_softc->rtr_queue,
10343 					    &pending_io->io_hdr, links);
10344 					break;
10345 				case CTL_ACTION_OVERLAP:
10346 					ctl_set_overlapped_cmd(
10347 					    (struct ctl_scsiio *)pending_io);
10348 					ctl_done_lock(pending_io,
10349 						      /*have_lock*/ 1);
10350 					break;
10351 				case CTL_ACTION_OVERLAP_TAG:
10352 					ctl_set_overlapped_tag(
10353 					    (struct ctl_scsiio *)pending_io,
10354 					    pending_io->scsiio.tag_num & 0xff);
10355 					ctl_done_lock(pending_io,
10356 						      /*have_lock*/ 1);
10357 					break;
10358 				case CTL_ACTION_ERROR:
10359 				default:
10360 					ctl_set_internal_failure(
10361 						(struct ctl_scsiio *)pending_io,
10362 						0,  // sks_valid
10363 						0); //retry count
10364 					ctl_done_lock(pending_io,
10365 						      /*have_lock*/ 1);
10366 					break;
10367 				}
10368 			}
10369 
10370 			/*
10371 			 * Build Unit Attention
10372 			 */
10373 			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
10374 				lun->pending_sense[i].ua_pending |=
10375 				                     CTL_UA_ASYM_ACC_CHANGE;
10376 			}
10377 		} else {
10378 			panic("Unhandled HA mode failover, LUN flags = %#x, "
10379 			      "ha_mode = #%x", lun->flags, ctl_softc->ha_mode);
10380 		}
10381 	}
10382 	ctl_pause_rtr = 0;
10383 	mtx_unlock(&ctl_softc->ctl_lock);
10384 }
10385 
10386 static int
10387 ctl_scsiio_precheck(struct ctl_softc *ctl_softc, struct ctl_scsiio *ctsio)
10388 {
10389 	struct ctl_lun *lun;
10390 	struct ctl_cmd_entry *entry;
10391 	uint8_t opcode;
10392 	uint32_t initidx, targ_lun;
10393 	int retval;
10394 
10395 	retval = 0;
10396 
10397 	lun = NULL;
10398 
10399 	opcode = ctsio->cdb[0];
10400 
10401 	mtx_lock(&ctl_softc->ctl_lock);
10402 
10403 	targ_lun = ctsio->io_hdr.nexus.targ_lun;
10404 	if (ctsio->io_hdr.nexus.lun_map_fn != NULL)
10405 		targ_lun = ctsio->io_hdr.nexus.lun_map_fn(ctsio->io_hdr.nexus.lun_map_arg, targ_lun);
10406 	if ((targ_lun < CTL_MAX_LUNS)
10407 	 && (ctl_softc->ctl_luns[targ_lun] != NULL)) {
10408 		lun = ctl_softc->ctl_luns[targ_lun];
10409 		/*
10410 		 * If the LUN is invalid, pretend that it doesn't exist.
10411 		 * It will go away as soon as all pending I/O has been
10412 		 * completed.
10413 		 */
10414 		if (lun->flags & CTL_LUN_DISABLED) {
10415 			lun = NULL;
10416 		} else {
10417 			ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
10418 			ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr =
10419 				lun->be_lun;
10420 			if (lun->be_lun->lun_type == T_PROCESSOR) {
10421 				ctsio->io_hdr.flags |= CTL_FLAG_CONTROL_DEV;
10422 			}
10423 		}
10424 	} else {
10425 		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
10426 		ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
10427 	}
10428 
10429 	entry = &ctl_cmd_table[opcode];
10430 
10431 	ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
10432 	ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
10433 
10434 	/*
10435 	 * Check to see whether we can send this command to LUNs that don't
10436 	 * exist.  This should pretty much only be the case for inquiry
10437 	 * and request sense.  Further checks, below, really require having
10438 	 * a LUN, so we can't really check the command anymore.  Just put
10439 	 * it on the rtr queue.
10440 	 */
10441 	if (lun == NULL) {
10442 		if (entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS)
10443 			goto queue_rtr;
10444 
10445 		ctl_set_unsupported_lun(ctsio);
10446 		mtx_unlock(&ctl_softc->ctl_lock);
10447 		ctl_done((union ctl_io *)ctsio);
10448 		CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
10449 		goto bailout;
10450 	} else {
10451 		/*
10452 		 * Every I/O goes into the OOA queue for a particular LUN, and
10453 		 * stays there until completion.
10454 		 */
10455 		TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
10456 
10457 		/*
10458 		 * Make sure we support this particular command on this LUN.
10459 		 * e.g., we don't support writes to the control LUN.
10460 		 */
10461 		switch (lun->be_lun->lun_type) {
10462 		case T_PROCESSOR:
10463 		 	if (((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0)
10464 			 && ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS)
10465 			      == 0)) {
10466 				ctl_set_invalid_opcode(ctsio);
10467 				mtx_unlock(&ctl_softc->ctl_lock);
10468 				ctl_done((union ctl_io *)ctsio);
10469 				goto bailout;
10470 			}
10471 			break;
10472 		case T_DIRECT:
10473 			if (((entry->flags & CTL_CMD_FLAG_OK_ON_SLUN) == 0)
10474 			 && ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS)
10475 			      == 0)){
10476 				ctl_set_invalid_opcode(ctsio);
10477 				mtx_unlock(&ctl_softc->ctl_lock);
10478 				ctl_done((union ctl_io *)ctsio);
10479 				goto bailout;
10480 			}
10481 			break;
10482 		default:
10483 			printf("Unsupported CTL LUN type %d\n",
10484 			       lun->be_lun->lun_type);
10485 			panic("Unsupported CTL LUN type %d\n",
10486 			      lun->be_lun->lun_type);
10487 			break; /* NOTREACHED */
10488 		}
10489 	}
10490 
10491 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
10492 
10493 	/*
10494 	 * If we've got a request sense, it'll clear the contingent
10495 	 * allegiance condition.  Otherwise, if we have a CA condition for
10496 	 * this initiator, clear it, because it sent down a command other
10497 	 * than request sense.
10498 	 */
10499 	if ((opcode != REQUEST_SENSE)
10500 	 && (ctl_is_set(lun->have_ca, initidx)))
10501 		ctl_clear_mask(lun->have_ca, initidx);
10502 
10503 	/*
10504 	 * If the command has this flag set, it handles its own unit
10505 	 * attention reporting, we shouldn't do anything.  Otherwise we
10506 	 * check for any pending unit attentions, and send them back to the
10507 	 * initiator.  We only do this when a command initially comes in,
10508 	 * not when we pull it off the blocked queue.
10509 	 *
10510 	 * According to SAM-3, section 5.3.2, the order that things get
10511 	 * presented back to the host is basically unit attentions caused
10512 	 * by some sort of reset event, busy status, reservation conflicts
10513 	 * or task set full, and finally any other status.
10514 	 *
10515 	 * One issue here is that some of the unit attentions we report
10516 	 * don't fall into the "reset" category (e.g. "reported luns data
10517 	 * has changed").  So reporting it here, before the reservation
10518 	 * check, may be technically wrong.  I guess the only thing to do
10519 	 * would be to check for and report the reset events here, and then
10520 	 * check for the other unit attention types after we check for a
10521 	 * reservation conflict.
10522 	 *
10523 	 * XXX KDM need to fix this
10524 	 */
10525 	if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
10526 		ctl_ua_type ua_type;
10527 
10528 		ua_type = lun->pending_sense[initidx].ua_pending;
10529 		if (ua_type != CTL_UA_NONE) {
10530 			scsi_sense_data_type sense_format;
10531 
10532 			if (lun != NULL)
10533 				sense_format = (lun->flags &
10534 				    CTL_LUN_SENSE_DESC) ? SSD_TYPE_DESC :
10535 				    SSD_TYPE_FIXED;
10536 			else
10537 				sense_format = SSD_TYPE_FIXED;
10538 
10539 			ua_type = ctl_build_ua(ua_type, &ctsio->sense_data,
10540 					       sense_format);
10541 			if (ua_type != CTL_UA_NONE) {
10542 				ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
10543 				ctsio->io_hdr.status = CTL_SCSI_ERROR |
10544 						       CTL_AUTOSENSE;
10545 				ctsio->sense_len = SSD_FULL_SIZE;
10546 				lun->pending_sense[initidx].ua_pending &=
10547 					~ua_type;
10548 				mtx_unlock(&ctl_softc->ctl_lock);
10549 				ctl_done((union ctl_io *)ctsio);
10550 				goto bailout;
10551 			}
10552 		}
10553 	}
10554 
10555 
10556 	if (ctl_scsiio_lun_check(ctl_softc, lun, entry, ctsio) != 0) {
10557 		mtx_unlock(&ctl_softc->ctl_lock);
10558 		ctl_done((union ctl_io *)ctsio);
10559 		goto bailout;
10560 	}
10561 
10562 	/*
10563 	 * XXX CHD this is where we want to send IO to other side if
10564 	 * this LUN is secondary on this SC. We will need to make a copy
10565 	 * of the IO and flag the IO on this side as SENT_2OTHER and the flag
10566 	 * the copy we send as FROM_OTHER.
10567 	 * We also need to stuff the address of the original IO so we can
10568 	 * find it easily. Something similar will need be done on the other
10569 	 * side so when we are done we can find the copy.
10570 	 */
10571 	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
10572 		union ctl_ha_msg msg_info;
10573 		int isc_retval;
10574 
10575 		ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
10576 
10577 		msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
10578 		msg_info.hdr.original_sc = (union ctl_io *)ctsio;
10579 #if 0
10580 		printf("1. ctsio %p\n", ctsio);
10581 #endif
10582 		msg_info.hdr.serializing_sc = NULL;
10583 		msg_info.hdr.nexus = ctsio->io_hdr.nexus;
10584 		msg_info.scsi.tag_num = ctsio->tag_num;
10585 		msg_info.scsi.tag_type = ctsio->tag_type;
10586 		memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
10587 
10588 		ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
10589 
10590 		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
10591 		    (void *)&msg_info, sizeof(msg_info), 0)) >
10592 		    CTL_HA_STATUS_SUCCESS) {
10593 			printf("CTL:precheck, ctl_ha_msg_send returned %d\n",
10594 			       isc_retval);
10595 			printf("CTL:opcode is %x\n",opcode);
10596 		} else {
10597 #if 0
10598 			printf("CTL:Precheck sent msg, opcode is %x\n",opcode);
10599 #endif
10600 		}
10601 
10602 		/*
10603 		 * XXX KDM this I/O is off the incoming queue, but hasn't
10604 		 * been inserted on any other queue.  We may need to come
10605 		 * up with a holding queue while we wait for serialization
10606 		 * so that we have an idea of what we're waiting for from
10607 		 * the other side.
10608 		 */
10609 		goto bailout_unlock;
10610 	}
10611 
10612 	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
10613 			      (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
10614 			      ctl_ooaq, ooa_links))) {
10615 	case CTL_ACTION_BLOCK:
10616 		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
10617 		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
10618 				  blocked_links);
10619 		goto bailout_unlock;
10620 		break; /* NOTREACHED */
10621 	case CTL_ACTION_PASS:
10622 	case CTL_ACTION_SKIP:
10623 		goto queue_rtr;
10624 		break; /* NOTREACHED */
10625 	case CTL_ACTION_OVERLAP:
10626 		ctl_set_overlapped_cmd(ctsio);
10627 		mtx_unlock(&ctl_softc->ctl_lock);
10628 		ctl_done((union ctl_io *)ctsio);
10629 		goto bailout;
10630 		break; /* NOTREACHED */
10631 	case CTL_ACTION_OVERLAP_TAG:
10632 		ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
10633 		mtx_unlock(&ctl_softc->ctl_lock);
10634 		ctl_done((union ctl_io *)ctsio);
10635 		goto bailout;
10636 		break; /* NOTREACHED */
10637 	case CTL_ACTION_ERROR:
10638 	default:
10639 		ctl_set_internal_failure(ctsio,
10640 					 /*sks_valid*/ 0,
10641 					 /*retry_count*/ 0);
10642 		mtx_unlock(&ctl_softc->ctl_lock);
10643 		ctl_done((union ctl_io *)ctsio);
10644 		goto bailout;
10645 		break; /* NOTREACHED */
10646 	}
10647 
10648 	goto bailout_unlock;
10649 
10650 queue_rtr:
10651 	ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
10652 	STAILQ_INSERT_TAIL(&ctl_softc->rtr_queue, &ctsio->io_hdr, links);
10653 
10654 bailout_unlock:
10655 	mtx_unlock(&ctl_softc->ctl_lock);
10656 
10657 bailout:
10658 	return (retval);
10659 }
10660 
10661 static int
10662 ctl_scsiio(struct ctl_scsiio *ctsio)
10663 {
10664 	int retval;
10665 	struct ctl_cmd_entry *entry;
10666 
10667 	retval = CTL_RETVAL_COMPLETE;
10668 
10669 	CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
10670 
10671 	entry = &ctl_cmd_table[ctsio->cdb[0]];
10672 
10673 	/*
10674 	 * If this I/O has been aborted, just send it straight to
10675 	 * ctl_done() without executing it.
10676 	 */
10677 	if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
10678 		ctl_done((union ctl_io *)ctsio);
10679 		goto bailout;
10680 	}
10681 
10682 	/*
10683 	 * All the checks should have been handled by ctl_scsiio_precheck().
10684 	 * We should be clear now to just execute the I/O.
10685 	 */
10686 	retval = entry->execute(ctsio);
10687 
10688 bailout:
10689 	return (retval);
10690 }
10691 
10692 /*
10693  * Since we only implement one target right now, a bus reset simply resets
10694  * our single target.
10695  */
10696 static int
10697 ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io)
10698 {
10699 	return(ctl_target_reset(ctl_softc, io, CTL_UA_BUS_RESET));
10700 }
10701 
10702 static int
10703 ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
10704 		 ctl_ua_type ua_type)
10705 {
10706 	struct ctl_lun *lun;
10707 	int retval;
10708 
10709 	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
10710 		union ctl_ha_msg msg_info;
10711 
10712 		io->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
10713 		msg_info.hdr.nexus = io->io_hdr.nexus;
10714 		if (ua_type==CTL_UA_TARG_RESET)
10715 			msg_info.task.task_action = CTL_TASK_TARGET_RESET;
10716 		else
10717 			msg_info.task.task_action = CTL_TASK_BUS_RESET;
10718 		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
10719 		msg_info.hdr.original_sc = NULL;
10720 		msg_info.hdr.serializing_sc = NULL;
10721 		if (CTL_HA_STATUS_SUCCESS != ctl_ha_msg_send(CTL_HA_CHAN_CTL,
10722 		    (void *)&msg_info, sizeof(msg_info), 0)) {
10723 		}
10724 	}
10725 	retval = 0;
10726 
10727 	STAILQ_FOREACH(lun, &ctl_softc->lun_list, links)
10728 		retval += ctl_lun_reset(lun, io, ua_type);
10729 
10730 	return (retval);
10731 }
10732 
10733 /*
10734  * The LUN should always be set.  The I/O is optional, and is used to
10735  * distinguish between I/Os sent by this initiator, and by other
10736  * initiators.  We set unit attention for initiators other than this one.
10737  * SAM-3 is vague on this point.  It does say that a unit attention should
10738  * be established for other initiators when a LUN is reset (see section
10739  * 5.7.3), but it doesn't specifically say that the unit attention should
10740  * be established for this particular initiator when a LUN is reset.  Here
10741  * is the relevant text, from SAM-3 rev 8:
10742  *
10743  * 5.7.2 When a SCSI initiator port aborts its own tasks
10744  *
10745  * When a SCSI initiator port causes its own task(s) to be aborted, no
10746  * notification that the task(s) have been aborted shall be returned to
10747  * the SCSI initiator port other than the completion response for the
10748  * command or task management function action that caused the task(s) to
10749  * be aborted and notification(s) associated with related effects of the
10750  * action (e.g., a reset unit attention condition).
10751  *
10752  * XXX KDM for now, we're setting unit attention for all initiators.
10753  */
10754 static int
10755 ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
10756 {
10757 	union ctl_io *xio;
10758 #if 0
10759 	uint32_t initindex;
10760 #endif
10761 	int i;
10762 
10763 	/*
10764 	 * Run through the OOA queue and abort each I/O.
10765 	 */
10766 #if 0
10767 	TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
10768 #endif
10769 	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
10770 	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
10771 		xio->io_hdr.flags |= CTL_FLAG_ABORT;
10772 	}
10773 
10774 	/*
10775 	 * This version sets unit attention for every
10776 	 */
10777 #if 0
10778 	initindex = ctl_get_initindex(&io->io_hdr.nexus);
10779 	for (i = 0; i < CTL_MAX_INITIATORS; i++) {
10780 		if (initindex == i)
10781 			continue;
10782 		lun->pending_sense[i].ua_pending |= ua_type;
10783 	}
10784 #endif
10785 
10786 	/*
10787 	 * A reset (any kind, really) clears reservations established with
10788 	 * RESERVE/RELEASE.  It does not clear reservations established
10789 	 * with PERSISTENT RESERVE OUT, but we don't support that at the
10790 	 * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
10791 	 * reservations made with the RESERVE/RELEASE commands, because
10792 	 * those commands are obsolete in SPC-3.
10793 	 */
10794 	lun->flags &= ~CTL_LUN_RESERVED;
10795 
10796 	for (i = 0; i < CTL_MAX_INITIATORS; i++) {
10797 		ctl_clear_mask(lun->have_ca, i);
10798 		lun->pending_sense[i].ua_pending |= ua_type;
10799 	}
10800 
10801 	return (0);
10802 }
10803 
10804 static int
10805 ctl_abort_task(union ctl_io *io)
10806 {
10807 	union ctl_io *xio;
10808 	struct ctl_lun *lun;
10809 	struct ctl_softc *ctl_softc;
10810 #if 0
10811 	struct sbuf sb;
10812 	char printbuf[128];
10813 #endif
10814 	int found;
10815 	uint32_t targ_lun;
10816 
10817 	ctl_softc = control_softc;
10818 	found = 0;
10819 
10820 	/*
10821 	 * Look up the LUN.
10822 	 */
10823 	targ_lun = io->io_hdr.nexus.targ_lun;
10824 	if (io->io_hdr.nexus.lun_map_fn != NULL)
10825 		targ_lun = io->io_hdr.nexus.lun_map_fn(io->io_hdr.nexus.lun_map_arg, targ_lun);
10826 	if ((targ_lun < CTL_MAX_LUNS)
10827 	 && (ctl_softc->ctl_luns[targ_lun] != NULL))
10828 		lun = ctl_softc->ctl_luns[targ_lun];
10829 	else
10830 		goto bailout;
10831 
10832 #if 0
10833 	printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
10834 	       lun->lun, io->taskio.tag_num, io->taskio.tag_type);
10835 #endif
10836 
10837 	/*
10838 	 * Run through the OOA queue and attempt to find the given I/O.
10839 	 * The target port, initiator ID, tag type and tag number have to
10840 	 * match the values that we got from the initiator.  If we have an
10841 	 * untagged command to abort, simply abort the first untagged command
10842 	 * we come to.  We only allow one untagged command at a time of course.
10843 	 */
10844 #if 0
10845 	TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
10846 #endif
10847 	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
10848 	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
10849 #if 0
10850 		sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
10851 
10852 		sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
10853 			    lun->lun, xio->scsiio.tag_num,
10854 			    xio->scsiio.tag_type,
10855 			    (xio->io_hdr.blocked_links.tqe_prev
10856 			    == NULL) ? "" : " BLOCKED",
10857 			    (xio->io_hdr.flags &
10858 			    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
10859 			    (xio->io_hdr.flags &
10860 			    CTL_FLAG_ABORT) ? " ABORT" : "",
10861 			    (xio->io_hdr.flags &
10862 			    CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
10863 		ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
10864 		sbuf_finish(&sb);
10865 		printf("%s\n", sbuf_data(&sb));
10866 #endif
10867 
10868 		if ((xio->io_hdr.nexus.targ_port == io->io_hdr.nexus.targ_port)
10869 		 && (xio->io_hdr.nexus.initid.id ==
10870 		     io->io_hdr.nexus.initid.id)) {
10871 			/*
10872 			 * If the abort says that the task is untagged, the
10873 			 * task in the queue must be untagged.  Otherwise,
10874 			 * we just check to see whether the tag numbers
10875 			 * match.  This is because the QLogic firmware
10876 			 * doesn't pass back the tag type in an abort
10877 			 * request.
10878 			 */
10879 #if 0
10880 			if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
10881 			  && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
10882 			 || (xio->scsiio.tag_num == io->taskio.tag_num)) {
10883 #endif
10884 			/*
10885 			 * XXX KDM we've got problems with FC, because it
10886 			 * doesn't send down a tag type with aborts.  So we
10887 			 * can only really go by the tag number...
10888 			 * This may cause problems with parallel SCSI.
10889 			 * Need to figure that out!!
10890 			 */
10891 			if (xio->scsiio.tag_num == io->taskio.tag_num) {
10892 				xio->io_hdr.flags |= CTL_FLAG_ABORT;
10893 				found = 1;
10894 				if ((io->io_hdr.flags &
10895 				     CTL_FLAG_FROM_OTHER_SC) == 0 &&
10896 				    !(lun->flags & CTL_LUN_PRIMARY_SC)) {
10897 					union ctl_ha_msg msg_info;
10898 
10899 					io->io_hdr.flags |=
10900 					                CTL_FLAG_SENT_2OTHER_SC;
10901 					msg_info.hdr.nexus = io->io_hdr.nexus;
10902 					msg_info.task.task_action =
10903 						CTL_TASK_ABORT_TASK;
10904 					msg_info.task.tag_num =
10905 						io->taskio.tag_num;
10906 					msg_info.task.tag_type =
10907 						io->taskio.tag_type;
10908 					msg_info.hdr.msg_type =
10909 						CTL_MSG_MANAGE_TASKS;
10910 					msg_info.hdr.original_sc = NULL;
10911 					msg_info.hdr.serializing_sc = NULL;
10912 #if 0
10913 					printf("Sent Abort to other side\n");
10914 #endif
10915 					if (CTL_HA_STATUS_SUCCESS !=
10916 					        ctl_ha_msg_send(CTL_HA_CHAN_CTL,
10917 		    				(void *)&msg_info,
10918 						sizeof(msg_info), 0)) {
10919 					}
10920 				}
10921 #if 0
10922 				printf("ctl_abort_task: found I/O to abort\n");
10923 #endif
10924 				break;
10925 			}
10926 		}
10927 	}
10928 
10929 bailout:
10930 
10931 	if (found == 0) {
10932 		/*
10933 		 * This isn't really an error.  It's entirely possible for
10934 		 * the abort and command completion to cross on the wire.
10935 		 * This is more of an informative/diagnostic error.
10936 		 */
10937 #if 0
10938 		printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
10939 		       "%d:%d:%d:%d tag %d type %d\n",
10940 		       io->io_hdr.nexus.initid.id,
10941 		       io->io_hdr.nexus.targ_port,
10942 		       io->io_hdr.nexus.targ_target.id,
10943 		       io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
10944 		       io->taskio.tag_type);
10945 #endif
10946 		return (1);
10947 	} else
10948 		return (0);
10949 }
10950 
10951 /*
10952  * This routine cannot block!  It must be callable from an interrupt
10953  * handler as well as from the work thread.
10954  */
10955 static void
10956 ctl_run_task_queue(struct ctl_softc *ctl_softc)
10957 {
10958 	union ctl_io *io, *next_io;
10959 
10960 	mtx_assert(&ctl_softc->ctl_lock, MA_OWNED);
10961 
10962 	CTL_DEBUG_PRINT(("ctl_run_task_queue\n"));
10963 
10964 	for (io = (union ctl_io *)STAILQ_FIRST(&ctl_softc->task_queue);
10965 	     io != NULL; io = next_io) {
10966 		int retval;
10967 		const char *task_desc;
10968 
10969 		next_io = (union ctl_io *)STAILQ_NEXT(&io->io_hdr, links);
10970 
10971 		retval = 0;
10972 
10973 		switch (io->io_hdr.io_type) {
10974 		case CTL_IO_TASK: {
10975 			task_desc = ctl_scsi_task_string(&io->taskio);
10976 			if (task_desc != NULL) {
10977 #ifdef NEEDTOPORT
10978 				csevent_log(CSC_CTL | CSC_SHELF_SW |
10979 					    CTL_TASK_REPORT,
10980 					    csevent_LogType_Trace,
10981 					    csevent_Severity_Information,
10982 					    csevent_AlertLevel_Green,
10983 					    csevent_FRU_Firmware,
10984 					    csevent_FRU_Unknown,
10985 					    "CTL: received task: %s",task_desc);
10986 #endif
10987 			} else {
10988 #ifdef NEEDTOPORT
10989 				csevent_log(CSC_CTL | CSC_SHELF_SW |
10990 					    CTL_TASK_REPORT,
10991 					    csevent_LogType_Trace,
10992 					    csevent_Severity_Information,
10993 					    csevent_AlertLevel_Green,
10994 					    csevent_FRU_Firmware,
10995 					    csevent_FRU_Unknown,
10996 					    "CTL: received unknown task "
10997 					    "type: %d (%#x)",
10998 					    io->taskio.task_action,
10999 					    io->taskio.task_action);
11000 #endif
11001 			}
11002 			switch (io->taskio.task_action) {
11003 			case CTL_TASK_ABORT_TASK:
11004 				retval = ctl_abort_task(io);
11005 				break;
11006 			case CTL_TASK_ABORT_TASK_SET:
11007 				break;
11008 			case CTL_TASK_CLEAR_ACA:
11009 				break;
11010 			case CTL_TASK_CLEAR_TASK_SET:
11011 				break;
11012 			case CTL_TASK_LUN_RESET: {
11013 				struct ctl_lun *lun;
11014 				uint32_t targ_lun;
11015 				int retval;
11016 
11017 				targ_lun = io->io_hdr.nexus.targ_lun;
11018 				if (io->io_hdr.nexus.lun_map_fn != NULL)
11019 					targ_lun = io->io_hdr.nexus.lun_map_fn(io->io_hdr.nexus.lun_map_arg, targ_lun);
11020 
11021 				if ((targ_lun < CTL_MAX_LUNS)
11022 				 && (ctl_softc->ctl_luns[targ_lun] != NULL))
11023 					lun = ctl_softc->ctl_luns[targ_lun];
11024 				else {
11025 					retval = 1;
11026 					break;
11027 				}
11028 
11029 				if (!(io->io_hdr.flags &
11030 				    CTL_FLAG_FROM_OTHER_SC)) {
11031 					union ctl_ha_msg msg_info;
11032 
11033 					io->io_hdr.flags |=
11034 						CTL_FLAG_SENT_2OTHER_SC;
11035 					msg_info.hdr.msg_type =
11036 						CTL_MSG_MANAGE_TASKS;
11037 					msg_info.hdr.nexus = io->io_hdr.nexus;
11038 					msg_info.task.task_action =
11039 						CTL_TASK_LUN_RESET;
11040 					msg_info.hdr.original_sc = NULL;
11041 					msg_info.hdr.serializing_sc = NULL;
11042 					if (CTL_HA_STATUS_SUCCESS !=
11043 					    ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11044 					    (void *)&msg_info,
11045 					    sizeof(msg_info), 0)) {
11046 					}
11047 				}
11048 
11049 				retval = ctl_lun_reset(lun, io,
11050 						       CTL_UA_LUN_RESET);
11051 				break;
11052 			}
11053 			case CTL_TASK_TARGET_RESET:
11054 				retval = ctl_target_reset(ctl_softc, io,
11055 							  CTL_UA_TARG_RESET);
11056 				break;
11057 			case CTL_TASK_BUS_RESET:
11058 				retval = ctl_bus_reset(ctl_softc, io);
11059 				break;
11060 			case CTL_TASK_PORT_LOGIN:
11061 				break;
11062 			case CTL_TASK_PORT_LOGOUT:
11063 				break;
11064 			default:
11065 				printf("ctl_run_task_queue: got unknown task "
11066 				       "management event %d\n",
11067 				       io->taskio.task_action);
11068 				break;
11069 			}
11070 			if (retval == 0)
11071 				io->io_hdr.status = CTL_SUCCESS;
11072 			else
11073 				io->io_hdr.status = CTL_ERROR;
11074 
11075 			STAILQ_REMOVE(&ctl_softc->task_queue, &io->io_hdr,
11076 				      ctl_io_hdr, links);
11077 			/*
11078 			 * This will queue this I/O to the done queue, but the
11079 			 * work thread won't be able to process it until we
11080 			 * return and the lock is released.
11081 			 */
11082 			ctl_done_lock(io, /*have_lock*/ 1);
11083 			break;
11084 		}
11085 		default: {
11086 
11087 			printf("%s: invalid I/O type %d msg %d cdb %x"
11088 			       " iptl: %ju:%d:%ju:%d tag 0x%04x\n",
11089 			       __func__, io->io_hdr.io_type,
11090 			       io->io_hdr.msg_type, io->scsiio.cdb[0],
11091 			       (uintmax_t)io->io_hdr.nexus.initid.id,
11092 			       io->io_hdr.nexus.targ_port,
11093 			       (uintmax_t)io->io_hdr.nexus.targ_target.id,
11094 			       io->io_hdr.nexus.targ_lun /* XXX */,
11095 			       (io->io_hdr.io_type == CTL_IO_TASK) ?
11096 			       io->taskio.tag_num : io->scsiio.tag_num);
11097 			STAILQ_REMOVE(&ctl_softc->task_queue, &io->io_hdr,
11098 				      ctl_io_hdr, links);
11099 			ctl_free_io_internal(io, 1);
11100 			break;
11101 		}
11102 		}
11103 	}
11104 
11105 	ctl_softc->flags &= ~CTL_FLAG_TASK_PENDING;
11106 }
11107 
11108 /*
11109  * For HA operation.  Handle commands that come in from the other
11110  * controller.
11111  */
11112 static void
11113 ctl_handle_isc(union ctl_io *io)
11114 {
11115 	int free_io;
11116 	struct ctl_lun *lun;
11117 	struct ctl_softc *ctl_softc;
11118 	uint32_t targ_lun;
11119 
11120 	ctl_softc = control_softc;
11121 
11122 	targ_lun = io->io_hdr.nexus.targ_lun;
11123 	if (io->io_hdr.nexus.lun_map_fn != NULL)
11124 		targ_lun = io->io_hdr.nexus.lun_map_fn(io->io_hdr.nexus.lun_map_arg, targ_lun);
11125 	lun = ctl_softc->ctl_luns[targ_lun];
11126 
11127 	switch (io->io_hdr.msg_type) {
11128 	case CTL_MSG_SERIALIZE:
11129 		free_io = ctl_serialize_other_sc_cmd(&io->scsiio,
11130 						     /*have_lock*/ 0);
11131 		break;
11132 	case CTL_MSG_R2R: {
11133 		uint8_t opcode;
11134 		struct ctl_cmd_entry *entry;
11135 
11136 		/*
11137 		 * This is only used in SER_ONLY mode.
11138 		 */
11139 		free_io = 0;
11140 		opcode = io->scsiio.cdb[0];
11141 		entry = &ctl_cmd_table[opcode];
11142 		mtx_lock(&ctl_softc->ctl_lock);
11143 		if (ctl_scsiio_lun_check(ctl_softc, lun,
11144 		    entry, (struct ctl_scsiio *)io) != 0) {
11145 			ctl_done_lock(io, /*have_lock*/ 1);
11146 			mtx_unlock(&ctl_softc->ctl_lock);
11147 			break;
11148 		}
11149 		io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11150 		STAILQ_INSERT_TAIL(&ctl_softc->rtr_queue,
11151 				   &io->io_hdr, links);
11152 		mtx_unlock(&ctl_softc->ctl_lock);
11153 		break;
11154 	}
11155 	case CTL_MSG_FINISH_IO:
11156 		if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
11157 			free_io = 0;
11158 			ctl_done_lock(io, /*have_lock*/ 0);
11159 		} else {
11160 			free_io = 1;
11161 			mtx_lock(&ctl_softc->ctl_lock);
11162 			TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr,
11163 				     ooa_links);
11164 			STAILQ_REMOVE(&ctl_softc->task_queue,
11165 				      &io->io_hdr, ctl_io_hdr, links);
11166 			ctl_check_blocked(lun);
11167 			mtx_unlock(&ctl_softc->ctl_lock);
11168 		}
11169 		break;
11170 	case CTL_MSG_PERS_ACTION:
11171 		ctl_hndl_per_res_out_on_other_sc(
11172 			(union ctl_ha_msg *)&io->presio.pr_msg);
11173 		free_io = 1;
11174 		break;
11175 	case CTL_MSG_BAD_JUJU:
11176 		free_io = 0;
11177 		ctl_done_lock(io, /*have_lock*/ 0);
11178 		break;
11179 	case CTL_MSG_DATAMOVE:
11180 		/* Only used in XFER mode */
11181 		free_io = 0;
11182 		ctl_datamove_remote(io);
11183 		break;
11184 	case CTL_MSG_DATAMOVE_DONE:
11185 		/* Only used in XFER mode */
11186 		free_io = 0;
11187 		io->scsiio.be_move_done(io);
11188 		break;
11189 	default:
11190 		free_io = 1;
11191 		printf("%s: Invalid message type %d\n",
11192 		       __func__, io->io_hdr.msg_type);
11193 		break;
11194 	}
11195 	if (free_io)
11196 		ctl_free_io_internal(io, 0);
11197 
11198 }
11199 
11200 
11201 /*
11202  * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
11203  * there is no match.
11204  */
11205 static ctl_lun_error_pattern
11206 ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
11207 {
11208 	struct ctl_cmd_entry *entry;
11209 	ctl_lun_error_pattern filtered_pattern, pattern;
11210 	uint8_t opcode;
11211 
11212 	pattern = desc->error_pattern;
11213 
11214 	/*
11215 	 * XXX KDM we need more data passed into this function to match a
11216 	 * custom pattern, and we actually need to implement custom pattern
11217 	 * matching.
11218 	 */
11219 	if (pattern & CTL_LUN_PAT_CMD)
11220 		return (CTL_LUN_PAT_CMD);
11221 
11222 	if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
11223 		return (CTL_LUN_PAT_ANY);
11224 
11225 	opcode = ctsio->cdb[0];
11226 	entry = &ctl_cmd_table[opcode];
11227 
11228 	filtered_pattern = entry->pattern & pattern;
11229 
11230 	/*
11231 	 * If the user requested specific flags in the pattern (e.g.
11232 	 * CTL_LUN_PAT_RANGE), make sure the command supports all of those
11233 	 * flags.
11234 	 *
11235 	 * If the user did not specify any flags, it doesn't matter whether
11236 	 * or not the command supports the flags.
11237 	 */
11238 	if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
11239 	     (pattern & ~CTL_LUN_PAT_MASK))
11240 		return (CTL_LUN_PAT_NONE);
11241 
11242 	/*
11243 	 * If the user asked for a range check, see if the requested LBA
11244 	 * range overlaps with this command's LBA range.
11245 	 */
11246 	if (filtered_pattern & CTL_LUN_PAT_RANGE) {
11247 		uint64_t lba1;
11248 		uint32_t len1;
11249 		ctl_action action;
11250 		int retval;
11251 
11252 		retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
11253 		if (retval != 0)
11254 			return (CTL_LUN_PAT_NONE);
11255 
11256 		action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
11257 					      desc->lba_range.len);
11258 		/*
11259 		 * A "pass" means that the LBA ranges don't overlap, so
11260 		 * this doesn't match the user's range criteria.
11261 		 */
11262 		if (action == CTL_ACTION_PASS)
11263 			return (CTL_LUN_PAT_NONE);
11264 	}
11265 
11266 	return (filtered_pattern);
11267 }
11268 
11269 static void
11270 ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
11271 {
11272 	struct ctl_error_desc *desc, *desc2;
11273 
11274 	mtx_assert(&control_softc->ctl_lock, MA_OWNED);
11275 
11276 	STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
11277 		ctl_lun_error_pattern pattern;
11278 		/*
11279 		 * Check to see whether this particular command matches
11280 		 * the pattern in the descriptor.
11281 		 */
11282 		pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
11283 		if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
11284 			continue;
11285 
11286 		switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
11287 		case CTL_LUN_INJ_ABORTED:
11288 			ctl_set_aborted(&io->scsiio);
11289 			break;
11290 		case CTL_LUN_INJ_MEDIUM_ERR:
11291 			ctl_set_medium_error(&io->scsiio);
11292 			break;
11293 		case CTL_LUN_INJ_UA:
11294 			/* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
11295 			 * OCCURRED */
11296 			ctl_set_ua(&io->scsiio, 0x29, 0x00);
11297 			break;
11298 		case CTL_LUN_INJ_CUSTOM:
11299 			/*
11300 			 * We're assuming the user knows what he is doing.
11301 			 * Just copy the sense information without doing
11302 			 * checks.
11303 			 */
11304 			bcopy(&desc->custom_sense, &io->scsiio.sense_data,
11305 			      ctl_min(sizeof(desc->custom_sense),
11306 				      sizeof(io->scsiio.sense_data)));
11307 			io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
11308 			io->scsiio.sense_len = SSD_FULL_SIZE;
11309 			io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
11310 			break;
11311 		case CTL_LUN_INJ_NONE:
11312 		default:
11313 			/*
11314 			 * If this is an error injection type we don't know
11315 			 * about, clear the continuous flag (if it is set)
11316 			 * so it will get deleted below.
11317 			 */
11318 			desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
11319 			break;
11320 		}
11321 		/*
11322 		 * By default, each error injection action is a one-shot
11323 		 */
11324 		if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
11325 			continue;
11326 
11327 		STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
11328 
11329 		free(desc, M_CTL);
11330 	}
11331 }
11332 
11333 #ifdef CTL_IO_DELAY
11334 static void
11335 ctl_datamove_timer_wakeup(void *arg)
11336 {
11337 	union ctl_io *io;
11338 
11339 	io = (union ctl_io *)arg;
11340 
11341 	ctl_datamove(io);
11342 }
11343 #endif /* CTL_IO_DELAY */
11344 
11345 void
11346 ctl_datamove(union ctl_io *io)
11347 {
11348 	void (*fe_datamove)(union ctl_io *io);
11349 
11350 	mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
11351 
11352 	CTL_DEBUG_PRINT(("ctl_datamove\n"));
11353 
11354 #ifdef CTL_TIME_IO
11355 	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
11356 		char str[256];
11357 		char path_str[64];
11358 		struct sbuf sb;
11359 
11360 		ctl_scsi_path_string(io, path_str, sizeof(path_str));
11361 		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
11362 
11363 		sbuf_cat(&sb, path_str);
11364 		switch (io->io_hdr.io_type) {
11365 		case CTL_IO_SCSI:
11366 			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
11367 			sbuf_printf(&sb, "\n");
11368 			sbuf_cat(&sb, path_str);
11369 			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
11370 				    io->scsiio.tag_num, io->scsiio.tag_type);
11371 			break;
11372 		case CTL_IO_TASK:
11373 			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
11374 				    "Tag Type: %d\n", io->taskio.task_action,
11375 				    io->taskio.tag_num, io->taskio.tag_type);
11376 			break;
11377 		default:
11378 			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
11379 			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
11380 			break;
11381 		}
11382 		sbuf_cat(&sb, path_str);
11383 		sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
11384 			    (intmax_t)time_uptime - io->io_hdr.start_time);
11385 		sbuf_finish(&sb);
11386 		printf("%s", sbuf_data(&sb));
11387 	}
11388 #endif /* CTL_TIME_IO */
11389 
11390 	mtx_lock(&control_softc->ctl_lock);
11391 #ifdef CTL_IO_DELAY
11392 	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
11393 		struct ctl_lun *lun;
11394 
11395 		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
11396 
11397 		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
11398 	} else {
11399 		struct ctl_lun *lun;
11400 
11401 		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
11402 		if ((lun != NULL)
11403 		 && (lun->delay_info.datamove_delay > 0)) {
11404 			struct callout *callout;
11405 
11406 			callout = (struct callout *)&io->io_hdr.timer_bytes;
11407 			callout_init(callout, /*mpsafe*/ 1);
11408 			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
11409 			callout_reset(callout,
11410 				      lun->delay_info.datamove_delay * hz,
11411 				      ctl_datamove_timer_wakeup, io);
11412 			if (lun->delay_info.datamove_type ==
11413 			    CTL_DELAY_TYPE_ONESHOT)
11414 				lun->delay_info.datamove_delay = 0;
11415 			mtx_unlock(&control_softc->ctl_lock);
11416 			return;
11417 		}
11418 	}
11419 #endif
11420 	/*
11421 	 * If we have any pending task management commands, process them
11422 	 * first.  This is necessary to eliminate a race condition with the
11423 	 * FETD:
11424 	 *
11425 	 * - FETD submits a task management command, like an abort.
11426 	 * - Back end calls fe_datamove() to move the data for the aborted
11427 	 *   command.  The FETD can't really accept it, but if it did, it
11428 	 *   would end up transmitting data for a command that the initiator
11429 	 *   told us to abort.
11430 	 *
11431 	 * We close the race by processing all pending task management
11432 	 * commands here (we can't block!), and then check this I/O to see
11433 	 * if it has been aborted.  If so, return it to the back end with
11434 	 * bad status, so the back end can say return an error to the back end
11435 	 * and then when the back end returns an error, we can return the
11436 	 * aborted command to the FETD, so it can clean up its resources.
11437 	 */
11438 	if (control_softc->flags & CTL_FLAG_TASK_PENDING)
11439 		ctl_run_task_queue(control_softc);
11440 
11441 	/*
11442 	 * This command has been aborted.  Set the port status, so we fail
11443 	 * the data move.
11444 	 */
11445 	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
11446 		printf("ctl_datamove: tag 0x%04x on (%ju:%d:%ju:%d) aborted\n",
11447 		       io->scsiio.tag_num,(uintmax_t)io->io_hdr.nexus.initid.id,
11448 		       io->io_hdr.nexus.targ_port,
11449 		       (uintmax_t)io->io_hdr.nexus.targ_target.id,
11450 		       io->io_hdr.nexus.targ_lun);
11451 		io->io_hdr.status = CTL_CMD_ABORTED;
11452 		io->io_hdr.port_status = 31337;
11453 		mtx_unlock(&control_softc->ctl_lock);
11454 		/*
11455 		 * Note that the backend, in this case, will get the
11456 		 * callback in its context.  In other cases it may get
11457 		 * called in the frontend's interrupt thread context.
11458 		 */
11459 		io->scsiio.be_move_done(io);
11460 		return;
11461 	}
11462 
11463 	/*
11464 	 * If we're in XFER mode and this I/O is from the other shelf
11465 	 * controller, we need to send the DMA to the other side to
11466 	 * actually transfer the data to/from the host.  In serialize only
11467 	 * mode the transfer happens below CTL and ctl_datamove() is only
11468 	 * called on the machine that originally received the I/O.
11469 	 */
11470 	if ((control_softc->ha_mode == CTL_HA_MODE_XFER)
11471 	 && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11472 		union ctl_ha_msg msg;
11473 		uint32_t sg_entries_sent;
11474 		int do_sg_copy;
11475 		int i;
11476 
11477 		memset(&msg, 0, sizeof(msg));
11478 		msg.hdr.msg_type = CTL_MSG_DATAMOVE;
11479 		msg.hdr.original_sc = io->io_hdr.original_sc;
11480 		msg.hdr.serializing_sc = io;
11481 		msg.hdr.nexus = io->io_hdr.nexus;
11482 		msg.dt.flags = io->io_hdr.flags;
11483 		/*
11484 		 * We convert everything into a S/G list here.  We can't
11485 		 * pass by reference, only by value between controllers.
11486 		 * So we can't pass a pointer to the S/G list, only as many
11487 		 * S/G entries as we can fit in here.  If it's possible for
11488 		 * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
11489 		 * then we need to break this up into multiple transfers.
11490 		 */
11491 		if (io->scsiio.kern_sg_entries == 0) {
11492 			msg.dt.kern_sg_entries = 1;
11493 			/*
11494 			 * If this is in cached memory, flush the cache
11495 			 * before we send the DMA request to the other
11496 			 * controller.  We want to do this in either the
11497 			 * read or the write case.  The read case is
11498 			 * straightforward.  In the write case, we want to
11499 			 * make sure nothing is in the local cache that
11500 			 * could overwrite the DMAed data.
11501 			 */
11502 			if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
11503 				/*
11504 				 * XXX KDM use bus_dmamap_sync() here.
11505 				 */
11506 			}
11507 
11508 			/*
11509 			 * Convert to a physical address if this is a
11510 			 * virtual address.
11511 			 */
11512 			if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
11513 				msg.dt.sg_list[0].addr =
11514 					io->scsiio.kern_data_ptr;
11515 			} else {
11516 				/*
11517 				 * XXX KDM use busdma here!
11518 				 */
11519 #if 0
11520 				msg.dt.sg_list[0].addr = (void *)
11521 					vtophys(io->scsiio.kern_data_ptr);
11522 #endif
11523 			}
11524 
11525 			msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
11526 			do_sg_copy = 0;
11527 		} else {
11528 			struct ctl_sg_entry *sgl;
11529 
11530 			do_sg_copy = 1;
11531 			msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
11532 			sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
11533 			if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
11534 				/*
11535 				 * XXX KDM use bus_dmamap_sync() here.
11536 				 */
11537 			}
11538 		}
11539 
11540 		msg.dt.kern_data_len = io->scsiio.kern_data_len;
11541 		msg.dt.kern_total_len = io->scsiio.kern_total_len;
11542 		msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
11543 		msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
11544 		msg.dt.sg_sequence = 0;
11545 
11546 		/*
11547 		 * Loop until we've sent all of the S/G entries.  On the
11548 		 * other end, we'll recompose these S/G entries into one
11549 		 * contiguous list before passing it to the
11550 		 */
11551 		for (sg_entries_sent = 0; sg_entries_sent <
11552 		     msg.dt.kern_sg_entries; msg.dt.sg_sequence++) {
11553 			msg.dt.cur_sg_entries = ctl_min((sizeof(msg.dt.sg_list)/
11554 				sizeof(msg.dt.sg_list[0])),
11555 				msg.dt.kern_sg_entries - sg_entries_sent);
11556 
11557 			if (do_sg_copy != 0) {
11558 				struct ctl_sg_entry *sgl;
11559 				int j;
11560 
11561 				sgl = (struct ctl_sg_entry *)
11562 					io->scsiio.kern_data_ptr;
11563 				/*
11564 				 * If this is in cached memory, flush the cache
11565 				 * before we send the DMA request to the other
11566 				 * controller.  We want to do this in either
11567 				 * the * read or the write case.  The read
11568 				 * case is straightforward.  In the write
11569 				 * case, we want to make sure nothing is
11570 				 * in the local cache that could overwrite
11571 				 * the DMAed data.
11572 				 */
11573 
11574 				for (i = sg_entries_sent, j = 0;
11575 				     i < msg.dt.cur_sg_entries; i++, j++) {
11576 					if ((io->io_hdr.flags &
11577 					     CTL_FLAG_NO_DATASYNC) == 0) {
11578 						/*
11579 						 * XXX KDM use bus_dmamap_sync()
11580 						 */
11581 					}
11582 					if ((io->io_hdr.flags &
11583 					     CTL_FLAG_BUS_ADDR) == 0) {
11584 						/*
11585 						 * XXX KDM use busdma.
11586 						 */
11587 #if 0
11588 						msg.dt.sg_list[j].addr =(void *)
11589 						       vtophys(sgl[i].addr);
11590 #endif
11591 					} else {
11592 						msg.dt.sg_list[j].addr =
11593 							sgl[i].addr;
11594 					}
11595 					msg.dt.sg_list[j].len = sgl[i].len;
11596 				}
11597 			}
11598 
11599 			sg_entries_sent += msg.dt.cur_sg_entries;
11600 			if (sg_entries_sent >= msg.dt.kern_sg_entries)
11601 				msg.dt.sg_last = 1;
11602 			else
11603 				msg.dt.sg_last = 0;
11604 
11605 			/*
11606 			 * XXX KDM drop and reacquire the lock here?
11607 			 */
11608 			if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
11609 			    sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
11610 				/*
11611 				 * XXX do something here.
11612 				 */
11613 			}
11614 
11615 			msg.dt.sent_sg_entries = sg_entries_sent;
11616 		}
11617 		io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11618 		if (io->io_hdr.flags & CTL_FLAG_FAILOVER)
11619 			ctl_failover_io(io, /*have_lock*/ 1);
11620 
11621 	} else {
11622 
11623 		/*
11624 		 * Lookup the fe_datamove() function for this particular
11625 		 * front end.
11626 		 */
11627 		fe_datamove =
11628 		    control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
11629 		mtx_unlock(&control_softc->ctl_lock);
11630 
11631 		fe_datamove(io);
11632 	}
11633 }
11634 
11635 static void
11636 ctl_send_datamove_done(union ctl_io *io, int have_lock)
11637 {
11638 	union ctl_ha_msg msg;
11639 	int isc_status;
11640 
11641 	memset(&msg, 0, sizeof(msg));
11642 
11643 	msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
11644 	msg.hdr.original_sc = io;
11645 	msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
11646 	msg.hdr.nexus = io->io_hdr.nexus;
11647 	msg.hdr.status = io->io_hdr.status;
11648 	msg.scsi.tag_num = io->scsiio.tag_num;
11649 	msg.scsi.tag_type = io->scsiio.tag_type;
11650 	msg.scsi.scsi_status = io->scsiio.scsi_status;
11651 	memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
11652 	       sizeof(io->scsiio.sense_data));
11653 	msg.scsi.sense_len = io->scsiio.sense_len;
11654 	msg.scsi.sense_residual = io->scsiio.sense_residual;
11655 	msg.scsi.fetd_status = io->io_hdr.port_status;
11656 	msg.scsi.residual = io->scsiio.residual;
11657 	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11658 
11659 	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
11660 		ctl_failover_io(io, /*have_lock*/ have_lock);
11661 		return;
11662 	}
11663 
11664 	isc_status = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0);
11665 	if (isc_status > CTL_HA_STATUS_SUCCESS) {
11666 		/* XXX do something if this fails */
11667 	}
11668 
11669 }
11670 
11671 /*
11672  * The DMA to the remote side is done, now we need to tell the other side
11673  * we're done so it can continue with its data movement.
11674  */
11675 static void
11676 ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
11677 {
11678 	union ctl_io *io;
11679 
11680 	io = rq->context;
11681 
11682 	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
11683 		printf("%s: ISC DMA write failed with error %d", __func__,
11684 		       rq->ret);
11685 		ctl_set_internal_failure(&io->scsiio,
11686 					 /*sks_valid*/ 1,
11687 					 /*retry_count*/ rq->ret);
11688 	}
11689 
11690 	ctl_dt_req_free(rq);
11691 
11692 	/*
11693 	 * In this case, we had to malloc the memory locally.  Free it.
11694 	 */
11695 	if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
11696 		int i;
11697 		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
11698 			free(io->io_hdr.local_sglist[i].addr, M_CTL);
11699 	}
11700 	/*
11701 	 * The data is in local and remote memory, so now we need to send
11702 	 * status (good or back) back to the other side.
11703 	 */
11704 	ctl_send_datamove_done(io, /*have_lock*/ 0);
11705 }
11706 
11707 /*
11708  * We've moved the data from the host/controller into local memory.  Now we
11709  * need to push it over to the remote controller's memory.
11710  */
11711 static int
11712 ctl_datamove_remote_dm_write_cb(union ctl_io *io)
11713 {
11714 	int retval;
11715 
11716 	retval = 0;
11717 
11718 	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
11719 					  ctl_datamove_remote_write_cb);
11720 
11721 	return (retval);
11722 }
11723 
11724 static void
11725 ctl_datamove_remote_write(union ctl_io *io)
11726 {
11727 	int retval;
11728 	void (*fe_datamove)(union ctl_io *io);
11729 
11730 	/*
11731 	 * - Get the data from the host/HBA into local memory.
11732 	 * - DMA memory from the local controller to the remote controller.
11733 	 * - Send status back to the remote controller.
11734 	 */
11735 
11736 	retval = ctl_datamove_remote_sgl_setup(io);
11737 	if (retval != 0)
11738 		return;
11739 
11740 	/* Switch the pointer over so the FETD knows what to do */
11741 	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
11742 
11743 	/*
11744 	 * Use a custom move done callback, since we need to send completion
11745 	 * back to the other controller, not to the backend on this side.
11746 	 */
11747 	io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
11748 
11749 	fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
11750 
11751 	fe_datamove(io);
11752 
11753 	return;
11754 
11755 }
11756 
11757 static int
11758 ctl_datamove_remote_dm_read_cb(union ctl_io *io)
11759 {
11760 #if 0
11761 	char str[256];
11762 	char path_str[64];
11763 	struct sbuf sb;
11764 #endif
11765 
11766 	/*
11767 	 * In this case, we had to malloc the memory locally.  Free it.
11768 	 */
11769 	if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
11770 		int i;
11771 		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
11772 			free(io->io_hdr.local_sglist[i].addr, M_CTL);
11773 	}
11774 
11775 #if 0
11776 	scsi_path_string(io, path_str, sizeof(path_str));
11777 	sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
11778 	sbuf_cat(&sb, path_str);
11779 	scsi_command_string(&io->scsiio, NULL, &sb);
11780 	sbuf_printf(&sb, "\n");
11781 	sbuf_cat(&sb, path_str);
11782 	sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
11783 		    io->scsiio.tag_num, io->scsiio.tag_type);
11784 	sbuf_cat(&sb, path_str);
11785 	sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
11786 		    io->io_hdr.flags, io->io_hdr.status);
11787 	sbuf_finish(&sb);
11788 	printk("%s", sbuf_data(&sb));
11789 #endif
11790 
11791 
11792 	/*
11793 	 * The read is done, now we need to send status (good or bad) back
11794 	 * to the other side.
11795 	 */
11796 	ctl_send_datamove_done(io, /*have_lock*/ 0);
11797 
11798 	return (0);
11799 }
11800 
11801 static void
11802 ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
11803 {
11804 	union ctl_io *io;
11805 	void (*fe_datamove)(union ctl_io *io);
11806 
11807 	io = rq->context;
11808 
11809 	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
11810 		printf("%s: ISC DMA read failed with error %d", __func__,
11811 		       rq->ret);
11812 		ctl_set_internal_failure(&io->scsiio,
11813 					 /*sks_valid*/ 1,
11814 					 /*retry_count*/ rq->ret);
11815 	}
11816 
11817 	ctl_dt_req_free(rq);
11818 
11819 	/* Switch the pointer over so the FETD knows what to do */
11820 	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
11821 
11822 	/*
11823 	 * Use a custom move done callback, since we need to send completion
11824 	 * back to the other controller, not to the backend on this side.
11825 	 */
11826 	io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
11827 
11828 	/* XXX KDM add checks like the ones in ctl_datamove? */
11829 
11830 	fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
11831 
11832 	fe_datamove(io);
11833 }
11834 
11835 static int
11836 ctl_datamove_remote_sgl_setup(union ctl_io *io)
11837 {
11838 	struct ctl_sg_entry *local_sglist, *remote_sglist;
11839 	struct ctl_sg_entry *local_dma_sglist, *remote_dma_sglist;
11840 	struct ctl_softc *softc;
11841 	int retval;
11842 	int i;
11843 
11844 	retval = 0;
11845 	softc = control_softc;
11846 
11847 	local_sglist = io->io_hdr.local_sglist;
11848 	local_dma_sglist = io->io_hdr.local_dma_sglist;
11849 	remote_sglist = io->io_hdr.remote_sglist;
11850 	remote_dma_sglist = io->io_hdr.remote_dma_sglist;
11851 
11852 	if (io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) {
11853 		for (i = 0; i < io->scsiio.kern_sg_entries; i++) {
11854 			local_sglist[i].len = remote_sglist[i].len;
11855 
11856 			/*
11857 			 * XXX Detect the situation where the RS-level I/O
11858 			 * redirector on the other side has already read the
11859 			 * data off of the AOR RS on this side, and
11860 			 * transferred it to remote (mirror) memory on the
11861 			 * other side.  Since we already have the data in
11862 			 * memory here, we just need to use it.
11863 			 *
11864 			 * XXX KDM this can probably be removed once we
11865 			 * get the cache device code in and take the
11866 			 * current AOR implementation out.
11867 			 */
11868 #ifdef NEEDTOPORT
11869 			if ((remote_sglist[i].addr >=
11870 			     (void *)vtophys(softc->mirr->addr))
11871 			 && (remote_sglist[i].addr <
11872 			     ((void *)vtophys(softc->mirr->addr) +
11873 			     CacheMirrorOffset))) {
11874 				local_sglist[i].addr = remote_sglist[i].addr -
11875 					CacheMirrorOffset;
11876 				if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
11877 				     CTL_FLAG_DATA_IN)
11878 					io->io_hdr.flags |= CTL_FLAG_REDIR_DONE;
11879 			} else {
11880 				local_sglist[i].addr = remote_sglist[i].addr +
11881 					CacheMirrorOffset;
11882 			}
11883 #endif
11884 #if 0
11885 			printf("%s: local %p, remote %p, len %d\n",
11886 			       __func__, local_sglist[i].addr,
11887 			       remote_sglist[i].addr, local_sglist[i].len);
11888 #endif
11889 		}
11890 	} else {
11891 		uint32_t len_to_go;
11892 
11893 		/*
11894 		 * In this case, we don't have automatically allocated
11895 		 * memory for this I/O on this controller.  This typically
11896 		 * happens with internal CTL I/O -- e.g. inquiry, mode
11897 		 * sense, etc.  Anything coming from RAIDCore will have
11898 		 * a mirror area available.
11899 		 */
11900 		len_to_go = io->scsiio.kern_data_len;
11901 
11902 		/*
11903 		 * Clear the no datasync flag, we have to use malloced
11904 		 * buffers.
11905 		 */
11906 		io->io_hdr.flags &= ~CTL_FLAG_NO_DATASYNC;
11907 
11908 		/*
11909 		 * The difficult thing here is that the size of the various
11910 		 * S/G segments may be different than the size from the
11911 		 * remote controller.  That'll make it harder when DMAing
11912 		 * the data back to the other side.
11913 		 */
11914 		for (i = 0; (i < sizeof(io->io_hdr.remote_sglist) /
11915 		     sizeof(io->io_hdr.remote_sglist[0])) &&
11916 		     (len_to_go > 0); i++) {
11917 			local_sglist[i].len = ctl_min(len_to_go, 131072);
11918 			CTL_SIZE_8B(local_dma_sglist[i].len,
11919 				    local_sglist[i].len);
11920 			local_sglist[i].addr =
11921 				malloc(local_dma_sglist[i].len, M_CTL,M_WAITOK);
11922 
11923 			local_dma_sglist[i].addr = local_sglist[i].addr;
11924 
11925 			if (local_sglist[i].addr == NULL) {
11926 				int j;
11927 
11928 				printf("malloc failed for %zd bytes!",
11929 				       local_dma_sglist[i].len);
11930 				for (j = 0; j < i; j++) {
11931 					free(local_sglist[j].addr, M_CTL);
11932 				}
11933 				ctl_set_internal_failure(&io->scsiio,
11934 							 /*sks_valid*/ 1,
11935 							 /*retry_count*/ 4857);
11936 				retval = 1;
11937 				goto bailout_error;
11938 
11939 			}
11940 			/* XXX KDM do we need a sync here? */
11941 
11942 			len_to_go -= local_sglist[i].len;
11943 		}
11944 		/*
11945 		 * Reset the number of S/G entries accordingly.  The
11946 		 * original number of S/G entries is available in
11947 		 * rem_sg_entries.
11948 		 */
11949 		io->scsiio.kern_sg_entries = i;
11950 
11951 #if 0
11952 		printf("%s: kern_sg_entries = %d\n", __func__,
11953 		       io->scsiio.kern_sg_entries);
11954 		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
11955 			printf("%s: sg[%d] = %p, %d (DMA: %d)\n", __func__, i,
11956 			       local_sglist[i].addr, local_sglist[i].len,
11957 			       local_dma_sglist[i].len);
11958 #endif
11959 	}
11960 
11961 
11962 	return (retval);
11963 
11964 bailout_error:
11965 
11966 	ctl_send_datamove_done(io, /*have_lock*/ 0);
11967 
11968 	return (retval);
11969 }
11970 
11971 static int
11972 ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
11973 			 ctl_ha_dt_cb callback)
11974 {
11975 	struct ctl_ha_dt_req *rq;
11976 	struct ctl_sg_entry *remote_sglist, *local_sglist;
11977 	struct ctl_sg_entry *remote_dma_sglist, *local_dma_sglist;
11978 	uint32_t local_used, remote_used, total_used;
11979 	int retval;
11980 	int i, j;
11981 
11982 	retval = 0;
11983 
11984 	rq = ctl_dt_req_alloc();
11985 
11986 	/*
11987 	 * If we failed to allocate the request, and if the DMA didn't fail
11988 	 * anyway, set busy status.  This is just a resource allocation
11989 	 * failure.
11990 	 */
11991 	if ((rq == NULL)
11992 	 && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE))
11993 		ctl_set_busy(&io->scsiio);
11994 
11995 	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE) {
11996 
11997 		if (rq != NULL)
11998 			ctl_dt_req_free(rq);
11999 
12000 		/*
12001 		 * The data move failed.  We need to return status back
12002 		 * to the other controller.  No point in trying to DMA
12003 		 * data to the remote controller.
12004 		 */
12005 
12006 		ctl_send_datamove_done(io, /*have_lock*/ 0);
12007 
12008 		retval = 1;
12009 
12010 		goto bailout;
12011 	}
12012 
12013 	local_sglist = io->io_hdr.local_sglist;
12014 	local_dma_sglist = io->io_hdr.local_dma_sglist;
12015 	remote_sglist = io->io_hdr.remote_sglist;
12016 	remote_dma_sglist = io->io_hdr.remote_dma_sglist;
12017 	local_used = 0;
12018 	remote_used = 0;
12019 	total_used = 0;
12020 
12021 	if (io->io_hdr.flags & CTL_FLAG_REDIR_DONE) {
12022 		rq->ret = CTL_HA_STATUS_SUCCESS;
12023 		rq->context = io;
12024 		callback(rq);
12025 		goto bailout;
12026 	}
12027 
12028 	/*
12029 	 * Pull/push the data over the wire from/to the other controller.
12030 	 * This takes into account the possibility that the local and
12031 	 * remote sglists may not be identical in terms of the size of
12032 	 * the elements and the number of elements.
12033 	 *
12034 	 * One fundamental assumption here is that the length allocated for
12035 	 * both the local and remote sglists is identical.  Otherwise, we've
12036 	 * essentially got a coding error of some sort.
12037 	 */
12038 	for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
12039 		int isc_ret;
12040 		uint32_t cur_len, dma_length;
12041 		uint8_t *tmp_ptr;
12042 
12043 		rq->id = CTL_HA_DATA_CTL;
12044 		rq->command = command;
12045 		rq->context = io;
12046 
12047 		/*
12048 		 * Both pointers should be aligned.  But it is possible
12049 		 * that the allocation length is not.  They should both
12050 		 * also have enough slack left over at the end, though,
12051 		 * to round up to the next 8 byte boundary.
12052 		 */
12053 		cur_len = ctl_min(local_sglist[i].len - local_used,
12054 				  remote_sglist[j].len - remote_used);
12055 
12056 		/*
12057 		 * In this case, we have a size issue and need to decrease
12058 		 * the size, except in the case where we actually have less
12059 		 * than 8 bytes left.  In that case, we need to increase
12060 		 * the DMA length to get the last bit.
12061 		 */
12062 		if ((cur_len & 0x7) != 0) {
12063 			if (cur_len > 0x7) {
12064 				cur_len = cur_len - (cur_len & 0x7);
12065 				dma_length = cur_len;
12066 			} else {
12067 				CTL_SIZE_8B(dma_length, cur_len);
12068 			}
12069 
12070 		} else
12071 			dma_length = cur_len;
12072 
12073 		/*
12074 		 * If we had to allocate memory for this I/O, instead of using
12075 		 * the non-cached mirror memory, we'll need to flush the cache
12076 		 * before trying to DMA to the other controller.
12077 		 *
12078 		 * We could end up doing this multiple times for the same
12079 		 * segment if we have a larger local segment than remote
12080 		 * segment.  That shouldn't be an issue.
12081 		 */
12082 		if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12083 			/*
12084 			 * XXX KDM use bus_dmamap_sync() here.
12085 			 */
12086 		}
12087 
12088 		rq->size = dma_length;
12089 
12090 		tmp_ptr = (uint8_t *)local_sglist[i].addr;
12091 		tmp_ptr += local_used;
12092 
12093 		/* Use physical addresses when talking to ISC hardware */
12094 		if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
12095 			/* XXX KDM use busdma */
12096 #if 0
12097 			rq->local = vtophys(tmp_ptr);
12098 #endif
12099 		} else
12100 			rq->local = tmp_ptr;
12101 
12102 		tmp_ptr = (uint8_t *)remote_sglist[j].addr;
12103 		tmp_ptr += remote_used;
12104 		rq->remote = tmp_ptr;
12105 
12106 		rq->callback = NULL;
12107 
12108 		local_used += cur_len;
12109 		if (local_used >= local_sglist[i].len) {
12110 			i++;
12111 			local_used = 0;
12112 		}
12113 
12114 		remote_used += cur_len;
12115 		if (remote_used >= remote_sglist[j].len) {
12116 			j++;
12117 			remote_used = 0;
12118 		}
12119 		total_used += cur_len;
12120 
12121 		if (total_used >= io->scsiio.kern_data_len)
12122 			rq->callback = callback;
12123 
12124 		if ((rq->size & 0x7) != 0) {
12125 			printf("%s: warning: size %d is not on 8b boundary\n",
12126 			       __func__, rq->size);
12127 		}
12128 		if (((uintptr_t)rq->local & 0x7) != 0) {
12129 			printf("%s: warning: local %p not on 8b boundary\n",
12130 			       __func__, rq->local);
12131 		}
12132 		if (((uintptr_t)rq->remote & 0x7) != 0) {
12133 			printf("%s: warning: remote %p not on 8b boundary\n",
12134 			       __func__, rq->local);
12135 		}
12136 #if 0
12137 		printf("%s: %s: local %#x remote %#x size %d\n", __func__,
12138 		       (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
12139 		       rq->local, rq->remote, rq->size);
12140 #endif
12141 
12142 		isc_ret = ctl_dt_single(rq);
12143 		if (isc_ret == CTL_HA_STATUS_WAIT)
12144 			continue;
12145 
12146 		if (isc_ret == CTL_HA_STATUS_DISCONNECT) {
12147 			rq->ret = CTL_HA_STATUS_SUCCESS;
12148 		} else {
12149 			rq->ret = isc_ret;
12150 		}
12151 		callback(rq);
12152 		goto bailout;
12153 	}
12154 
12155 bailout:
12156 	return (retval);
12157 
12158 }
12159 
12160 static void
12161 ctl_datamove_remote_read(union ctl_io *io)
12162 {
12163 	int retval;
12164 	int i;
12165 
12166 	/*
12167 	 * This will send an error to the other controller in the case of a
12168 	 * failure.
12169 	 */
12170 	retval = ctl_datamove_remote_sgl_setup(io);
12171 	if (retval != 0)
12172 		return;
12173 
12174 	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
12175 					  ctl_datamove_remote_read_cb);
12176 	if ((retval != 0)
12177 	 && ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0)) {
12178 		/*
12179 		 * Make sure we free memory if there was an error..  The
12180 		 * ctl_datamove_remote_xfer() function will send the
12181 		 * datamove done message, or call the callback with an
12182 		 * error if there is a problem.
12183 		 */
12184 		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12185 			free(io->io_hdr.local_sglist[i].addr, M_CTL);
12186 	}
12187 
12188 	return;
12189 }
12190 
12191 /*
12192  * Process a datamove request from the other controller.  This is used for
12193  * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
12194  * first.  Once that is complete, the data gets DMAed into the remote
12195  * controller's memory.  For reads, we DMA from the remote controller's
12196  * memory into our memory first, and then move it out to the FETD.
12197  */
12198 static void
12199 ctl_datamove_remote(union ctl_io *io)
12200 {
12201 	struct ctl_softc *softc;
12202 
12203 	softc = control_softc;
12204 
12205 	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
12206 
12207 	/*
12208 	 * Note that we look for an aborted I/O here, but don't do some of
12209 	 * the other checks that ctl_datamove() normally does.  We don't
12210 	 * need to run the task queue, because this I/O is on the ISC
12211 	 * queue, which is executed by the work thread after the task queue.
12212 	 * We don't need to run the datamove delay code, since that should
12213 	 * have been done if need be on the other controller.
12214 	 */
12215 	mtx_lock(&softc->ctl_lock);
12216 
12217 	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12218 
12219 		printf("%s: tag 0x%04x on (%d:%d:%d:%d) aborted\n", __func__,
12220 		       io->scsiio.tag_num, io->io_hdr.nexus.initid.id,
12221 		       io->io_hdr.nexus.targ_port,
12222 		       io->io_hdr.nexus.targ_target.id,
12223 		       io->io_hdr.nexus.targ_lun);
12224 		io->io_hdr.status = CTL_CMD_ABORTED;
12225 		io->io_hdr.port_status = 31338;
12226 
12227 		mtx_unlock(&softc->ctl_lock);
12228 
12229 		ctl_send_datamove_done(io, /*have_lock*/ 0);
12230 
12231 		return;
12232 	}
12233 
12234 	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT) {
12235 		mtx_unlock(&softc->ctl_lock);
12236 		ctl_datamove_remote_write(io);
12237 	} else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN){
12238 		mtx_unlock(&softc->ctl_lock);
12239 		ctl_datamove_remote_read(io);
12240 	} else {
12241 		union ctl_ha_msg msg;
12242 		struct scsi_sense_data *sense;
12243 		uint8_t sks[3];
12244 		int retry_count;
12245 
12246 		memset(&msg, 0, sizeof(msg));
12247 
12248 		msg.hdr.msg_type = CTL_MSG_BAD_JUJU;
12249 		msg.hdr.status = CTL_SCSI_ERROR;
12250 		msg.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
12251 
12252 		retry_count = 4243;
12253 
12254 		sense = &msg.scsi.sense_data;
12255 		sks[0] = SSD_SCS_VALID;
12256 		sks[1] = (retry_count >> 8) & 0xff;
12257 		sks[2] = retry_count & 0xff;
12258 
12259 		/* "Internal target failure" */
12260 		scsi_set_sense_data(sense,
12261 				    /*sense_format*/ SSD_TYPE_NONE,
12262 				    /*current_error*/ 1,
12263 				    /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
12264 				    /*asc*/ 0x44,
12265 				    /*ascq*/ 0x00,
12266 				    /*type*/ SSD_ELEM_SKS,
12267 				    /*size*/ sizeof(sks),
12268 				    /*data*/ sks,
12269 				    SSD_ELEM_NONE);
12270 
12271 		io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12272 		if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12273 			ctl_failover_io(io, /*have_lock*/ 1);
12274 			mtx_unlock(&softc->ctl_lock);
12275 			return;
12276 		}
12277 
12278 		mtx_unlock(&softc->ctl_lock);
12279 
12280 		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0) >
12281 		    CTL_HA_STATUS_SUCCESS) {
12282 			/* XXX KDM what to do if this fails? */
12283 		}
12284 		return;
12285 	}
12286 
12287 }
12288 
12289 static int
12290 ctl_process_done(union ctl_io *io, int have_lock)
12291 {
12292 	struct ctl_lun *lun;
12293 	struct ctl_softc *ctl_softc;
12294 	void (*fe_done)(union ctl_io *io);
12295 	uint32_t targ_port = ctl_port_idx(io->io_hdr.nexus.targ_port);
12296 
12297 	CTL_DEBUG_PRINT(("ctl_process_done\n"));
12298 
12299 	fe_done =
12300 	    control_softc->ctl_ports[targ_port]->fe_done;
12301 
12302 #ifdef CTL_TIME_IO
12303 	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12304 		char str[256];
12305 		char path_str[64];
12306 		struct sbuf sb;
12307 
12308 		ctl_scsi_path_string(io, path_str, sizeof(path_str));
12309 		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12310 
12311 		sbuf_cat(&sb, path_str);
12312 		switch (io->io_hdr.io_type) {
12313 		case CTL_IO_SCSI:
12314 			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12315 			sbuf_printf(&sb, "\n");
12316 			sbuf_cat(&sb, path_str);
12317 			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12318 				    io->scsiio.tag_num, io->scsiio.tag_type);
12319 			break;
12320 		case CTL_IO_TASK:
12321 			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12322 				    "Tag Type: %d\n", io->taskio.task_action,
12323 				    io->taskio.tag_num, io->taskio.tag_type);
12324 			break;
12325 		default:
12326 			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12327 			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12328 			break;
12329 		}
12330 		sbuf_cat(&sb, path_str);
12331 		sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
12332 			    (intmax_t)time_uptime - io->io_hdr.start_time);
12333 		sbuf_finish(&sb);
12334 		printf("%s", sbuf_data(&sb));
12335 	}
12336 #endif /* CTL_TIME_IO */
12337 
12338 	switch (io->io_hdr.io_type) {
12339 	case CTL_IO_SCSI:
12340 		break;
12341 	case CTL_IO_TASK:
12342 		ctl_io_error_print(io, NULL);
12343 		if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
12344 			ctl_free_io_internal(io, /*have_lock*/ 0);
12345 		else
12346 			fe_done(io);
12347 		return (CTL_RETVAL_COMPLETE);
12348 		break;
12349 	default:
12350 		printf("ctl_process_done: invalid io type %d\n",
12351 		       io->io_hdr.io_type);
12352 		panic("ctl_process_done: invalid io type %d\n",
12353 		      io->io_hdr.io_type);
12354 		break; /* NOTREACHED */
12355 	}
12356 
12357 	lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12358 	if (lun == NULL) {
12359 		CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
12360 				 io->io_hdr.nexus.targ_lun));
12361 		fe_done(io);
12362 		goto bailout;
12363 	}
12364 	ctl_softc = lun->ctl_softc;
12365 
12366 	/*
12367 	 * Remove this from the OOA queue.
12368 	 */
12369 	if (have_lock == 0)
12370 		mtx_lock(&ctl_softc->ctl_lock);
12371 
12372 	/*
12373 	 * Check to see if we have any errors to inject here.  We only
12374 	 * inject errors for commands that don't already have errors set.
12375 	 */
12376 	if ((STAILQ_FIRST(&lun->error_list) != NULL)
12377 	 && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS))
12378 		ctl_inject_error(lun, io);
12379 
12380 	/*
12381 	 * XXX KDM how do we treat commands that aren't completed
12382 	 * successfully?
12383 	 *
12384 	 * XXX KDM should we also track I/O latency?
12385 	 */
12386 	if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS) {
12387 		uint32_t blocksize;
12388 #ifdef CTL_TIME_IO
12389 		struct bintime cur_bt;
12390 #endif
12391 
12392 		if ((lun->be_lun != NULL)
12393 		 && (lun->be_lun->blocksize != 0))
12394 			blocksize = lun->be_lun->blocksize;
12395 		else
12396 			blocksize = 512;
12397 
12398 		switch (io->io_hdr.io_type) {
12399 		case CTL_IO_SCSI: {
12400 			int isread;
12401 			struct ctl_lba_len lbalen;
12402 
12403 			isread = 0;
12404 			switch (io->scsiio.cdb[0]) {
12405 			case READ_6:
12406 			case READ_10:
12407 			case READ_12:
12408 			case READ_16:
12409 				isread = 1;
12410 				/* FALLTHROUGH */
12411 			case WRITE_6:
12412 			case WRITE_10:
12413 			case WRITE_12:
12414 			case WRITE_16:
12415 			case WRITE_VERIFY_10:
12416 			case WRITE_VERIFY_12:
12417 			case WRITE_VERIFY_16:
12418 				memcpy(&lbalen, io->io_hdr.ctl_private[
12419 				       CTL_PRIV_LBA_LEN].bytes, sizeof(lbalen));
12420 
12421 				if (isread) {
12422 					lun->stats.ports[targ_port].bytes[CTL_STATS_READ] +=
12423 						lbalen.len * blocksize;
12424 					lun->stats.ports[targ_port].operations[CTL_STATS_READ]++;
12425 
12426 #ifdef CTL_TIME_IO
12427 					bintime_add(
12428 					   &lun->stats.ports[targ_port].dma_time[CTL_STATS_READ],
12429 					   &io->io_hdr.dma_bt);
12430 					lun->stats.ports[targ_port].num_dmas[CTL_STATS_READ] +=
12431 						io->io_hdr.num_dmas;
12432 					getbintime(&cur_bt);
12433 					bintime_sub(&cur_bt,
12434 						    &io->io_hdr.start_bt);
12435 
12436 					bintime_add(
12437 					    &lun->stats.ports[targ_port].time[CTL_STATS_READ],
12438 					    &cur_bt);
12439 
12440 #if 0
12441 					cs_prof_gettime(&cur_ticks);
12442 					lun->stats.time[CTL_STATS_READ] +=
12443 						cur_ticks -
12444 						io->io_hdr.start_ticks;
12445 #endif
12446 #if 0
12447 					lun->stats.time[CTL_STATS_READ] +=
12448 						jiffies - io->io_hdr.start_time;
12449 #endif
12450 #endif /* CTL_TIME_IO */
12451 				} else {
12452 					lun->stats.ports[targ_port].bytes[CTL_STATS_WRITE] +=
12453 						lbalen.len * blocksize;
12454 					lun->stats.ports[targ_port].operations[
12455 						CTL_STATS_WRITE]++;
12456 
12457 #ifdef CTL_TIME_IO
12458 					bintime_add(
12459 					  &lun->stats.ports[targ_port].dma_time[CTL_STATS_WRITE],
12460 					  &io->io_hdr.dma_bt);
12461 					lun->stats.ports[targ_port].num_dmas[CTL_STATS_WRITE] +=
12462 						io->io_hdr.num_dmas;
12463 					getbintime(&cur_bt);
12464 					bintime_sub(&cur_bt,
12465 						    &io->io_hdr.start_bt);
12466 
12467 					bintime_add(
12468 					    &lun->stats.ports[targ_port].time[CTL_STATS_WRITE],
12469 					    &cur_bt);
12470 #if 0
12471 					cs_prof_gettime(&cur_ticks);
12472 					lun->stats.ports[targ_port].time[CTL_STATS_WRITE] +=
12473 						cur_ticks -
12474 						io->io_hdr.start_ticks;
12475 					lun->stats.ports[targ_port].time[CTL_STATS_WRITE] +=
12476 						jiffies - io->io_hdr.start_time;
12477 #endif
12478 #endif /* CTL_TIME_IO */
12479 				}
12480 				break;
12481 			default:
12482 				lun->stats.ports[targ_port].operations[CTL_STATS_NO_IO]++;
12483 
12484 #ifdef CTL_TIME_IO
12485 				bintime_add(
12486 				  &lun->stats.ports[targ_port].dma_time[CTL_STATS_NO_IO],
12487 				  &io->io_hdr.dma_bt);
12488 				lun->stats.ports[targ_port].num_dmas[CTL_STATS_NO_IO] +=
12489 					io->io_hdr.num_dmas;
12490 				getbintime(&cur_bt);
12491 				bintime_sub(&cur_bt, &io->io_hdr.start_bt);
12492 
12493 				bintime_add(&lun->stats.ports[targ_port].time[CTL_STATS_NO_IO],
12494 					    &cur_bt);
12495 
12496 #if 0
12497 				cs_prof_gettime(&cur_ticks);
12498 				lun->stats.ports[targ_port].time[CTL_STATS_NO_IO] +=
12499 					cur_ticks -
12500 					io->io_hdr.start_ticks;
12501 				lun->stats.ports[targ_port].time[CTL_STATS_NO_IO] +=
12502 					jiffies - io->io_hdr.start_time;
12503 #endif
12504 #endif /* CTL_TIME_IO */
12505 				break;
12506 			}
12507 			break;
12508 		}
12509 		default:
12510 			break;
12511 		}
12512 	}
12513 
12514 	TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
12515 
12516 	/*
12517 	 * Run through the blocked queue on this LUN and see if anything
12518 	 * has become unblocked, now that this transaction is done.
12519 	 */
12520 	ctl_check_blocked(lun);
12521 
12522 	/*
12523 	 * If the LUN has been invalidated, free it if there is nothing
12524 	 * left on its OOA queue.
12525 	 */
12526 	if ((lun->flags & CTL_LUN_INVALID)
12527 	 && (TAILQ_FIRST(&lun->ooa_queue) == NULL))
12528 		ctl_free_lun(lun);
12529 
12530 	/*
12531 	 * If this command has been aborted, make sure we set the status
12532 	 * properly.  The FETD is responsible for freeing the I/O and doing
12533 	 * whatever it needs to do to clean up its state.
12534 	 */
12535 	if (io->io_hdr.flags & CTL_FLAG_ABORT)
12536 		io->io_hdr.status = CTL_CMD_ABORTED;
12537 
12538 	/*
12539 	 * We print out status for every task management command.  For SCSI
12540 	 * commands, we filter out any unit attention errors; they happen
12541 	 * on every boot, and would clutter up the log.  Note:  task
12542 	 * management commands aren't printed here, they are printed above,
12543 	 * since they should never even make it down here.
12544 	 */
12545 	switch (io->io_hdr.io_type) {
12546 	case CTL_IO_SCSI: {
12547 		int error_code, sense_key, asc, ascq;
12548 
12549 		sense_key = 0;
12550 
12551 		if (((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SCSI_ERROR)
12552 		 && (io->scsiio.scsi_status == SCSI_STATUS_CHECK_COND)) {
12553 			/*
12554 			 * Since this is just for printing, no need to
12555 			 * show errors here.
12556 			 */
12557 			scsi_extract_sense_len(&io->scsiio.sense_data,
12558 					       io->scsiio.sense_len,
12559 					       &error_code,
12560 					       &sense_key,
12561 					       &asc,
12562 					       &ascq,
12563 					       /*show_errors*/ 0);
12564 		}
12565 
12566 		if (((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)
12567 		 && (((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SCSI_ERROR)
12568 		  || (io->scsiio.scsi_status != SCSI_STATUS_CHECK_COND)
12569 		  || (sense_key != SSD_KEY_UNIT_ATTENTION))) {
12570 
12571 			if ((time_uptime - ctl_softc->last_print_jiffies) <= 0){
12572 				ctl_softc->skipped_prints++;
12573 				if (have_lock == 0)
12574 					mtx_unlock(&ctl_softc->ctl_lock);
12575 			} else {
12576 				uint32_t skipped_prints;
12577 
12578 				skipped_prints = ctl_softc->skipped_prints;
12579 
12580 				ctl_softc->skipped_prints = 0;
12581 				ctl_softc->last_print_jiffies = time_uptime;
12582 
12583 				if (have_lock == 0)
12584 					mtx_unlock(&ctl_softc->ctl_lock);
12585 				if (skipped_prints > 0) {
12586 #ifdef NEEDTOPORT
12587 					csevent_log(CSC_CTL | CSC_SHELF_SW |
12588 					    CTL_ERROR_REPORT,
12589 					    csevent_LogType_Trace,
12590 					    csevent_Severity_Information,
12591 					    csevent_AlertLevel_Green,
12592 					    csevent_FRU_Firmware,
12593 					    csevent_FRU_Unknown,
12594 					    "High CTL error volume, %d prints "
12595 					    "skipped", skipped_prints);
12596 #endif
12597 				}
12598 				ctl_io_error_print(io, NULL);
12599 			}
12600 		} else {
12601 			if (have_lock == 0)
12602 				mtx_unlock(&ctl_softc->ctl_lock);
12603 		}
12604 		break;
12605 	}
12606 	case CTL_IO_TASK:
12607 		if (have_lock == 0)
12608 			mtx_unlock(&ctl_softc->ctl_lock);
12609 		ctl_io_error_print(io, NULL);
12610 		break;
12611 	default:
12612 		if (have_lock == 0)
12613 			mtx_unlock(&ctl_softc->ctl_lock);
12614 		break;
12615 	}
12616 
12617 	/*
12618 	 * Tell the FETD or the other shelf controller we're done with this
12619 	 * command.  Note that only SCSI commands get to this point.  Task
12620 	 * management commands are completed above.
12621 	 *
12622 	 * We only send status to the other controller if we're in XFER
12623 	 * mode.  In SER_ONLY mode, the I/O is done on the controller that
12624 	 * received the I/O (from CTL's perspective), and so the status is
12625 	 * generated there.
12626 	 *
12627 	 * XXX KDM if we hold the lock here, we could cause a deadlock
12628 	 * if the frontend comes back in in this context to queue
12629 	 * something.
12630 	 */
12631 	if ((ctl_softc->ha_mode == CTL_HA_MODE_XFER)
12632 	 && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12633 		union ctl_ha_msg msg;
12634 
12635 		memset(&msg, 0, sizeof(msg));
12636 		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
12637 		msg.hdr.original_sc = io->io_hdr.original_sc;
12638 		msg.hdr.nexus = io->io_hdr.nexus;
12639 		msg.hdr.status = io->io_hdr.status;
12640 		msg.scsi.scsi_status = io->scsiio.scsi_status;
12641 		msg.scsi.tag_num = io->scsiio.tag_num;
12642 		msg.scsi.tag_type = io->scsiio.tag_type;
12643 		msg.scsi.sense_len = io->scsiio.sense_len;
12644 		msg.scsi.sense_residual = io->scsiio.sense_residual;
12645 		msg.scsi.residual = io->scsiio.residual;
12646 		memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12647 		       sizeof(io->scsiio.sense_data));
12648 		/*
12649 		 * We copy this whether or not this is an I/O-related
12650 		 * command.  Otherwise, we'd have to go and check to see
12651 		 * whether it's a read/write command, and it really isn't
12652 		 * worth it.
12653 		 */
12654 		memcpy(&msg.scsi.lbalen,
12655 		       &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
12656 		       sizeof(msg.scsi.lbalen));
12657 
12658 		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12659 				sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
12660 			/* XXX do something here */
12661 		}
12662 
12663 		ctl_free_io_internal(io, /*have_lock*/ 0);
12664 	} else
12665 		fe_done(io);
12666 
12667 bailout:
12668 
12669 	return (CTL_RETVAL_COMPLETE);
12670 }
12671 
12672 /*
12673  * Front end should call this if it doesn't do autosense.  When the request
12674  * sense comes back in from the initiator, we'll dequeue this and send it.
12675  */
12676 int
12677 ctl_queue_sense(union ctl_io *io)
12678 {
12679 	struct ctl_lun *lun;
12680 	struct ctl_softc *ctl_softc;
12681 	uint32_t initidx, targ_lun;
12682 
12683 	ctl_softc = control_softc;
12684 
12685 	CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
12686 
12687 	/*
12688 	 * LUN lookup will likely move to the ctl_work_thread() once we
12689 	 * have our new queueing infrastructure (that doesn't put things on
12690 	 * a per-LUN queue initially).  That is so that we can handle
12691 	 * things like an INQUIRY to a LUN that we don't have enabled.  We
12692 	 * can't deal with that right now.
12693 	 */
12694 	mtx_lock(&ctl_softc->ctl_lock);
12695 
12696 	/*
12697 	 * If we don't have a LUN for this, just toss the sense
12698 	 * information.
12699 	 */
12700 	targ_lun = io->io_hdr.nexus.targ_lun;
12701 	if (io->io_hdr.nexus.lun_map_fn != NULL)
12702 		targ_lun = io->io_hdr.nexus.lun_map_fn(io->io_hdr.nexus.lun_map_arg, targ_lun);
12703 	if ((targ_lun < CTL_MAX_LUNS)
12704 	 && (ctl_softc->ctl_luns[targ_lun] != NULL))
12705 		lun = ctl_softc->ctl_luns[targ_lun];
12706 	else
12707 		goto bailout;
12708 
12709 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
12710 
12711 	/*
12712 	 * Already have CA set for this LUN...toss the sense information.
12713 	 */
12714 	if (ctl_is_set(lun->have_ca, initidx))
12715 		goto bailout;
12716 
12717 	memcpy(&lun->pending_sense[initidx].sense, &io->scsiio.sense_data,
12718 	       ctl_min(sizeof(lun->pending_sense[initidx].sense),
12719 	       sizeof(io->scsiio.sense_data)));
12720 	ctl_set_mask(lun->have_ca, initidx);
12721 
12722 bailout:
12723 	mtx_unlock(&ctl_softc->ctl_lock);
12724 
12725 	ctl_free_io(io);
12726 
12727 	return (CTL_RETVAL_COMPLETE);
12728 }
12729 
12730 /*
12731  * Primary command inlet from frontend ports.  All SCSI and task I/O
12732  * requests must go through this function.
12733  */
12734 int
12735 ctl_queue(union ctl_io *io)
12736 {
12737 	struct ctl_softc *ctl_softc;
12738 
12739 	CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
12740 
12741 	ctl_softc = control_softc;
12742 
12743 #ifdef CTL_TIME_IO
12744 	io->io_hdr.start_time = time_uptime;
12745 	getbintime(&io->io_hdr.start_bt);
12746 #endif /* CTL_TIME_IO */
12747 
12748 	mtx_lock(&ctl_softc->ctl_lock);
12749 
12750 	switch (io->io_hdr.io_type) {
12751 	case CTL_IO_SCSI:
12752 		STAILQ_INSERT_TAIL(&ctl_softc->incoming_queue, &io->io_hdr,
12753 				   links);
12754 		break;
12755 	case CTL_IO_TASK:
12756 		STAILQ_INSERT_TAIL(&ctl_softc->task_queue, &io->io_hdr, links);
12757 		/*
12758 		 * Set the task pending flag.  This is necessary to close a
12759 		 * race condition with the FETD:
12760 		 *
12761 		 * - FETD submits a task management command, like an abort.
12762 		 * - Back end calls fe_datamove() to move the data for the
12763 		 *   aborted command.  The FETD can't really accept it, but
12764 		 *   if it did, it would end up transmitting data for a
12765 		 *   command that the initiator told us to abort.
12766 		 *
12767 		 * We close the race condition by setting the flag here,
12768 		 * and checking it in ctl_datamove(), before calling the
12769 		 * FETD's fe_datamove routine.  If we've got a task
12770 		 * pending, we run the task queue and then check to see
12771 		 * whether our particular I/O has been aborted.
12772 		 */
12773 		ctl_softc->flags |= CTL_FLAG_TASK_PENDING;
12774 		break;
12775 	default:
12776 		mtx_unlock(&ctl_softc->ctl_lock);
12777 		printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
12778 		return (-EINVAL);
12779 		break; /* NOTREACHED */
12780 	}
12781 	mtx_unlock(&ctl_softc->ctl_lock);
12782 
12783 	ctl_wakeup_thread();
12784 
12785 	return (CTL_RETVAL_COMPLETE);
12786 }
12787 
12788 #ifdef CTL_IO_DELAY
12789 static void
12790 ctl_done_timer_wakeup(void *arg)
12791 {
12792 	union ctl_io *io;
12793 
12794 	io = (union ctl_io *)arg;
12795 	ctl_done_lock(io, /*have_lock*/ 0);
12796 }
12797 #endif /* CTL_IO_DELAY */
12798 
12799 void
12800 ctl_done_lock(union ctl_io *io, int have_lock)
12801 {
12802 	struct ctl_softc *ctl_softc;
12803 #ifndef CTL_DONE_THREAD
12804 	union ctl_io *xio;
12805 #endif /* !CTL_DONE_THREAD */
12806 
12807 	ctl_softc = control_softc;
12808 
12809 	if (have_lock == 0)
12810 		mtx_lock(&ctl_softc->ctl_lock);
12811 
12812 	/*
12813 	 * Enable this to catch duplicate completion issues.
12814 	 */
12815 #if 0
12816 	if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
12817 		printf("%s: type %d msg %d cdb %x iptl: "
12818 		       "%d:%d:%d:%d tag 0x%04x "
12819 		       "flag %#x status %x\n",
12820 			__func__,
12821 			io->io_hdr.io_type,
12822 			io->io_hdr.msg_type,
12823 			io->scsiio.cdb[0],
12824 			io->io_hdr.nexus.initid.id,
12825 			io->io_hdr.nexus.targ_port,
12826 			io->io_hdr.nexus.targ_target.id,
12827 			io->io_hdr.nexus.targ_lun,
12828 			(io->io_hdr.io_type ==
12829 			CTL_IO_TASK) ?
12830 			io->taskio.tag_num :
12831 			io->scsiio.tag_num,
12832 		        io->io_hdr.flags,
12833 			io->io_hdr.status);
12834 	} else
12835 		io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
12836 #endif
12837 
12838 	/*
12839 	 * This is an internal copy of an I/O, and should not go through
12840 	 * the normal done processing logic.
12841 	 */
12842 	if (io->io_hdr.flags & CTL_FLAG_INT_COPY) {
12843 		if (have_lock == 0)
12844 			mtx_unlock(&ctl_softc->ctl_lock);
12845 		return;
12846 	}
12847 
12848 	/*
12849 	 * We need to send a msg to the serializing shelf to finish the IO
12850 	 * as well.  We don't send a finish message to the other shelf if
12851 	 * this is a task management command.  Task management commands
12852 	 * aren't serialized in the OOA queue, but rather just executed on
12853 	 * both shelf controllers for commands that originated on that
12854 	 * controller.
12855 	 */
12856 	if ((io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)
12857 	 && (io->io_hdr.io_type != CTL_IO_TASK)) {
12858 		union ctl_ha_msg msg_io;
12859 
12860 		msg_io.hdr.msg_type = CTL_MSG_FINISH_IO;
12861 		msg_io.hdr.serializing_sc = io->io_hdr.serializing_sc;
12862 		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_io,
12863 		    sizeof(msg_io), 0 ) != CTL_HA_STATUS_SUCCESS) {
12864 		}
12865 		/* continue on to finish IO */
12866 	}
12867 #ifdef CTL_IO_DELAY
12868 	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12869 		struct ctl_lun *lun;
12870 
12871 		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12872 
12873 		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12874 	} else {
12875 		struct ctl_lun *lun;
12876 
12877 		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12878 
12879 		if ((lun != NULL)
12880 		 && (lun->delay_info.done_delay > 0)) {
12881 			struct callout *callout;
12882 
12883 			callout = (struct callout *)&io->io_hdr.timer_bytes;
12884 			callout_init(callout, /*mpsafe*/ 1);
12885 			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12886 			callout_reset(callout,
12887 				      lun->delay_info.done_delay * hz,
12888 				      ctl_done_timer_wakeup, io);
12889 			if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
12890 				lun->delay_info.done_delay = 0;
12891 			if (have_lock == 0)
12892 				mtx_unlock(&ctl_softc->ctl_lock);
12893 			return;
12894 		}
12895 	}
12896 #endif /* CTL_IO_DELAY */
12897 
12898 	STAILQ_INSERT_TAIL(&ctl_softc->done_queue, &io->io_hdr, links);
12899 
12900 #ifdef CTL_DONE_THREAD
12901 	if (have_lock == 0)
12902 		mtx_unlock(&ctl_softc->ctl_lock);
12903 
12904 	ctl_wakeup_thread();
12905 #else /* CTL_DONE_THREAD */
12906 	for (xio = (union ctl_io *)STAILQ_FIRST(&ctl_softc->done_queue);
12907 	     xio != NULL;
12908 	     xio =(union ctl_io *)STAILQ_FIRST(&ctl_softc->done_queue)) {
12909 
12910 		STAILQ_REMOVE_HEAD(&ctl_softc->done_queue, links);
12911 
12912 		ctl_process_done(xio, /*have_lock*/ 1);
12913 	}
12914 	if (have_lock == 0)
12915 		mtx_unlock(&ctl_softc->ctl_lock);
12916 #endif /* CTL_DONE_THREAD */
12917 }
12918 
12919 void
12920 ctl_done(union ctl_io *io)
12921 {
12922 	ctl_done_lock(io, /*have_lock*/ 0);
12923 }
12924 
12925 int
12926 ctl_isc(struct ctl_scsiio *ctsio)
12927 {
12928 	struct ctl_lun *lun;
12929 	int retval;
12930 
12931 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12932 
12933 	CTL_DEBUG_PRINT(("ctl_isc: command: %02x\n", ctsio->cdb[0]));
12934 
12935 	CTL_DEBUG_PRINT(("ctl_isc: calling data_submit()\n"));
12936 
12937 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
12938 
12939 	return (retval);
12940 }
12941 
12942 
12943 static void
12944 ctl_work_thread(void *arg)
12945 {
12946 	struct ctl_softc *softc;
12947 	union ctl_io *io;
12948 	struct ctl_be_lun *be_lun;
12949 	int retval;
12950 
12951 	CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
12952 
12953 	softc = (struct ctl_softc *)arg;
12954 	if (softc == NULL)
12955 		return;
12956 
12957 	mtx_lock(&softc->ctl_lock);
12958 	for (;;) {
12959 		retval = 0;
12960 
12961 		/*
12962 		 * We handle the queues in this order:
12963 		 * - task management
12964 		 * - ISC
12965 		 * - done queue (to free up resources, unblock other commands)
12966 		 * - RtR queue
12967 		 * - incoming queue
12968 		 *
12969 		 * If those queues are empty, we break out of the loop and
12970 		 * go to sleep.
12971 		 */
12972 		io = (union ctl_io *)STAILQ_FIRST(&softc->task_queue);
12973 		if (io != NULL) {
12974 			ctl_run_task_queue(softc);
12975 			continue;
12976 		}
12977 		io = (union ctl_io *)STAILQ_FIRST(&softc->isc_queue);
12978 		if (io != NULL) {
12979 			STAILQ_REMOVE_HEAD(&softc->isc_queue, links);
12980 			ctl_handle_isc(io);
12981 			continue;
12982 		}
12983 		io = (union ctl_io *)STAILQ_FIRST(&softc->done_queue);
12984 		if (io != NULL) {
12985 			STAILQ_REMOVE_HEAD(&softc->done_queue, links);
12986 			/* clear any blocked commands, call fe_done */
12987 			mtx_unlock(&softc->ctl_lock);
12988 			/*
12989 			 * XXX KDM
12990 			 * Call this without a lock for now.  This will
12991 			 * depend on whether there is any way the FETD can
12992 			 * sleep or deadlock if called with the CTL lock
12993 			 * held.
12994 			 */
12995 			retval = ctl_process_done(io, /*have_lock*/ 0);
12996 			mtx_lock(&softc->ctl_lock);
12997 			continue;
12998 		}
12999 		if (!ctl_pause_rtr) {
13000 			io = (union ctl_io *)STAILQ_FIRST(&softc->rtr_queue);
13001 			if (io != NULL) {
13002 				STAILQ_REMOVE_HEAD(&softc->rtr_queue, links);
13003 				mtx_unlock(&softc->ctl_lock);
13004 				goto execute;
13005 			}
13006 		}
13007 		io = (union ctl_io *)STAILQ_FIRST(&softc->incoming_queue);
13008 		if (io != NULL) {
13009 			STAILQ_REMOVE_HEAD(&softc->incoming_queue, links);
13010 			mtx_unlock(&softc->ctl_lock);
13011 			ctl_scsiio_precheck(softc, &io->scsiio);
13012 			mtx_lock(&softc->ctl_lock);
13013 			continue;
13014 		}
13015 		/*
13016 		 * We might want to move this to a separate thread, so that
13017 		 * configuration requests (in this case LUN creations)
13018 		 * won't impact the I/O path.
13019 		 */
13020 		be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
13021 		if (be_lun != NULL) {
13022 			STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
13023 			mtx_unlock(&softc->ctl_lock);
13024 			ctl_create_lun(be_lun);
13025 			mtx_lock(&softc->ctl_lock);
13026 			continue;
13027 		}
13028 
13029 		/* XXX KDM use the PDROP flag?? */
13030 		/* Sleep until we have something to do. */
13031 		mtx_sleep(softc, &softc->ctl_lock, PRIBIO, "ctl_work", 0);
13032 
13033 		/* Back to the top of the loop to see what woke us up. */
13034 		continue;
13035 
13036 execute:
13037 		retval = ctl_scsiio(&io->scsiio);
13038 		switch (retval) {
13039 		case CTL_RETVAL_COMPLETE:
13040 			break;
13041 		default:
13042 			/*
13043 			 * Probably need to make sure this doesn't happen.
13044 			 */
13045 			break;
13046 		}
13047 		mtx_lock(&softc->ctl_lock);
13048 	}
13049 }
13050 
13051 void
13052 ctl_wakeup_thread()
13053 {
13054 	struct ctl_softc *softc;
13055 
13056 	softc = control_softc;
13057 
13058 	wakeup(softc);
13059 }
13060 
13061 /* Initialization and failover */
13062 
13063 void
13064 ctl_init_isc_msg(void)
13065 {
13066 	printf("CTL: Still calling this thing\n");
13067 }
13068 
13069 /*
13070  * Init component
13071  * 	Initializes component into configuration defined by bootMode
13072  *	(see hasc-sv.c)
13073  *  	returns hasc_Status:
13074  * 		OK
13075  *		ERROR - fatal error
13076  */
13077 static ctl_ha_comp_status
13078 ctl_isc_init(struct ctl_ha_component *c)
13079 {
13080 	ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
13081 
13082 	c->status = ret;
13083 	return ret;
13084 }
13085 
13086 /* Start component
13087  * 	Starts component in state requested. If component starts successfully,
13088  *	it must set its own state to the requestrd state
13089  *	When requested state is HASC_STATE_HA, the component may refine it
13090  * 	by adding _SLAVE or _MASTER flags.
13091  *	Currently allowed state transitions are:
13092  *	UNKNOWN->HA		- initial startup
13093  *	UNKNOWN->SINGLE - initial startup when no parter detected
13094  *	HA->SINGLE		- failover
13095  * returns ctl_ha_comp_status:
13096  * 		OK	- component successfully started in requested state
13097  *		FAILED  - could not start the requested state, failover may
13098  * 			  be possible
13099  *		ERROR	- fatal error detected, no future startup possible
13100  */
13101 static ctl_ha_comp_status
13102 ctl_isc_start(struct ctl_ha_component *c, ctl_ha_state state)
13103 {
13104 	ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
13105 
13106 	printf("%s: go\n", __func__);
13107 
13108 	// UNKNOWN->HA or UNKNOWN->SINGLE (bootstrap)
13109 	if (c->state == CTL_HA_STATE_UNKNOWN ) {
13110 		ctl_is_single = 0;
13111 		if (ctl_ha_msg_create(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
13112 		    != CTL_HA_STATUS_SUCCESS) {
13113 			printf("ctl_isc_start: ctl_ha_msg_create failed.\n");
13114 			ret = CTL_HA_COMP_STATUS_ERROR;
13115 		}
13116 	} else if (CTL_HA_STATE_IS_HA(c->state)
13117 		&& CTL_HA_STATE_IS_SINGLE(state)){
13118 		// HA->SINGLE transition
13119 	        ctl_failover();
13120 		ctl_is_single = 1;
13121 	} else {
13122 		printf("ctl_isc_start:Invalid state transition %X->%X\n",
13123 		       c->state, state);
13124 		ret = CTL_HA_COMP_STATUS_ERROR;
13125 	}
13126 	if (CTL_HA_STATE_IS_SINGLE(state))
13127 		ctl_is_single = 1;
13128 
13129 	c->state = state;
13130 	c->status = ret;
13131 	return ret;
13132 }
13133 
13134 /*
13135  * Quiesce component
13136  * The component must clear any error conditions (set status to OK) and
13137  * prepare itself to another Start call
13138  * returns ctl_ha_comp_status:
13139  * 	OK
13140  *	ERROR
13141  */
13142 static ctl_ha_comp_status
13143 ctl_isc_quiesce(struct ctl_ha_component *c)
13144 {
13145 	int ret = CTL_HA_COMP_STATUS_OK;
13146 
13147 	ctl_pause_rtr = 1;
13148 	c->status = ret;
13149 	return ret;
13150 }
13151 
13152 struct ctl_ha_component ctl_ha_component_ctlisc =
13153 {
13154 	.name = "CTL ISC",
13155 	.state = CTL_HA_STATE_UNKNOWN,
13156 	.init = ctl_isc_init,
13157 	.start = ctl_isc_start,
13158 	.quiesce = ctl_isc_quiesce
13159 };
13160 
13161 /*
13162  *  vim: ts=8
13163  */
13164