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