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