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