xref: /freebsd/sys/cam/ctl/ctl.c (revision 95d45410b5100e07f6f98450bcd841a8945d4726)
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/smp.h>
64 #include <sys/endian.h>
65 #include <sys/sysctl.h>
66 
67 #include <cam/cam.h>
68 #include <cam/scsi/scsi_all.h>
69 #include <cam/scsi/scsi_da.h>
70 #include <cam/ctl/ctl_io.h>
71 #include <cam/ctl/ctl.h>
72 #include <cam/ctl/ctl_frontend.h>
73 #include <cam/ctl/ctl_frontend_internal.h>
74 #include <cam/ctl/ctl_util.h>
75 #include <cam/ctl/ctl_backend.h>
76 #include <cam/ctl/ctl_ioctl.h>
77 #include <cam/ctl/ctl_ha.h>
78 #include <cam/ctl/ctl_private.h>
79 #include <cam/ctl/ctl_debug.h>
80 #include <cam/ctl/ctl_scsi_all.h>
81 #include <cam/ctl/ctl_error.h>
82 
83 struct ctl_softc *control_softc = NULL;
84 
85 /*
86  * Size and alignment macros needed for Copan-specific HA hardware.  These
87  * can go away when the HA code is re-written, and uses busdma for any
88  * hardware.
89  */
90 #define	CTL_ALIGN_8B(target, source, type)				\
91 	if (((uint32_t)source & 0x7) != 0)				\
92 		target = (type)(source + (0x8 - ((uint32_t)source & 0x7)));\
93 	else								\
94 		target = (type)source;
95 
96 #define	CTL_SIZE_8B(target, size)					\
97 	if ((size & 0x7) != 0)						\
98 		target = size + (0x8 - (size & 0x7));			\
99 	else								\
100 		target = size;
101 
102 #define CTL_ALIGN_8B_MARGIN	16
103 
104 /*
105  * Template mode pages.
106  */
107 
108 /*
109  * Note that these are default values only.  The actual values will be
110  * filled in when the user does a mode sense.
111  */
112 static struct copan_power_subpage power_page_default = {
113 	/*page_code*/ PWR_PAGE_CODE | SMPH_SPF,
114 	/*subpage*/ PWR_SUBPAGE_CODE,
115 	/*page_length*/ {(sizeof(struct copan_power_subpage) - 4) & 0xff00,
116 			 (sizeof(struct copan_power_subpage) - 4) & 0x00ff},
117 	/*page_version*/ PWR_VERSION,
118 	/* total_luns */ 26,
119 	/* max_active_luns*/ PWR_DFLT_MAX_LUNS,
120 	/*reserved*/ {0, 0, 0, 0, 0, 0, 0, 0, 0,
121 		      0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
122 		      0, 0, 0, 0, 0, 0}
123 };
124 
125 static struct copan_power_subpage power_page_changeable = {
126 	/*page_code*/ PWR_PAGE_CODE | SMPH_SPF,
127 	/*subpage*/ PWR_SUBPAGE_CODE,
128 	/*page_length*/ {(sizeof(struct copan_power_subpage) - 4) & 0xff00,
129 			 (sizeof(struct copan_power_subpage) - 4) & 0x00ff},
130 	/*page_version*/ 0,
131 	/* total_luns */ 0,
132 	/* max_active_luns*/ 0,
133 	/*reserved*/ {0, 0, 0, 0, 0, 0, 0, 0, 0,
134 		      0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
135 		      0, 0, 0, 0, 0, 0}
136 };
137 
138 static struct copan_aps_subpage aps_page_default = {
139 	APS_PAGE_CODE | SMPH_SPF, //page_code
140 	APS_SUBPAGE_CODE, //subpage
141 	{(sizeof(struct copan_aps_subpage) - 4) & 0xff00,
142 	 (sizeof(struct copan_aps_subpage) - 4) & 0x00ff}, //page_length
143 	APS_VERSION, //page_version
144 	0, //lock_active
145 	{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
146 	0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
147 	0, 0, 0, 0, 0} //reserved
148 };
149 
150 static struct copan_aps_subpage aps_page_changeable = {
151 	APS_PAGE_CODE | SMPH_SPF, //page_code
152 	APS_SUBPAGE_CODE, //subpage
153 	{(sizeof(struct copan_aps_subpage) - 4) & 0xff00,
154 	 (sizeof(struct copan_aps_subpage) - 4) & 0x00ff}, //page_length
155 	0, //page_version
156 	0, //lock_active
157 	{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
158 	0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
159 	0, 0, 0, 0, 0} //reserved
160 };
161 
162 static struct copan_debugconf_subpage debugconf_page_default = {
163 	DBGCNF_PAGE_CODE | SMPH_SPF,	/* page_code */
164 	DBGCNF_SUBPAGE_CODE,		/* subpage */
165 	{(sizeof(struct copan_debugconf_subpage) - 4) >> 8,
166 	 (sizeof(struct copan_debugconf_subpage) - 4) >> 0}, /* page_length */
167 	DBGCNF_VERSION,			/* page_version */
168 	{CTL_TIME_IO_DEFAULT_SECS>>8,
169 	 CTL_TIME_IO_DEFAULT_SECS>>0},	/* ctl_time_io_secs */
170 };
171 
172 static struct copan_debugconf_subpage debugconf_page_changeable = {
173 	DBGCNF_PAGE_CODE | SMPH_SPF,	/* page_code */
174 	DBGCNF_SUBPAGE_CODE,		/* subpage */
175 	{(sizeof(struct copan_debugconf_subpage) - 4) >> 8,
176 	 (sizeof(struct copan_debugconf_subpage) - 4) >> 0}, /* page_length */
177 	0,				/* page_version */
178 	{0xff,0xff},			/* ctl_time_io_secs */
179 };
180 
181 static struct scsi_format_page format_page_default = {
182 	/*page_code*/SMS_FORMAT_DEVICE_PAGE,
183 	/*page_length*/sizeof(struct scsi_format_page) - 2,
184 	/*tracks_per_zone*/ {0, 0},
185 	/*alt_sectors_per_zone*/ {0, 0},
186 	/*alt_tracks_per_zone*/ {0, 0},
187 	/*alt_tracks_per_lun*/ {0, 0},
188 	/*sectors_per_track*/ {(CTL_DEFAULT_SECTORS_PER_TRACK >> 8) & 0xff,
189 			        CTL_DEFAULT_SECTORS_PER_TRACK & 0xff},
190 	/*bytes_per_sector*/ {0, 0},
191 	/*interleave*/ {0, 0},
192 	/*track_skew*/ {0, 0},
193 	/*cylinder_skew*/ {0, 0},
194 	/*flags*/ SFP_HSEC,
195 	/*reserved*/ {0, 0, 0}
196 };
197 
198 static struct scsi_format_page format_page_changeable = {
199 	/*page_code*/SMS_FORMAT_DEVICE_PAGE,
200 	/*page_length*/sizeof(struct scsi_format_page) - 2,
201 	/*tracks_per_zone*/ {0, 0},
202 	/*alt_sectors_per_zone*/ {0, 0},
203 	/*alt_tracks_per_zone*/ {0, 0},
204 	/*alt_tracks_per_lun*/ {0, 0},
205 	/*sectors_per_track*/ {0, 0},
206 	/*bytes_per_sector*/ {0, 0},
207 	/*interleave*/ {0, 0},
208 	/*track_skew*/ {0, 0},
209 	/*cylinder_skew*/ {0, 0},
210 	/*flags*/ 0,
211 	/*reserved*/ {0, 0, 0}
212 };
213 
214 static struct scsi_rigid_disk_page rigid_disk_page_default = {
215 	/*page_code*/SMS_RIGID_DISK_PAGE,
216 	/*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
217 	/*cylinders*/ {0, 0, 0},
218 	/*heads*/ CTL_DEFAULT_HEADS,
219 	/*start_write_precomp*/ {0, 0, 0},
220 	/*start_reduced_current*/ {0, 0, 0},
221 	/*step_rate*/ {0, 0},
222 	/*landing_zone_cylinder*/ {0, 0, 0},
223 	/*rpl*/ SRDP_RPL_DISABLED,
224 	/*rotational_offset*/ 0,
225 	/*reserved1*/ 0,
226 	/*rotation_rate*/ {(CTL_DEFAULT_ROTATION_RATE >> 8) & 0xff,
227 			   CTL_DEFAULT_ROTATION_RATE & 0xff},
228 	/*reserved2*/ {0, 0}
229 };
230 
231 static struct scsi_rigid_disk_page rigid_disk_page_changeable = {
232 	/*page_code*/SMS_RIGID_DISK_PAGE,
233 	/*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
234 	/*cylinders*/ {0, 0, 0},
235 	/*heads*/ 0,
236 	/*start_write_precomp*/ {0, 0, 0},
237 	/*start_reduced_current*/ {0, 0, 0},
238 	/*step_rate*/ {0, 0},
239 	/*landing_zone_cylinder*/ {0, 0, 0},
240 	/*rpl*/ 0,
241 	/*rotational_offset*/ 0,
242 	/*reserved1*/ 0,
243 	/*rotation_rate*/ {0, 0},
244 	/*reserved2*/ {0, 0}
245 };
246 
247 static struct scsi_caching_page caching_page_default = {
248 	/*page_code*/SMS_CACHING_PAGE,
249 	/*page_length*/sizeof(struct scsi_caching_page) - 2,
250 	/*flags1*/ SCP_DISC | SCP_WCE,
251 	/*ret_priority*/ 0,
252 	/*disable_pf_transfer_len*/ {0xff, 0xff},
253 	/*min_prefetch*/ {0, 0},
254 	/*max_prefetch*/ {0xff, 0xff},
255 	/*max_pf_ceiling*/ {0xff, 0xff},
256 	/*flags2*/ 0,
257 	/*cache_segments*/ 0,
258 	/*cache_seg_size*/ {0, 0},
259 	/*reserved*/ 0,
260 	/*non_cache_seg_size*/ {0, 0, 0}
261 };
262 
263 static struct scsi_caching_page caching_page_changeable = {
264 	/*page_code*/SMS_CACHING_PAGE,
265 	/*page_length*/sizeof(struct scsi_caching_page) - 2,
266 	/*flags1*/ 0,
267 	/*ret_priority*/ 0,
268 	/*disable_pf_transfer_len*/ {0, 0},
269 	/*min_prefetch*/ {0, 0},
270 	/*max_prefetch*/ {0, 0},
271 	/*max_pf_ceiling*/ {0, 0},
272 	/*flags2*/ 0,
273 	/*cache_segments*/ 0,
274 	/*cache_seg_size*/ {0, 0},
275 	/*reserved*/ 0,
276 	/*non_cache_seg_size*/ {0, 0, 0}
277 };
278 
279 static struct scsi_control_page control_page_default = {
280 	/*page_code*/SMS_CONTROL_MODE_PAGE,
281 	/*page_length*/sizeof(struct scsi_control_page) - 2,
282 	/*rlec*/0,
283 	/*queue_flags*/0,
284 	/*eca_and_aen*/0,
285 	/*flags4*/SCP_TAS,
286 	/*aen_holdoff_period*/{0, 0},
287 	/*busy_timeout_period*/{0, 0},
288 	/*extended_selftest_completion_time*/{0, 0}
289 };
290 
291 static struct scsi_control_page control_page_changeable = {
292 	/*page_code*/SMS_CONTROL_MODE_PAGE,
293 	/*page_length*/sizeof(struct scsi_control_page) - 2,
294 	/*rlec*/SCP_DSENSE,
295 	/*queue_flags*/0,
296 	/*eca_and_aen*/0,
297 	/*flags4*/0,
298 	/*aen_holdoff_period*/{0, 0},
299 	/*busy_timeout_period*/{0, 0},
300 	/*extended_selftest_completion_time*/{0, 0}
301 };
302 
303 
304 /*
305  * XXX KDM move these into the softc.
306  */
307 static int rcv_sync_msg;
308 static int persis_offset;
309 static uint8_t ctl_pause_rtr;
310 static int     ctl_is_single = 1;
311 static int     index_to_aps_page;
312 
313 SYSCTL_NODE(_kern_cam, OID_AUTO, ctl, CTLFLAG_RD, 0, "CAM Target Layer");
314 static int worker_threads = -1;
315 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, worker_threads, CTLFLAG_RDTUN,
316     &worker_threads, 1, "Number of worker threads");
317 static int verbose = 0;
318 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, verbose, CTLFLAG_RWTUN,
319     &verbose, 0, "Show SCSI errors returned to initiator");
320 
321 /*
322  * Supported pages (0x00), Serial number (0x80), Device ID (0x83),
323  * SCSI Ports (0x88), Third-party Copy (0x8F), Block limits (0xB0) and
324  * Logical Block Provisioning (0xB2)
325  */
326 #define SCSI_EVPD_NUM_SUPPORTED_PAGES	7
327 
328 static void ctl_isc_event_handler(ctl_ha_channel chanel, ctl_ha_event event,
329 				  int param);
330 static void ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest);
331 static int ctl_init(void);
332 void ctl_shutdown(void);
333 static int ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td);
334 static int ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td);
335 static void ctl_ioctl_online(void *arg);
336 static void ctl_ioctl_offline(void *arg);
337 static int ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id);
338 static int ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id);
339 static int ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio);
340 static int ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio);
341 static int ctl_ioctl_submit_wait(union ctl_io *io);
342 static void ctl_ioctl_datamove(union ctl_io *io);
343 static void ctl_ioctl_done(union ctl_io *io);
344 static void ctl_ioctl_hard_startstop_callback(void *arg,
345 					      struct cfi_metatask *metatask);
346 static void ctl_ioctl_bbrread_callback(void *arg,struct cfi_metatask *metatask);
347 static int ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
348 			      struct ctl_ooa *ooa_hdr,
349 			      struct ctl_ooa_entry *kern_entries);
350 static int ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
351 		     struct thread *td);
352 static uint32_t ctl_map_lun(int port_num, uint32_t lun);
353 static uint32_t ctl_map_lun_back(int port_num, uint32_t lun);
354 #ifdef unused
355 static union ctl_io *ctl_malloc_io(ctl_io_type io_type, uint32_t targ_port,
356 				   uint32_t targ_target, uint32_t targ_lun,
357 				   int can_wait);
358 static void ctl_kfree_io(union ctl_io *io);
359 #endif /* unused */
360 static int ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
361 			 struct ctl_be_lun *be_lun, struct ctl_id target_id);
362 static int ctl_free_lun(struct ctl_lun *lun);
363 static void ctl_create_lun(struct ctl_be_lun *be_lun);
364 /**
365 static void ctl_failover_change_pages(struct ctl_softc *softc,
366 				      struct ctl_scsiio *ctsio, int master);
367 **/
368 
369 static int ctl_do_mode_select(union ctl_io *io);
370 static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
371 			   uint64_t res_key, uint64_t sa_res_key,
372 			   uint8_t type, uint32_t residx,
373 			   struct ctl_scsiio *ctsio,
374 			   struct scsi_per_res_out *cdb,
375 			   struct scsi_per_res_out_parms* param);
376 static void ctl_pro_preempt_other(struct ctl_lun *lun,
377 				  union ctl_ha_msg *msg);
378 static void ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg);
379 static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
380 static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
381 static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
382 static int ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio,
383 					 int alloc_len);
384 static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
385 					 int alloc_len);
386 static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
387 static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
388 static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
389 static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint32_t *len);
390 static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2);
391 static ctl_action ctl_check_for_blockage(union ctl_io *pending_io,
392 					 union ctl_io *ooa_io);
393 static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
394 				union ctl_io *starting_io);
395 static int ctl_check_blocked(struct ctl_lun *lun);
396 static int ctl_scsiio_lun_check(struct ctl_softc *ctl_softc,
397 				struct ctl_lun *lun,
398 				const struct ctl_cmd_entry *entry,
399 				struct ctl_scsiio *ctsio);
400 //static int ctl_check_rtr(union ctl_io *pending_io, struct ctl_softc *softc);
401 static void ctl_failover(void);
402 static int ctl_scsiio_precheck(struct ctl_softc *ctl_softc,
403 			       struct ctl_scsiio *ctsio);
404 static int ctl_scsiio(struct ctl_scsiio *ctsio);
405 
406 static int ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
407 static int ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
408 			    ctl_ua_type ua_type);
409 static int ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io,
410 			 ctl_ua_type ua_type);
411 static int ctl_abort_task(union ctl_io *io);
412 static int ctl_abort_task_set(union ctl_io *io);
413 static int ctl_i_t_nexus_reset(union ctl_io *io);
414 static void ctl_run_task(union ctl_io *io);
415 #ifdef CTL_IO_DELAY
416 static void ctl_datamove_timer_wakeup(void *arg);
417 static void ctl_done_timer_wakeup(void *arg);
418 #endif /* CTL_IO_DELAY */
419 
420 static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
421 static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
422 static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
423 static void ctl_datamove_remote_write(union ctl_io *io);
424 static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
425 static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
426 static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
427 static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
428 				    ctl_ha_dt_cb callback);
429 static void ctl_datamove_remote_read(union ctl_io *io);
430 static void ctl_datamove_remote(union ctl_io *io);
431 static int ctl_process_done(union ctl_io *io);
432 static void ctl_lun_thread(void *arg);
433 static void ctl_work_thread(void *arg);
434 static void ctl_enqueue_incoming(union ctl_io *io);
435 static void ctl_enqueue_rtr(union ctl_io *io);
436 static void ctl_enqueue_done(union ctl_io *io);
437 static void ctl_enqueue_isc(union ctl_io *io);
438 static const struct ctl_cmd_entry *
439     ctl_get_cmd_entry(struct ctl_scsiio *ctsio);
440 static const struct ctl_cmd_entry *
441     ctl_validate_command(struct ctl_scsiio *ctsio);
442 static int ctl_cmd_applicable(uint8_t lun_type,
443     const struct ctl_cmd_entry *entry);
444 
445 /*
446  * Load the serialization table.  This isn't very pretty, but is probably
447  * the easiest way to do it.
448  */
449 #include "ctl_ser_table.c"
450 
451 /*
452  * We only need to define open, close and ioctl routines for this driver.
453  */
454 static struct cdevsw ctl_cdevsw = {
455 	.d_version =	D_VERSION,
456 	.d_flags =	0,
457 	.d_open =	ctl_open,
458 	.d_close =	ctl_close,
459 	.d_ioctl =	ctl_ioctl,
460 	.d_name =	"ctl",
461 };
462 
463 
464 MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
465 MALLOC_DEFINE(M_CTLIO, "ctlio", "Memory used for CTL requests");
466 
467 static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
468 
469 static moduledata_t ctl_moduledata = {
470 	"ctl",
471 	ctl_module_event_handler,
472 	NULL
473 };
474 
475 DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
476 MODULE_VERSION(ctl, 1);
477 
478 static struct ctl_frontend ioctl_frontend =
479 {
480 	.name = "ioctl",
481 };
482 
483 static void
484 ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
485 			    union ctl_ha_msg *msg_info)
486 {
487 	struct ctl_scsiio *ctsio;
488 
489 	if (msg_info->hdr.original_sc == NULL) {
490 		printf("%s: original_sc == NULL!\n", __func__);
491 		/* XXX KDM now what? */
492 		return;
493 	}
494 
495 	ctsio = &msg_info->hdr.original_sc->scsiio;
496 	ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
497 	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
498 	ctsio->io_hdr.status = msg_info->hdr.status;
499 	ctsio->scsi_status = msg_info->scsi.scsi_status;
500 	ctsio->sense_len = msg_info->scsi.sense_len;
501 	ctsio->sense_residual = msg_info->scsi.sense_residual;
502 	ctsio->residual = msg_info->scsi.residual;
503 	memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
504 	       sizeof(ctsio->sense_data));
505 	memcpy(&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
506 	       &msg_info->scsi.lbalen, sizeof(msg_info->scsi.lbalen));
507 	ctl_enqueue_isc((union ctl_io *)ctsio);
508 }
509 
510 static void
511 ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
512 				union ctl_ha_msg *msg_info)
513 {
514 	struct ctl_scsiio *ctsio;
515 
516 	if (msg_info->hdr.serializing_sc == NULL) {
517 		printf("%s: serializing_sc == NULL!\n", __func__);
518 		/* XXX KDM now what? */
519 		return;
520 	}
521 
522 	ctsio = &msg_info->hdr.serializing_sc->scsiio;
523 #if 0
524 	/*
525 	 * Attempt to catch the situation where an I/O has
526 	 * been freed, and we're using it again.
527 	 */
528 	if (ctsio->io_hdr.io_type == 0xff) {
529 		union ctl_io *tmp_io;
530 		tmp_io = (union ctl_io *)ctsio;
531 		printf("%s: %p use after free!\n", __func__,
532 		       ctsio);
533 		printf("%s: type %d msg %d cdb %x iptl: "
534 		       "%d:%d:%d:%d tag 0x%04x "
535 		       "flag %#x status %x\n",
536 			__func__,
537 			tmp_io->io_hdr.io_type,
538 			tmp_io->io_hdr.msg_type,
539 			tmp_io->scsiio.cdb[0],
540 			tmp_io->io_hdr.nexus.initid.id,
541 			tmp_io->io_hdr.nexus.targ_port,
542 			tmp_io->io_hdr.nexus.targ_target.id,
543 			tmp_io->io_hdr.nexus.targ_lun,
544 			(tmp_io->io_hdr.io_type ==
545 			CTL_IO_TASK) ?
546 			tmp_io->taskio.tag_num :
547 			tmp_io->scsiio.tag_num,
548 		        tmp_io->io_hdr.flags,
549 			tmp_io->io_hdr.status);
550 	}
551 #endif
552 	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
553 	ctl_enqueue_isc((union ctl_io *)ctsio);
554 }
555 
556 /*
557  * ISC (Inter Shelf Communication) event handler.  Events from the HA
558  * subsystem come in here.
559  */
560 static void
561 ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
562 {
563 	struct ctl_softc *ctl_softc;
564 	union ctl_io *io;
565 	struct ctl_prio *presio;
566 	ctl_ha_status isc_status;
567 
568 	ctl_softc = control_softc;
569 	io = NULL;
570 
571 
572 #if 0
573 	printf("CTL: Isc Msg event %d\n", event);
574 #endif
575 	if (event == CTL_HA_EVT_MSG_RECV) {
576 		union ctl_ha_msg msg_info;
577 
578 		isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
579 					     sizeof(msg_info), /*wait*/ 0);
580 #if 0
581 		printf("CTL: msg_type %d\n", msg_info.msg_type);
582 #endif
583 		if (isc_status != 0) {
584 			printf("Error receiving message, status = %d\n",
585 			       isc_status);
586 			return;
587 		}
588 
589 		switch (msg_info.hdr.msg_type) {
590 		case CTL_MSG_SERIALIZE:
591 #if 0
592 			printf("Serialize\n");
593 #endif
594 			io = ctl_alloc_io((void *)ctl_softc->othersc_pool);
595 			if (io == NULL) {
596 				printf("ctl_isc_event_handler: can't allocate "
597 				       "ctl_io!\n");
598 				/* Bad Juju */
599 				/* Need to set busy and send msg back */
600 				msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
601 				msg_info.hdr.status = CTL_SCSI_ERROR;
602 				msg_info.scsi.scsi_status = SCSI_STATUS_BUSY;
603 				msg_info.scsi.sense_len = 0;
604 			        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
605 				    sizeof(msg_info), 0) > CTL_HA_STATUS_SUCCESS){
606 				}
607 				goto bailout;
608 			}
609 			ctl_zero_io(io);
610 			// populate ctsio from msg_info
611 			io->io_hdr.io_type = CTL_IO_SCSI;
612 			io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
613 			io->io_hdr.original_sc = msg_info.hdr.original_sc;
614 #if 0
615 			printf("pOrig %x\n", (int)msg_info.original_sc);
616 #endif
617 			io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
618 					    CTL_FLAG_IO_ACTIVE;
619 			/*
620 			 * If we're in serialization-only mode, we don't
621 			 * want to go through full done processing.  Thus
622 			 * the COPY flag.
623 			 *
624 			 * XXX KDM add another flag that is more specific.
625 			 */
626 			if (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)
627 				io->io_hdr.flags |= CTL_FLAG_INT_COPY;
628 			io->io_hdr.nexus = msg_info.hdr.nexus;
629 #if 0
630 			printf("targ %d, port %d, iid %d, lun %d\n",
631 			       io->io_hdr.nexus.targ_target.id,
632 			       io->io_hdr.nexus.targ_port,
633 			       io->io_hdr.nexus.initid.id,
634 			       io->io_hdr.nexus.targ_lun);
635 #endif
636 			io->scsiio.tag_num = msg_info.scsi.tag_num;
637 			io->scsiio.tag_type = msg_info.scsi.tag_type;
638 			memcpy(io->scsiio.cdb, msg_info.scsi.cdb,
639 			       CTL_MAX_CDBLEN);
640 			if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
641 				const struct ctl_cmd_entry *entry;
642 
643 				entry = ctl_get_cmd_entry(&io->scsiio);
644 				io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
645 				io->io_hdr.flags |=
646 					entry->flags & CTL_FLAG_DATA_MASK;
647 			}
648 			ctl_enqueue_isc(io);
649 			break;
650 
651 		/* Performed on the Originating SC, XFER mode only */
652 		case CTL_MSG_DATAMOVE: {
653 			struct ctl_sg_entry *sgl;
654 			int i, j;
655 
656 			io = msg_info.hdr.original_sc;
657 			if (io == NULL) {
658 				printf("%s: original_sc == NULL!\n", __func__);
659 				/* XXX KDM do something here */
660 				break;
661 			}
662 			io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
663 			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
664 			/*
665 			 * Keep track of this, we need to send it back over
666 			 * when the datamove is complete.
667 			 */
668 			io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
669 
670 			if (msg_info.dt.sg_sequence == 0) {
671 				/*
672 				 * XXX KDM we use the preallocated S/G list
673 				 * here, but we'll need to change this to
674 				 * dynamic allocation if we need larger S/G
675 				 * lists.
676 				 */
677 				if (msg_info.dt.kern_sg_entries >
678 				    sizeof(io->io_hdr.remote_sglist) /
679 				    sizeof(io->io_hdr.remote_sglist[0])) {
680 					printf("%s: number of S/G entries "
681 					    "needed %u > allocated num %zd\n",
682 					    __func__,
683 					    msg_info.dt.kern_sg_entries,
684 					    sizeof(io->io_hdr.remote_sglist)/
685 					    sizeof(io->io_hdr.remote_sglist[0]));
686 
687 					/*
688 					 * XXX KDM send a message back to
689 					 * the other side to shut down the
690 					 * DMA.  The error will come back
691 					 * through via the normal channel.
692 					 */
693 					break;
694 				}
695 				sgl = io->io_hdr.remote_sglist;
696 				memset(sgl, 0,
697 				       sizeof(io->io_hdr.remote_sglist));
698 
699 				io->scsiio.kern_data_ptr = (uint8_t *)sgl;
700 
701 				io->scsiio.kern_sg_entries =
702 					msg_info.dt.kern_sg_entries;
703 				io->scsiio.rem_sg_entries =
704 					msg_info.dt.kern_sg_entries;
705 				io->scsiio.kern_data_len =
706 					msg_info.dt.kern_data_len;
707 				io->scsiio.kern_total_len =
708 					msg_info.dt.kern_total_len;
709 				io->scsiio.kern_data_resid =
710 					msg_info.dt.kern_data_resid;
711 				io->scsiio.kern_rel_offset =
712 					msg_info.dt.kern_rel_offset;
713 				/*
714 				 * Clear out per-DMA flags.
715 				 */
716 				io->io_hdr.flags &= ~CTL_FLAG_RDMA_MASK;
717 				/*
718 				 * Add per-DMA flags that are set for this
719 				 * particular DMA request.
720 				 */
721 				io->io_hdr.flags |= msg_info.dt.flags &
722 						    CTL_FLAG_RDMA_MASK;
723 			} else
724 				sgl = (struct ctl_sg_entry *)
725 					io->scsiio.kern_data_ptr;
726 
727 			for (i = msg_info.dt.sent_sg_entries, j = 0;
728 			     i < (msg_info.dt.sent_sg_entries +
729 			     msg_info.dt.cur_sg_entries); i++, j++) {
730 				sgl[i].addr = msg_info.dt.sg_list[j].addr;
731 				sgl[i].len = msg_info.dt.sg_list[j].len;
732 
733 #if 0
734 				printf("%s: L: %p,%d -> %p,%d j=%d, i=%d\n",
735 				       __func__,
736 				       msg_info.dt.sg_list[j].addr,
737 				       msg_info.dt.sg_list[j].len,
738 				       sgl[i].addr, sgl[i].len, j, i);
739 #endif
740 			}
741 #if 0
742 			memcpy(&sgl[msg_info.dt.sent_sg_entries],
743 			       msg_info.dt.sg_list,
744 			       sizeof(*sgl) * msg_info.dt.cur_sg_entries);
745 #endif
746 
747 			/*
748 			 * If this is the last piece of the I/O, we've got
749 			 * the full S/G list.  Queue processing in the thread.
750 			 * Otherwise wait for the next piece.
751 			 */
752 			if (msg_info.dt.sg_last != 0)
753 				ctl_enqueue_isc(io);
754 			break;
755 		}
756 		/* Performed on the Serializing (primary) SC, XFER mode only */
757 		case CTL_MSG_DATAMOVE_DONE: {
758 			if (msg_info.hdr.serializing_sc == NULL) {
759 				printf("%s: serializing_sc == NULL!\n",
760 				       __func__);
761 				/* XXX KDM now what? */
762 				break;
763 			}
764 			/*
765 			 * We grab the sense information here in case
766 			 * there was a failure, so we can return status
767 			 * back to the initiator.
768 			 */
769 			io = msg_info.hdr.serializing_sc;
770 			io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
771 			io->io_hdr.status = msg_info.hdr.status;
772 			io->scsiio.scsi_status = msg_info.scsi.scsi_status;
773 			io->scsiio.sense_len = msg_info.scsi.sense_len;
774 			io->scsiio.sense_residual =msg_info.scsi.sense_residual;
775 			io->io_hdr.port_status = msg_info.scsi.fetd_status;
776 			io->scsiio.residual = msg_info.scsi.residual;
777 			memcpy(&io->scsiio.sense_data,&msg_info.scsi.sense_data,
778 			       sizeof(io->scsiio.sense_data));
779 			ctl_enqueue_isc(io);
780 			break;
781 		}
782 
783 		/* Preformed on Originating SC, SER_ONLY mode */
784 		case CTL_MSG_R2R:
785 			io = msg_info.hdr.original_sc;
786 			if (io == NULL) {
787 				printf("%s: Major Bummer\n", __func__);
788 				return;
789 			} else {
790 #if 0
791 				printf("pOrig %x\n",(int) ctsio);
792 #endif
793 			}
794 			io->io_hdr.msg_type = CTL_MSG_R2R;
795 			io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
796 			ctl_enqueue_isc(io);
797 			break;
798 
799 		/*
800 		 * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
801 		 * mode.
802 		 * Performed on the Originating (i.e. secondary) SC in XFER
803 		 * mode
804 		 */
805 		case CTL_MSG_FINISH_IO:
806 			if (ctl_softc->ha_mode == CTL_HA_MODE_XFER)
807 				ctl_isc_handler_finish_xfer(ctl_softc,
808 							    &msg_info);
809 			else
810 				ctl_isc_handler_finish_ser_only(ctl_softc,
811 								&msg_info);
812 			break;
813 
814 		/* Preformed on Originating SC */
815 		case CTL_MSG_BAD_JUJU:
816 			io = msg_info.hdr.original_sc;
817 			if (io == NULL) {
818 				printf("%s: Bad JUJU!, original_sc is NULL!\n",
819 				       __func__);
820 				break;
821 			}
822 			ctl_copy_sense_data(&msg_info, io);
823 			/*
824 			 * IO should have already been cleaned up on other
825 			 * SC so clear this flag so we won't send a message
826 			 * back to finish the IO there.
827 			 */
828 			io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
829 			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
830 
831 			/* io = msg_info.hdr.serializing_sc; */
832 			io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
833 			ctl_enqueue_isc(io);
834 			break;
835 
836 		/* Handle resets sent from the other side */
837 		case CTL_MSG_MANAGE_TASKS: {
838 			struct ctl_taskio *taskio;
839 			taskio = (struct ctl_taskio *)ctl_alloc_io(
840 				(void *)ctl_softc->othersc_pool);
841 			if (taskio == NULL) {
842 				printf("ctl_isc_event_handler: can't allocate "
843 				       "ctl_io!\n");
844 				/* Bad Juju */
845 				/* should I just call the proper reset func
846 				   here??? */
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 			ctl_run_task((union ctl_io *)taskio);
864 			break;
865 		}
866 		/* Persistent Reserve action which needs attention */
867 		case CTL_MSG_PERS_ACTION:
868 			presio = (struct ctl_prio *)ctl_alloc_io(
869 				(void *)ctl_softc->othersc_pool);
870 			if (presio == NULL) {
871 				printf("ctl_isc_event_handler: can't allocate "
872 				       "ctl_io!\n");
873 				/* Bad Juju */
874 				/* Need to set busy and send msg back */
875 				goto bailout;
876 			}
877 			ctl_zero_io((union ctl_io *)presio);
878 			presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
879 			presio->pr_msg = msg_info.pr;
880 			ctl_enqueue_isc((union ctl_io *)presio);
881 			break;
882 		case CTL_MSG_SYNC_FE:
883 			rcv_sync_msg = 1;
884 			break;
885 		case CTL_MSG_APS_LOCK: {
886 			// It's quicker to execute this then to
887 			// queue it.
888 			struct ctl_lun *lun;
889 			struct ctl_page_index *page_index;
890 			struct copan_aps_subpage *current_sp;
891 			uint32_t targ_lun;
892 
893 			targ_lun = msg_info.hdr.nexus.targ_mapped_lun;
894 			lun = ctl_softc->ctl_luns[targ_lun];
895 			mtx_lock(&lun->lun_lock);
896 			page_index = &lun->mode_pages.index[index_to_aps_page];
897 			current_sp = (struct copan_aps_subpage *)
898 				     (page_index->page_data +
899 				     (page_index->page_len * CTL_PAGE_CURRENT));
900 
901 			current_sp->lock_active = msg_info.aps.lock_flag;
902 			mtx_unlock(&lun->lun_lock);
903 		        break;
904 		}
905 		default:
906 		        printf("How did I get here?\n");
907 		}
908 	} else if (event == CTL_HA_EVT_MSG_SENT) {
909 		if (param != CTL_HA_STATUS_SUCCESS) {
910 			printf("Bad status from ctl_ha_msg_send status %d\n",
911 			       param);
912 		}
913 		return;
914 	} else if (event == CTL_HA_EVT_DISCONNECT) {
915 		printf("CTL: Got a disconnect from Isc\n");
916 		return;
917 	} else {
918 		printf("ctl_isc_event_handler: Unknown event %d\n", event);
919 		return;
920 	}
921 
922 bailout:
923 	return;
924 }
925 
926 static void
927 ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
928 {
929 	struct scsi_sense_data *sense;
930 
931 	sense = &dest->scsiio.sense_data;
932 	bcopy(&src->scsi.sense_data, sense, sizeof(*sense));
933 	dest->scsiio.scsi_status = src->scsi.scsi_status;
934 	dest->scsiio.sense_len = src->scsi.sense_len;
935 	dest->io_hdr.status = src->hdr.status;
936 }
937 
938 static int
939 ctl_init(void)
940 {
941 	struct ctl_softc *softc;
942 	struct ctl_io_pool *internal_pool, *emergency_pool, *other_pool;
943 	struct ctl_port *port;
944         uint8_t sc_id =0;
945 	int i, error, retval;
946 	//int isc_retval;
947 
948 	retval = 0;
949 	ctl_pause_rtr = 0;
950         rcv_sync_msg = 0;
951 
952 	control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
953 			       M_WAITOK | M_ZERO);
954 	softc = control_softc;
955 
956 	softc->dev = make_dev(&ctl_cdevsw, 0, UID_ROOT, GID_OPERATOR, 0600,
957 			      "cam/ctl");
958 
959 	softc->dev->si_drv1 = softc;
960 
961 	/*
962 	 * By default, return a "bad LUN" peripheral qualifier for unknown
963 	 * LUNs.  The user can override this default using the tunable or
964 	 * sysctl.  See the comment in ctl_inquiry_std() for more details.
965 	 */
966 	softc->inquiry_pq_no_lun = 1;
967 	TUNABLE_INT_FETCH("kern.cam.ctl.inquiry_pq_no_lun",
968 			  &softc->inquiry_pq_no_lun);
969 	sysctl_ctx_init(&softc->sysctl_ctx);
970 	softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
971 		SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
972 		CTLFLAG_RD, 0, "CAM Target Layer");
973 
974 	if (softc->sysctl_tree == NULL) {
975 		printf("%s: unable to allocate sysctl tree\n", __func__);
976 		destroy_dev(softc->dev);
977 		free(control_softc, M_DEVBUF);
978 		control_softc = NULL;
979 		return (ENOMEM);
980 	}
981 
982 	SYSCTL_ADD_INT(&softc->sysctl_ctx,
983 		       SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
984 		       "inquiry_pq_no_lun", CTLFLAG_RW,
985 		       &softc->inquiry_pq_no_lun, 0,
986 		       "Report no lun possible for invalid LUNs");
987 
988 	mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
989 	mtx_init(&softc->pool_lock, "CTL pool mutex", NULL, MTX_DEF);
990 	softc->open_count = 0;
991 
992 	/*
993 	 * Default to actually sending a SYNCHRONIZE CACHE command down to
994 	 * the drive.
995 	 */
996 	softc->flags = CTL_FLAG_REAL_SYNC;
997 
998 	/*
999 	 * In Copan's HA scheme, the "master" and "slave" roles are
1000 	 * figured out through the slot the controller is in.  Although it
1001 	 * is an active/active system, someone has to be in charge.
1002  	 */
1003 #ifdef NEEDTOPORT
1004         scmicro_rw(SCMICRO_GET_SHELF_ID, &sc_id);
1005 #endif
1006 
1007         if (sc_id == 0) {
1008 		softc->flags |= CTL_FLAG_MASTER_SHELF;
1009 		persis_offset = 0;
1010 	} else
1011 		persis_offset = CTL_MAX_INITIATORS;
1012 
1013 	/*
1014 	 * XXX KDM need to figure out where we want to get our target ID
1015 	 * and WWID.  Is it different on each port?
1016 	 */
1017 	softc->target.id = 0;
1018 	softc->target.wwid[0] = 0x12345678;
1019 	softc->target.wwid[1] = 0x87654321;
1020 	STAILQ_INIT(&softc->lun_list);
1021 	STAILQ_INIT(&softc->pending_lun_queue);
1022 	STAILQ_INIT(&softc->fe_list);
1023 	STAILQ_INIT(&softc->port_list);
1024 	STAILQ_INIT(&softc->be_list);
1025 	STAILQ_INIT(&softc->io_pools);
1026 
1027 	if (ctl_pool_create(softc, CTL_POOL_INTERNAL, CTL_POOL_ENTRIES_INTERNAL,
1028 			    &internal_pool)!= 0){
1029 		printf("ctl: can't allocate %d entry internal pool, "
1030 		       "exiting\n", CTL_POOL_ENTRIES_INTERNAL);
1031 		return (ENOMEM);
1032 	}
1033 
1034 	if (ctl_pool_create(softc, CTL_POOL_EMERGENCY,
1035 			    CTL_POOL_ENTRIES_EMERGENCY, &emergency_pool) != 0) {
1036 		printf("ctl: can't allocate %d entry emergency pool, "
1037 		       "exiting\n", CTL_POOL_ENTRIES_EMERGENCY);
1038 		ctl_pool_free(internal_pool);
1039 		return (ENOMEM);
1040 	}
1041 
1042 	if (ctl_pool_create(softc, CTL_POOL_4OTHERSC, CTL_POOL_ENTRIES_OTHER_SC,
1043 	                    &other_pool) != 0)
1044 	{
1045 		printf("ctl: can't allocate %d entry other SC pool, "
1046 		       "exiting\n", CTL_POOL_ENTRIES_OTHER_SC);
1047 		ctl_pool_free(internal_pool);
1048 		ctl_pool_free(emergency_pool);
1049 		return (ENOMEM);
1050 	}
1051 
1052 	softc->internal_pool = internal_pool;
1053 	softc->emergency_pool = emergency_pool;
1054 	softc->othersc_pool = other_pool;
1055 
1056 	if (worker_threads <= 0)
1057 		worker_threads = max(1, mp_ncpus / 4);
1058 	if (worker_threads > CTL_MAX_THREADS)
1059 		worker_threads = CTL_MAX_THREADS;
1060 
1061 	for (i = 0; i < worker_threads; i++) {
1062 		struct ctl_thread *thr = &softc->threads[i];
1063 
1064 		mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1065 		thr->ctl_softc = softc;
1066 		STAILQ_INIT(&thr->incoming_queue);
1067 		STAILQ_INIT(&thr->rtr_queue);
1068 		STAILQ_INIT(&thr->done_queue);
1069 		STAILQ_INIT(&thr->isc_queue);
1070 
1071 		error = kproc_kthread_add(ctl_work_thread, thr,
1072 		    &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1073 		if (error != 0) {
1074 			printf("error creating CTL work thread!\n");
1075 			ctl_pool_free(internal_pool);
1076 			ctl_pool_free(emergency_pool);
1077 			ctl_pool_free(other_pool);
1078 			return (error);
1079 		}
1080 	}
1081 	error = kproc_kthread_add(ctl_lun_thread, softc,
1082 	    &softc->ctl_proc, NULL, 0, 0, "ctl", "lun");
1083 	if (error != 0) {
1084 		printf("error creating CTL lun thread!\n");
1085 		ctl_pool_free(internal_pool);
1086 		ctl_pool_free(emergency_pool);
1087 		ctl_pool_free(other_pool);
1088 		return (error);
1089 	}
1090 	if (bootverbose)
1091 		printf("ctl: CAM Target Layer loaded\n");
1092 
1093 	/*
1094 	 * Initialize the ioctl front end.
1095 	 */
1096 	ctl_frontend_register(&ioctl_frontend);
1097 	port = &softc->ioctl_info.port;
1098 	port->frontend = &ioctl_frontend;
1099 	sprintf(softc->ioctl_info.port_name, "ioctl");
1100 	port->port_type = CTL_PORT_IOCTL;
1101 	port->num_requested_ctl_io = 100;
1102 	port->port_name = softc->ioctl_info.port_name;
1103 	port->port_online = ctl_ioctl_online;
1104 	port->port_offline = ctl_ioctl_offline;
1105 	port->onoff_arg = &softc->ioctl_info;
1106 	port->lun_enable = ctl_ioctl_lun_enable;
1107 	port->lun_disable = ctl_ioctl_lun_disable;
1108 	port->targ_lun_arg = &softc->ioctl_info;
1109 	port->fe_datamove = ctl_ioctl_datamove;
1110 	port->fe_done = ctl_ioctl_done;
1111 	port->max_targets = 15;
1112 	port->max_target_id = 15;
1113 
1114 	if (ctl_port_register(&softc->ioctl_info.port,
1115 	                  (softc->flags & CTL_FLAG_MASTER_SHELF)) != 0) {
1116 		printf("ctl: ioctl front end registration failed, will "
1117 		       "continue anyway\n");
1118 	}
1119 
1120 #ifdef CTL_IO_DELAY
1121 	if (sizeof(struct callout) > CTL_TIMER_BYTES) {
1122 		printf("sizeof(struct callout) %zd > CTL_TIMER_BYTES %zd\n",
1123 		       sizeof(struct callout), CTL_TIMER_BYTES);
1124 		return (EINVAL);
1125 	}
1126 #endif /* CTL_IO_DELAY */
1127 
1128 	return (0);
1129 }
1130 
1131 void
1132 ctl_shutdown(void)
1133 {
1134 	struct ctl_softc *softc;
1135 	struct ctl_lun *lun, *next_lun;
1136 	struct ctl_io_pool *pool;
1137 
1138 	softc = (struct ctl_softc *)control_softc;
1139 
1140 	if (ctl_port_deregister(&softc->ioctl_info.port) != 0)
1141 		printf("ctl: ioctl front end deregistration failed\n");
1142 
1143 	mtx_lock(&softc->ctl_lock);
1144 
1145 	/*
1146 	 * Free up each LUN.
1147 	 */
1148 	for (lun = STAILQ_FIRST(&softc->lun_list); lun != NULL; lun = next_lun){
1149 		next_lun = STAILQ_NEXT(lun, links);
1150 		ctl_free_lun(lun);
1151 	}
1152 
1153 	mtx_unlock(&softc->ctl_lock);
1154 
1155 	ctl_frontend_deregister(&ioctl_frontend);
1156 
1157 	/*
1158 	 * This will rip the rug out from under any FETDs or anyone else
1159 	 * that has a pool allocated.  Since we increment our module
1160 	 * refcount any time someone outside the main CTL module allocates
1161 	 * a pool, we shouldn't have any problems here.  The user won't be
1162 	 * able to unload the CTL module until client modules have
1163 	 * successfully unloaded.
1164 	 */
1165 	while ((pool = STAILQ_FIRST(&softc->io_pools)) != NULL)
1166 		ctl_pool_free(pool);
1167 
1168 #if 0
1169 	ctl_shutdown_thread(softc->work_thread);
1170 	mtx_destroy(&softc->queue_lock);
1171 #endif
1172 
1173 	mtx_destroy(&softc->pool_lock);
1174 	mtx_destroy(&softc->ctl_lock);
1175 
1176 	destroy_dev(softc->dev);
1177 
1178 	sysctl_ctx_free(&softc->sysctl_ctx);
1179 
1180 	free(control_softc, M_DEVBUF);
1181 	control_softc = NULL;
1182 
1183 	if (bootverbose)
1184 		printf("ctl: CAM Target Layer unloaded\n");
1185 }
1186 
1187 static int
1188 ctl_module_event_handler(module_t mod, int what, void *arg)
1189 {
1190 
1191 	switch (what) {
1192 	case MOD_LOAD:
1193 		return (ctl_init());
1194 	case MOD_UNLOAD:
1195 		return (EBUSY);
1196 	default:
1197 		return (EOPNOTSUPP);
1198 	}
1199 }
1200 
1201 /*
1202  * XXX KDM should we do some access checks here?  Bump a reference count to
1203  * prevent a CTL module from being unloaded while someone has it open?
1204  */
1205 static int
1206 ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
1207 {
1208 	return (0);
1209 }
1210 
1211 static int
1212 ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
1213 {
1214 	return (0);
1215 }
1216 
1217 int
1218 ctl_port_enable(ctl_port_type port_type)
1219 {
1220 	struct ctl_softc *softc;
1221 	struct ctl_port *port;
1222 
1223 	if (ctl_is_single == 0) {
1224 		union ctl_ha_msg msg_info;
1225 		int isc_retval;
1226 
1227 #if 0
1228 		printf("%s: HA mode, synchronizing frontend enable\n",
1229 		        __func__);
1230 #endif
1231 		msg_info.hdr.msg_type = CTL_MSG_SYNC_FE;
1232 	        if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1233 		        sizeof(msg_info), 1 )) > CTL_HA_STATUS_SUCCESS) {
1234 			printf("Sync msg send error retval %d\n", isc_retval);
1235 		}
1236 		if (!rcv_sync_msg) {
1237 			isc_retval=ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
1238 			        sizeof(msg_info), 1);
1239 		}
1240 #if 0
1241         	printf("CTL:Frontend Enable\n");
1242 	} else {
1243 		printf("%s: single mode, skipping frontend synchronization\n",
1244 		        __func__);
1245 #endif
1246 	}
1247 
1248 	softc = control_softc;
1249 
1250 	STAILQ_FOREACH(port, &softc->port_list, links) {
1251 		if (port_type & port->port_type)
1252 		{
1253 #if 0
1254 			printf("port %d\n", port->targ_port);
1255 #endif
1256 			ctl_port_online(port);
1257 		}
1258 	}
1259 
1260 	return (0);
1261 }
1262 
1263 int
1264 ctl_port_disable(ctl_port_type port_type)
1265 {
1266 	struct ctl_softc *softc;
1267 	struct ctl_port *port;
1268 
1269 	softc = control_softc;
1270 
1271 	STAILQ_FOREACH(port, &softc->port_list, links) {
1272 		if (port_type & port->port_type)
1273 			ctl_port_offline(port);
1274 	}
1275 
1276 	return (0);
1277 }
1278 
1279 /*
1280  * Returns 0 for success, 1 for failure.
1281  * Currently the only failure mode is if there aren't enough entries
1282  * allocated.  So, in case of a failure, look at num_entries_dropped,
1283  * reallocate and try again.
1284  */
1285 int
1286 ctl_port_list(struct ctl_port_entry *entries, int num_entries_alloced,
1287 	      int *num_entries_filled, int *num_entries_dropped,
1288 	      ctl_port_type port_type, int no_virtual)
1289 {
1290 	struct ctl_softc *softc;
1291 	struct ctl_port *port;
1292 	int entries_dropped, entries_filled;
1293 	int retval;
1294 	int i;
1295 
1296 	softc = control_softc;
1297 
1298 	retval = 0;
1299 	entries_filled = 0;
1300 	entries_dropped = 0;
1301 
1302 	i = 0;
1303 	mtx_lock(&softc->ctl_lock);
1304 	STAILQ_FOREACH(port, &softc->port_list, links) {
1305 		struct ctl_port_entry *entry;
1306 
1307 		if ((port->port_type & port_type) == 0)
1308 			continue;
1309 
1310 		if ((no_virtual != 0)
1311 		 && (port->virtual_port != 0))
1312 			continue;
1313 
1314 		if (entries_filled >= num_entries_alloced) {
1315 			entries_dropped++;
1316 			continue;
1317 		}
1318 		entry = &entries[i];
1319 
1320 		entry->port_type = port->port_type;
1321 		strlcpy(entry->port_name, port->port_name,
1322 			sizeof(entry->port_name));
1323 		entry->physical_port = port->physical_port;
1324 		entry->virtual_port = port->virtual_port;
1325 		entry->wwnn = port->wwnn;
1326 		entry->wwpn = port->wwpn;
1327 
1328 		i++;
1329 		entries_filled++;
1330 	}
1331 
1332 	mtx_unlock(&softc->ctl_lock);
1333 
1334 	if (entries_dropped > 0)
1335 		retval = 1;
1336 
1337 	*num_entries_dropped = entries_dropped;
1338 	*num_entries_filled = entries_filled;
1339 
1340 	return (retval);
1341 }
1342 
1343 static void
1344 ctl_ioctl_online(void *arg)
1345 {
1346 	struct ctl_ioctl_info *ioctl_info;
1347 
1348 	ioctl_info = (struct ctl_ioctl_info *)arg;
1349 
1350 	ioctl_info->flags |= CTL_IOCTL_FLAG_ENABLED;
1351 }
1352 
1353 static void
1354 ctl_ioctl_offline(void *arg)
1355 {
1356 	struct ctl_ioctl_info *ioctl_info;
1357 
1358 	ioctl_info = (struct ctl_ioctl_info *)arg;
1359 
1360 	ioctl_info->flags &= ~CTL_IOCTL_FLAG_ENABLED;
1361 }
1362 
1363 /*
1364  * Remove an initiator by port number and initiator ID.
1365  * Returns 0 for success, -1 for failure.
1366  */
1367 int
1368 ctl_remove_initiator(struct ctl_port *port, int iid)
1369 {
1370 	struct ctl_softc *softc = control_softc;
1371 
1372 	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1373 
1374 	if (iid > CTL_MAX_INIT_PER_PORT) {
1375 		printf("%s: initiator ID %u > maximun %u!\n",
1376 		       __func__, iid, CTL_MAX_INIT_PER_PORT);
1377 		return (-1);
1378 	}
1379 
1380 	mtx_lock(&softc->ctl_lock);
1381 	port->wwpn_iid[iid].in_use--;
1382 	port->wwpn_iid[iid].last_use = time_uptime;
1383 	mtx_unlock(&softc->ctl_lock);
1384 
1385 	return (0);
1386 }
1387 
1388 /*
1389  * Add an initiator to the initiator map.
1390  * Returns iid for success, < 0 for failure.
1391  */
1392 int
1393 ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
1394 {
1395 	struct ctl_softc *softc = control_softc;
1396 	time_t best_time;
1397 	int i, best;
1398 
1399 	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1400 
1401 	if (iid >= CTL_MAX_INIT_PER_PORT) {
1402 		printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
1403 		       __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
1404 		free(name, M_CTL);
1405 		return (-1);
1406 	}
1407 
1408 	mtx_lock(&softc->ctl_lock);
1409 
1410 	if (iid < 0 && (wwpn != 0 || name != NULL)) {
1411 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1412 			if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
1413 				iid = i;
1414 				break;
1415 			}
1416 			if (name != NULL && port->wwpn_iid[i].name != NULL &&
1417 			    strcmp(name, port->wwpn_iid[i].name) == 0) {
1418 				iid = i;
1419 				break;
1420 			}
1421 		}
1422 	}
1423 
1424 	if (iid < 0) {
1425 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1426 			if (port->wwpn_iid[i].in_use == 0 &&
1427 			    port->wwpn_iid[i].wwpn == 0 &&
1428 			    port->wwpn_iid[i].name == NULL) {
1429 				iid = i;
1430 				break;
1431 			}
1432 		}
1433 	}
1434 
1435 	if (iid < 0) {
1436 		best = -1;
1437 		best_time = INT32_MAX;
1438 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1439 			if (port->wwpn_iid[i].in_use == 0) {
1440 				if (port->wwpn_iid[i].last_use < best_time) {
1441 					best = i;
1442 					best_time = port->wwpn_iid[i].last_use;
1443 				}
1444 			}
1445 		}
1446 		iid = best;
1447 	}
1448 
1449 	if (iid < 0) {
1450 		mtx_unlock(&softc->ctl_lock);
1451 		free(name, M_CTL);
1452 		return (-2);
1453 	}
1454 
1455 	if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
1456 		/*
1457 		 * This is not an error yet.
1458 		 */
1459 		if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
1460 #if 0
1461 			printf("%s: port %d iid %u WWPN %#jx arrived"
1462 			    " again\n", __func__, port->targ_port,
1463 			    iid, (uintmax_t)wwpn);
1464 #endif
1465 			goto take;
1466 		}
1467 		if (name != NULL && port->wwpn_iid[iid].name != NULL &&
1468 		    strcmp(name, port->wwpn_iid[iid].name) == 0) {
1469 #if 0
1470 			printf("%s: port %d iid %u name '%s' arrived"
1471 			    " again\n", __func__, port->targ_port,
1472 			    iid, name);
1473 #endif
1474 			goto take;
1475 		}
1476 
1477 		/*
1478 		 * This is an error, but what do we do about it?  The
1479 		 * driver is telling us we have a new WWPN for this
1480 		 * initiator ID, so we pretty much need to use it.
1481 		 */
1482 		printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
1483 		    " but WWPN %#jx '%s' is still at that address\n",
1484 		    __func__, port->targ_port, iid, wwpn, name,
1485 		    (uintmax_t)port->wwpn_iid[iid].wwpn,
1486 		    port->wwpn_iid[iid].name);
1487 
1488 		/*
1489 		 * XXX KDM clear have_ca and ua_pending on each LUN for
1490 		 * this initiator.
1491 		 */
1492 	}
1493 take:
1494 	free(port->wwpn_iid[iid].name, M_CTL);
1495 	port->wwpn_iid[iid].name = name;
1496 	port->wwpn_iid[iid].wwpn = wwpn;
1497 	port->wwpn_iid[iid].in_use++;
1498 	mtx_unlock(&softc->ctl_lock);
1499 
1500 	return (iid);
1501 }
1502 
1503 static int
1504 ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
1505 {
1506 	int len;
1507 
1508 	switch (port->port_type) {
1509 	case CTL_PORT_FC:
1510 	{
1511 		struct scsi_transportid_fcp *id =
1512 		    (struct scsi_transportid_fcp *)buf;
1513 		if (port->wwpn_iid[iid].wwpn == 0)
1514 			return (0);
1515 		memset(id, 0, sizeof(*id));
1516 		id->format_protocol = SCSI_PROTO_FC;
1517 		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
1518 		return (sizeof(*id));
1519 	}
1520 	case CTL_PORT_ISCSI:
1521 	{
1522 		struct scsi_transportid_iscsi_port *id =
1523 		    (struct scsi_transportid_iscsi_port *)buf;
1524 		if (port->wwpn_iid[iid].name == NULL)
1525 			return (0);
1526 		memset(id, 0, 256);
1527 		id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
1528 		    SCSI_PROTO_ISCSI;
1529 		len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
1530 		len = roundup2(min(len, 252), 4);
1531 		scsi_ulto2b(len, id->additional_length);
1532 		return (sizeof(*id) + len);
1533 	}
1534 	case CTL_PORT_SAS:
1535 	{
1536 		struct scsi_transportid_sas *id =
1537 		    (struct scsi_transportid_sas *)buf;
1538 		if (port->wwpn_iid[iid].wwpn == 0)
1539 			return (0);
1540 		memset(id, 0, sizeof(*id));
1541 		id->format_protocol = SCSI_PROTO_SAS;
1542 		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
1543 		return (sizeof(*id));
1544 	}
1545 	default:
1546 	{
1547 		struct scsi_transportid_spi *id =
1548 		    (struct scsi_transportid_spi *)buf;
1549 		memset(id, 0, sizeof(*id));
1550 		id->format_protocol = SCSI_PROTO_SPI;
1551 		scsi_ulto2b(iid, id->scsi_addr);
1552 		scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
1553 		return (sizeof(*id));
1554 	}
1555 	}
1556 }
1557 
1558 static int
1559 ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id)
1560 {
1561 	return (0);
1562 }
1563 
1564 static int
1565 ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id)
1566 {
1567 	return (0);
1568 }
1569 
1570 /*
1571  * Data movement routine for the CTL ioctl frontend port.
1572  */
1573 static int
1574 ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio)
1575 {
1576 	struct ctl_sg_entry *ext_sglist, *kern_sglist;
1577 	struct ctl_sg_entry ext_entry, kern_entry;
1578 	int ext_sglen, ext_sg_entries, kern_sg_entries;
1579 	int ext_sg_start, ext_offset;
1580 	int len_to_copy, len_copied;
1581 	int kern_watermark, ext_watermark;
1582 	int ext_sglist_malloced;
1583 	int i, j;
1584 
1585 	ext_sglist_malloced = 0;
1586 	ext_sg_start = 0;
1587 	ext_offset = 0;
1588 
1589 	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove\n"));
1590 
1591 	/*
1592 	 * If this flag is set, fake the data transfer.
1593 	 */
1594 	if (ctsio->io_hdr.flags & CTL_FLAG_NO_DATAMOVE) {
1595 		ctsio->ext_data_filled = ctsio->ext_data_len;
1596 		goto bailout;
1597 	}
1598 
1599 	/*
1600 	 * To simplify things here, if we have a single buffer, stick it in
1601 	 * a S/G entry and just make it a single entry S/G list.
1602 	 */
1603 	if (ctsio->io_hdr.flags & CTL_FLAG_EDPTR_SGLIST) {
1604 		int len_seen;
1605 
1606 		ext_sglen = ctsio->ext_sg_entries * sizeof(*ext_sglist);
1607 
1608 		ext_sglist = (struct ctl_sg_entry *)malloc(ext_sglen, M_CTL,
1609 							   M_WAITOK);
1610 		ext_sglist_malloced = 1;
1611 		if (copyin(ctsio->ext_data_ptr, ext_sglist,
1612 				   ext_sglen) != 0) {
1613 			ctl_set_internal_failure(ctsio,
1614 						 /*sks_valid*/ 0,
1615 						 /*retry_count*/ 0);
1616 			goto bailout;
1617 		}
1618 		ext_sg_entries = ctsio->ext_sg_entries;
1619 		len_seen = 0;
1620 		for (i = 0; i < ext_sg_entries; i++) {
1621 			if ((len_seen + ext_sglist[i].len) >=
1622 			     ctsio->ext_data_filled) {
1623 				ext_sg_start = i;
1624 				ext_offset = ctsio->ext_data_filled - len_seen;
1625 				break;
1626 			}
1627 			len_seen += ext_sglist[i].len;
1628 		}
1629 	} else {
1630 		ext_sglist = &ext_entry;
1631 		ext_sglist->addr = ctsio->ext_data_ptr;
1632 		ext_sglist->len = ctsio->ext_data_len;
1633 		ext_sg_entries = 1;
1634 		ext_sg_start = 0;
1635 		ext_offset = ctsio->ext_data_filled;
1636 	}
1637 
1638 	if (ctsio->kern_sg_entries > 0) {
1639 		kern_sglist = (struct ctl_sg_entry *)ctsio->kern_data_ptr;
1640 		kern_sg_entries = ctsio->kern_sg_entries;
1641 	} else {
1642 		kern_sglist = &kern_entry;
1643 		kern_sglist->addr = ctsio->kern_data_ptr;
1644 		kern_sglist->len = ctsio->kern_data_len;
1645 		kern_sg_entries = 1;
1646 	}
1647 
1648 
1649 	kern_watermark = 0;
1650 	ext_watermark = ext_offset;
1651 	len_copied = 0;
1652 	for (i = ext_sg_start, j = 0;
1653 	     i < ext_sg_entries && j < kern_sg_entries;) {
1654 		uint8_t *ext_ptr, *kern_ptr;
1655 
1656 		len_to_copy = ctl_min(ext_sglist[i].len - ext_watermark,
1657 				      kern_sglist[j].len - kern_watermark);
1658 
1659 		ext_ptr = (uint8_t *)ext_sglist[i].addr;
1660 		ext_ptr = ext_ptr + ext_watermark;
1661 		if (ctsio->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
1662 			/*
1663 			 * XXX KDM fix this!
1664 			 */
1665 			panic("need to implement bus address support");
1666 #if 0
1667 			kern_ptr = bus_to_virt(kern_sglist[j].addr);
1668 #endif
1669 		} else
1670 			kern_ptr = (uint8_t *)kern_sglist[j].addr;
1671 		kern_ptr = kern_ptr + kern_watermark;
1672 
1673 		kern_watermark += len_to_copy;
1674 		ext_watermark += len_to_copy;
1675 
1676 		if ((ctsio->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
1677 		     CTL_FLAG_DATA_IN) {
1678 			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1679 					 "bytes to user\n", len_to_copy));
1680 			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1681 					 "to %p\n", kern_ptr, ext_ptr));
1682 			if (copyout(kern_ptr, ext_ptr, len_to_copy) != 0) {
1683 				ctl_set_internal_failure(ctsio,
1684 							 /*sks_valid*/ 0,
1685 							 /*retry_count*/ 0);
1686 				goto bailout;
1687 			}
1688 		} else {
1689 			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1690 					 "bytes from user\n", len_to_copy));
1691 			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1692 					 "to %p\n", ext_ptr, kern_ptr));
1693 			if (copyin(ext_ptr, kern_ptr, len_to_copy)!= 0){
1694 				ctl_set_internal_failure(ctsio,
1695 							 /*sks_valid*/ 0,
1696 							 /*retry_count*/0);
1697 				goto bailout;
1698 			}
1699 		}
1700 
1701 		len_copied += len_to_copy;
1702 
1703 		if (ext_sglist[i].len == ext_watermark) {
1704 			i++;
1705 			ext_watermark = 0;
1706 		}
1707 
1708 		if (kern_sglist[j].len == kern_watermark) {
1709 			j++;
1710 			kern_watermark = 0;
1711 		}
1712 	}
1713 
1714 	ctsio->ext_data_filled += len_copied;
1715 
1716 	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_sg_entries: %d, "
1717 			 "kern_sg_entries: %d\n", ext_sg_entries,
1718 			 kern_sg_entries));
1719 	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_data_len = %d, "
1720 			 "kern_data_len = %d\n", ctsio->ext_data_len,
1721 			 ctsio->kern_data_len));
1722 
1723 
1724 	/* XXX KDM set residual?? */
1725 bailout:
1726 
1727 	if (ext_sglist_malloced != 0)
1728 		free(ext_sglist, M_CTL);
1729 
1730 	return (CTL_RETVAL_COMPLETE);
1731 }
1732 
1733 /*
1734  * Serialize a command that went down the "wrong" side, and so was sent to
1735  * this controller for execution.  The logic is a little different than the
1736  * standard case in ctl_scsiio_precheck().  Errors in this case need to get
1737  * sent back to the other side, but in the success case, we execute the
1738  * command on this side (XFER mode) or tell the other side to execute it
1739  * (SER_ONLY mode).
1740  */
1741 static int
1742 ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
1743 {
1744 	struct ctl_softc *ctl_softc;
1745 	union ctl_ha_msg msg_info;
1746 	struct ctl_lun *lun;
1747 	int retval = 0;
1748 	uint32_t targ_lun;
1749 
1750 	ctl_softc = control_softc;
1751 
1752 	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
1753 	lun = ctl_softc->ctl_luns[targ_lun];
1754 	if (lun==NULL)
1755 	{
1756 		/*
1757 		 * Why isn't LUN defined? The other side wouldn't
1758 		 * send a cmd if the LUN is undefined.
1759 		 */
1760 		printf("%s: Bad JUJU!, LUN is NULL!\n", __func__);
1761 
1762 		/* "Logical unit not supported" */
1763 		ctl_set_sense_data(&msg_info.scsi.sense_data,
1764 				   lun,
1765 				   /*sense_format*/SSD_TYPE_NONE,
1766 				   /*current_error*/ 1,
1767 				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1768 				   /*asc*/ 0x25,
1769 				   /*ascq*/ 0x00,
1770 				   SSD_ELEM_NONE);
1771 
1772 		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1773 		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1774 		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1775 		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1776 		msg_info.hdr.serializing_sc = NULL;
1777 		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1778 	        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1779 				sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1780 		}
1781 		return(1);
1782 
1783 	}
1784 
1785 	mtx_lock(&lun->lun_lock);
1786     	TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1787 
1788 	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
1789 		(union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
1790 		 ooa_links))) {
1791 	case CTL_ACTION_BLOCK:
1792 		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
1793 		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
1794 				  blocked_links);
1795 		break;
1796 	case CTL_ACTION_PASS:
1797 	case CTL_ACTION_SKIP:
1798 		if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
1799 			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
1800 			ctl_enqueue_rtr((union ctl_io *)ctsio);
1801 		} else {
1802 
1803 			/* send msg back to other side */
1804 			msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1805 			msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
1806 			msg_info.hdr.msg_type = CTL_MSG_R2R;
1807 #if 0
1808 			printf("2. pOrig %x\n", (int)msg_info.hdr.original_sc);
1809 #endif
1810 		        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1811 			    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1812 			}
1813 		}
1814 		break;
1815 	case CTL_ACTION_OVERLAP:
1816 		/* OVERLAPPED COMMANDS ATTEMPTED */
1817 		ctl_set_sense_data(&msg_info.scsi.sense_data,
1818 				   lun,
1819 				   /*sense_format*/SSD_TYPE_NONE,
1820 				   /*current_error*/ 1,
1821 				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1822 				   /*asc*/ 0x4E,
1823 				   /*ascq*/ 0x00,
1824 				   SSD_ELEM_NONE);
1825 
1826 		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1827 		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1828 		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1829 		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1830 		msg_info.hdr.serializing_sc = NULL;
1831 		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1832 #if 0
1833 		printf("BAD JUJU:Major Bummer Overlap\n");
1834 #endif
1835 		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1836 		retval = 1;
1837 		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1838 		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1839 		}
1840 		break;
1841 	case CTL_ACTION_OVERLAP_TAG:
1842 		/* TAGGED OVERLAPPED COMMANDS (NN = QUEUE TAG) */
1843 		ctl_set_sense_data(&msg_info.scsi.sense_data,
1844 				   lun,
1845 				   /*sense_format*/SSD_TYPE_NONE,
1846 				   /*current_error*/ 1,
1847 				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1848 				   /*asc*/ 0x4D,
1849 				   /*ascq*/ ctsio->tag_num & 0xff,
1850 				   SSD_ELEM_NONE);
1851 
1852 		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1853 		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1854 		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1855 		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1856 		msg_info.hdr.serializing_sc = NULL;
1857 		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1858 #if 0
1859 		printf("BAD JUJU:Major Bummer Overlap Tag\n");
1860 #endif
1861 		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1862 		retval = 1;
1863 		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1864 		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1865 		}
1866 		break;
1867 	case CTL_ACTION_ERROR:
1868 	default:
1869 		/* "Internal target failure" */
1870 		ctl_set_sense_data(&msg_info.scsi.sense_data,
1871 				   lun,
1872 				   /*sense_format*/SSD_TYPE_NONE,
1873 				   /*current_error*/ 1,
1874 				   /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
1875 				   /*asc*/ 0x44,
1876 				   /*ascq*/ 0x00,
1877 				   SSD_ELEM_NONE);
1878 
1879 		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1880 		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1881 		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1882 		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1883 		msg_info.hdr.serializing_sc = NULL;
1884 		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1885 #if 0
1886 		printf("BAD JUJU:Major Bummer HW Error\n");
1887 #endif
1888 		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1889 		retval = 1;
1890 		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1891 		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1892 		}
1893 		break;
1894 	}
1895 	mtx_unlock(&lun->lun_lock);
1896 	return (retval);
1897 }
1898 
1899 static int
1900 ctl_ioctl_submit_wait(union ctl_io *io)
1901 {
1902 	struct ctl_fe_ioctl_params params;
1903 	ctl_fe_ioctl_state last_state;
1904 	int done, retval;
1905 
1906 	retval = 0;
1907 
1908 	bzero(&params, sizeof(params));
1909 
1910 	mtx_init(&params.ioctl_mtx, "ctliocmtx", NULL, MTX_DEF);
1911 	cv_init(&params.sem, "ctlioccv");
1912 	params.state = CTL_IOCTL_INPROG;
1913 	last_state = params.state;
1914 
1915 	io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr = &params;
1916 
1917 	CTL_DEBUG_PRINT(("ctl_ioctl_submit_wait\n"));
1918 
1919 	/* This shouldn't happen */
1920 	if ((retval = ctl_queue(io)) != CTL_RETVAL_COMPLETE)
1921 		return (retval);
1922 
1923 	done = 0;
1924 
1925 	do {
1926 		mtx_lock(&params.ioctl_mtx);
1927 		/*
1928 		 * Check the state here, and don't sleep if the state has
1929 		 * already changed (i.e. wakeup has already occured, but we
1930 		 * weren't waiting yet).
1931 		 */
1932 		if (params.state == last_state) {
1933 			/* XXX KDM cv_wait_sig instead? */
1934 			cv_wait(&params.sem, &params.ioctl_mtx);
1935 		}
1936 		last_state = params.state;
1937 
1938 		switch (params.state) {
1939 		case CTL_IOCTL_INPROG:
1940 			/* Why did we wake up? */
1941 			/* XXX KDM error here? */
1942 			mtx_unlock(&params.ioctl_mtx);
1943 			break;
1944 		case CTL_IOCTL_DATAMOVE:
1945 			CTL_DEBUG_PRINT(("got CTL_IOCTL_DATAMOVE\n"));
1946 
1947 			/*
1948 			 * change last_state back to INPROG to avoid
1949 			 * deadlock on subsequent data moves.
1950 			 */
1951 			params.state = last_state = CTL_IOCTL_INPROG;
1952 
1953 			mtx_unlock(&params.ioctl_mtx);
1954 			ctl_ioctl_do_datamove(&io->scsiio);
1955 			/*
1956 			 * Note that in some cases, most notably writes,
1957 			 * this will queue the I/O and call us back later.
1958 			 * In other cases, generally reads, this routine
1959 			 * will immediately call back and wake us up,
1960 			 * probably using our own context.
1961 			 */
1962 			io->scsiio.be_move_done(io);
1963 			break;
1964 		case CTL_IOCTL_DONE:
1965 			mtx_unlock(&params.ioctl_mtx);
1966 			CTL_DEBUG_PRINT(("got CTL_IOCTL_DONE\n"));
1967 			done = 1;
1968 			break;
1969 		default:
1970 			mtx_unlock(&params.ioctl_mtx);
1971 			/* XXX KDM error here? */
1972 			break;
1973 		}
1974 	} while (done == 0);
1975 
1976 	mtx_destroy(&params.ioctl_mtx);
1977 	cv_destroy(&params.sem);
1978 
1979 	return (CTL_RETVAL_COMPLETE);
1980 }
1981 
1982 static void
1983 ctl_ioctl_datamove(union ctl_io *io)
1984 {
1985 	struct ctl_fe_ioctl_params *params;
1986 
1987 	params = (struct ctl_fe_ioctl_params *)
1988 		io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
1989 
1990 	mtx_lock(&params->ioctl_mtx);
1991 	params->state = CTL_IOCTL_DATAMOVE;
1992 	cv_broadcast(&params->sem);
1993 	mtx_unlock(&params->ioctl_mtx);
1994 }
1995 
1996 static void
1997 ctl_ioctl_done(union ctl_io *io)
1998 {
1999 	struct ctl_fe_ioctl_params *params;
2000 
2001 	params = (struct ctl_fe_ioctl_params *)
2002 		io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2003 
2004 	mtx_lock(&params->ioctl_mtx);
2005 	params->state = CTL_IOCTL_DONE;
2006 	cv_broadcast(&params->sem);
2007 	mtx_unlock(&params->ioctl_mtx);
2008 }
2009 
2010 static void
2011 ctl_ioctl_hard_startstop_callback(void *arg, struct cfi_metatask *metatask)
2012 {
2013 	struct ctl_fe_ioctl_startstop_info *sd_info;
2014 
2015 	sd_info = (struct ctl_fe_ioctl_startstop_info *)arg;
2016 
2017 	sd_info->hs_info.status = metatask->status;
2018 	sd_info->hs_info.total_luns = metatask->taskinfo.startstop.total_luns;
2019 	sd_info->hs_info.luns_complete =
2020 		metatask->taskinfo.startstop.luns_complete;
2021 	sd_info->hs_info.luns_failed = metatask->taskinfo.startstop.luns_failed;
2022 
2023 	cv_broadcast(&sd_info->sem);
2024 }
2025 
2026 static void
2027 ctl_ioctl_bbrread_callback(void *arg, struct cfi_metatask *metatask)
2028 {
2029 	struct ctl_fe_ioctl_bbrread_info *fe_bbr_info;
2030 
2031 	fe_bbr_info = (struct ctl_fe_ioctl_bbrread_info *)arg;
2032 
2033 	mtx_lock(fe_bbr_info->lock);
2034 	fe_bbr_info->bbr_info->status = metatask->status;
2035 	fe_bbr_info->bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2036 	fe_bbr_info->wakeup_done = 1;
2037 	mtx_unlock(fe_bbr_info->lock);
2038 
2039 	cv_broadcast(&fe_bbr_info->sem);
2040 }
2041 
2042 /*
2043  * Returns 0 for success, errno for failure.
2044  */
2045 static int
2046 ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2047 		   struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2048 {
2049 	union ctl_io *io;
2050 	int retval;
2051 
2052 	retval = 0;
2053 
2054 	mtx_lock(&lun->lun_lock);
2055 	for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
2056 	     (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2057 	     ooa_links)) {
2058 		struct ctl_ooa_entry *entry;
2059 
2060 		/*
2061 		 * If we've got more than we can fit, just count the
2062 		 * remaining entries.
2063 		 */
2064 		if (*cur_fill_num >= ooa_hdr->alloc_num)
2065 			continue;
2066 
2067 		entry = &kern_entries[*cur_fill_num];
2068 
2069 		entry->tag_num = io->scsiio.tag_num;
2070 		entry->lun_num = lun->lun;
2071 #ifdef CTL_TIME_IO
2072 		entry->start_bt = io->io_hdr.start_bt;
2073 #endif
2074 		bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2075 		entry->cdb_len = io->scsiio.cdb_len;
2076 		if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
2077 			entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2078 
2079 		if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2080 			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2081 
2082 		if (io->io_hdr.flags & CTL_FLAG_ABORT)
2083 			entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2084 
2085 		if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2086 			entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2087 
2088 		if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2089 			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2090 	}
2091 	mtx_unlock(&lun->lun_lock);
2092 
2093 	return (retval);
2094 }
2095 
2096 static void *
2097 ctl_copyin_alloc(void *user_addr, int len, char *error_str,
2098 		 size_t error_str_len)
2099 {
2100 	void *kptr;
2101 
2102 	kptr = malloc(len, M_CTL, M_WAITOK | M_ZERO);
2103 
2104 	if (copyin(user_addr, kptr, len) != 0) {
2105 		snprintf(error_str, error_str_len, "Error copying %d bytes "
2106 			 "from user address %p to kernel address %p", len,
2107 			 user_addr, kptr);
2108 		free(kptr, M_CTL);
2109 		return (NULL);
2110 	}
2111 
2112 	return (kptr);
2113 }
2114 
2115 static void
2116 ctl_free_args(int num_args, struct ctl_be_arg *args)
2117 {
2118 	int i;
2119 
2120 	if (args == NULL)
2121 		return;
2122 
2123 	for (i = 0; i < num_args; i++) {
2124 		free(args[i].kname, M_CTL);
2125 		free(args[i].kvalue, M_CTL);
2126 	}
2127 
2128 	free(args, M_CTL);
2129 }
2130 
2131 static struct ctl_be_arg *
2132 ctl_copyin_args(int num_args, struct ctl_be_arg *uargs,
2133 		char *error_str, size_t error_str_len)
2134 {
2135 	struct ctl_be_arg *args;
2136 	int i;
2137 
2138 	args = ctl_copyin_alloc(uargs, num_args * sizeof(*args),
2139 				error_str, error_str_len);
2140 
2141 	if (args == NULL)
2142 		goto bailout;
2143 
2144 	for (i = 0; i < num_args; i++) {
2145 		args[i].kname = NULL;
2146 		args[i].kvalue = NULL;
2147 	}
2148 
2149 	for (i = 0; i < num_args; i++) {
2150 		uint8_t *tmpptr;
2151 
2152 		args[i].kname = ctl_copyin_alloc(args[i].name,
2153 			args[i].namelen, error_str, error_str_len);
2154 		if (args[i].kname == NULL)
2155 			goto bailout;
2156 
2157 		if (args[i].kname[args[i].namelen - 1] != '\0') {
2158 			snprintf(error_str, error_str_len, "Argument %d "
2159 				 "name is not NUL-terminated", i);
2160 			goto bailout;
2161 		}
2162 
2163 		if (args[i].flags & CTL_BEARG_RD) {
2164 			tmpptr = ctl_copyin_alloc(args[i].value,
2165 				args[i].vallen, error_str, error_str_len);
2166 			if (tmpptr == NULL)
2167 				goto bailout;
2168 			if ((args[i].flags & CTL_BEARG_ASCII)
2169 			 && (tmpptr[args[i].vallen - 1] != '\0')) {
2170 				snprintf(error_str, error_str_len, "Argument "
2171 				    "%d value is not NUL-terminated", i);
2172 				goto bailout;
2173 			}
2174 			args[i].kvalue = tmpptr;
2175 		} else {
2176 			args[i].kvalue = malloc(args[i].vallen,
2177 			    M_CTL, M_WAITOK | M_ZERO);
2178 		}
2179 	}
2180 
2181 	return (args);
2182 bailout:
2183 
2184 	ctl_free_args(num_args, args);
2185 
2186 	return (NULL);
2187 }
2188 
2189 static void
2190 ctl_copyout_args(int num_args, struct ctl_be_arg *args)
2191 {
2192 	int i;
2193 
2194 	for (i = 0; i < num_args; i++) {
2195 		if (args[i].flags & CTL_BEARG_WR)
2196 			copyout(args[i].kvalue, args[i].value, args[i].vallen);
2197 	}
2198 }
2199 
2200 /*
2201  * Escape characters that are illegal or not recommended in XML.
2202  */
2203 int
2204 ctl_sbuf_printf_esc(struct sbuf *sb, char *str)
2205 {
2206 	int retval;
2207 
2208 	retval = 0;
2209 
2210 	for (; *str; str++) {
2211 		switch (*str) {
2212 		case '&':
2213 			retval = sbuf_printf(sb, "&amp;");
2214 			break;
2215 		case '>':
2216 			retval = sbuf_printf(sb, "&gt;");
2217 			break;
2218 		case '<':
2219 			retval = sbuf_printf(sb, "&lt;");
2220 			break;
2221 		default:
2222 			retval = sbuf_putc(sb, *str);
2223 			break;
2224 		}
2225 
2226 		if (retval != 0)
2227 			break;
2228 
2229 	}
2230 
2231 	return (retval);
2232 }
2233 
2234 static int
2235 ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2236 	  struct thread *td)
2237 {
2238 	struct ctl_softc *softc;
2239 	int retval;
2240 
2241 	softc = control_softc;
2242 
2243 	retval = 0;
2244 
2245 	switch (cmd) {
2246 	case CTL_IO: {
2247 		union ctl_io *io;
2248 		void *pool_tmp;
2249 
2250 		/*
2251 		 * If we haven't been "enabled", don't allow any SCSI I/O
2252 		 * to this FETD.
2253 		 */
2254 		if ((softc->ioctl_info.flags & CTL_IOCTL_FLAG_ENABLED) == 0) {
2255 			retval = EPERM;
2256 			break;
2257 		}
2258 
2259 		io = ctl_alloc_io(softc->ioctl_info.port.ctl_pool_ref);
2260 		if (io == NULL) {
2261 			printf("ctl_ioctl: can't allocate ctl_io!\n");
2262 			retval = ENOSPC;
2263 			break;
2264 		}
2265 
2266 		/*
2267 		 * Need to save the pool reference so it doesn't get
2268 		 * spammed by the user's ctl_io.
2269 		 */
2270 		pool_tmp = io->io_hdr.pool;
2271 
2272 		memcpy(io, (void *)addr, sizeof(*io));
2273 
2274 		io->io_hdr.pool = pool_tmp;
2275 		/*
2276 		 * No status yet, so make sure the status is set properly.
2277 		 */
2278 		io->io_hdr.status = CTL_STATUS_NONE;
2279 
2280 		/*
2281 		 * The user sets the initiator ID, target and LUN IDs.
2282 		 */
2283 		io->io_hdr.nexus.targ_port = softc->ioctl_info.port.targ_port;
2284 		io->io_hdr.flags |= CTL_FLAG_USER_REQ;
2285 		if ((io->io_hdr.io_type == CTL_IO_SCSI)
2286 		 && (io->scsiio.tag_type != CTL_TAG_UNTAGGED))
2287 			io->scsiio.tag_num = softc->ioctl_info.cur_tag_num++;
2288 
2289 		retval = ctl_ioctl_submit_wait(io);
2290 
2291 		if (retval != 0) {
2292 			ctl_free_io(io);
2293 			break;
2294 		}
2295 
2296 		memcpy((void *)addr, io, sizeof(*io));
2297 
2298 		/* return this to our pool */
2299 		ctl_free_io(io);
2300 
2301 		break;
2302 	}
2303 	case CTL_ENABLE_PORT:
2304 	case CTL_DISABLE_PORT:
2305 	case CTL_SET_PORT_WWNS: {
2306 		struct ctl_port *port;
2307 		struct ctl_port_entry *entry;
2308 
2309 		entry = (struct ctl_port_entry *)addr;
2310 
2311 		mtx_lock(&softc->ctl_lock);
2312 		STAILQ_FOREACH(port, &softc->port_list, links) {
2313 			int action, done;
2314 
2315 			action = 0;
2316 			done = 0;
2317 
2318 			if ((entry->port_type == CTL_PORT_NONE)
2319 			 && (entry->targ_port == port->targ_port)) {
2320 				/*
2321 				 * If the user only wants to enable or
2322 				 * disable or set WWNs on a specific port,
2323 				 * do the operation and we're done.
2324 				 */
2325 				action = 1;
2326 				done = 1;
2327 			} else if (entry->port_type & port->port_type) {
2328 				/*
2329 				 * Compare the user's type mask with the
2330 				 * particular frontend type to see if we
2331 				 * have a match.
2332 				 */
2333 				action = 1;
2334 				done = 0;
2335 
2336 				/*
2337 				 * Make sure the user isn't trying to set
2338 				 * WWNs on multiple ports at the same time.
2339 				 */
2340 				if (cmd == CTL_SET_PORT_WWNS) {
2341 					printf("%s: Can't set WWNs on "
2342 					       "multiple ports\n", __func__);
2343 					retval = EINVAL;
2344 					break;
2345 				}
2346 			}
2347 			if (action != 0) {
2348 				/*
2349 				 * XXX KDM we have to drop the lock here,
2350 				 * because the online/offline operations
2351 				 * can potentially block.  We need to
2352 				 * reference count the frontends so they
2353 				 * can't go away,
2354 				 */
2355 				mtx_unlock(&softc->ctl_lock);
2356 
2357 				if (cmd == CTL_ENABLE_PORT) {
2358 					struct ctl_lun *lun;
2359 
2360 					STAILQ_FOREACH(lun, &softc->lun_list,
2361 						       links) {
2362 						port->lun_enable(port->targ_lun_arg,
2363 						    lun->target,
2364 						    lun->lun);
2365 					}
2366 
2367 					ctl_port_online(port);
2368 				} else if (cmd == CTL_DISABLE_PORT) {
2369 					struct ctl_lun *lun;
2370 
2371 					ctl_port_offline(port);
2372 
2373 					STAILQ_FOREACH(lun, &softc->lun_list,
2374 						       links) {
2375 						port->lun_disable(
2376 						    port->targ_lun_arg,
2377 						    lun->target,
2378 						    lun->lun);
2379 					}
2380 				}
2381 
2382 				mtx_lock(&softc->ctl_lock);
2383 
2384 				if (cmd == CTL_SET_PORT_WWNS)
2385 					ctl_port_set_wwns(port,
2386 					    (entry->flags & CTL_PORT_WWNN_VALID) ?
2387 					    1 : 0, entry->wwnn,
2388 					    (entry->flags & CTL_PORT_WWPN_VALID) ?
2389 					    1 : 0, entry->wwpn);
2390 			}
2391 			if (done != 0)
2392 				break;
2393 		}
2394 		mtx_unlock(&softc->ctl_lock);
2395 		break;
2396 	}
2397 	case CTL_GET_PORT_LIST: {
2398 		struct ctl_port *port;
2399 		struct ctl_port_list *list;
2400 		int i;
2401 
2402 		list = (struct ctl_port_list *)addr;
2403 
2404 		if (list->alloc_len != (list->alloc_num *
2405 		    sizeof(struct ctl_port_entry))) {
2406 			printf("%s: CTL_GET_PORT_LIST: alloc_len %u != "
2407 			       "alloc_num %u * sizeof(struct ctl_port_entry) "
2408 			       "%zu\n", __func__, list->alloc_len,
2409 			       list->alloc_num, sizeof(struct ctl_port_entry));
2410 			retval = EINVAL;
2411 			break;
2412 		}
2413 		list->fill_len = 0;
2414 		list->fill_num = 0;
2415 		list->dropped_num = 0;
2416 		i = 0;
2417 		mtx_lock(&softc->ctl_lock);
2418 		STAILQ_FOREACH(port, &softc->port_list, links) {
2419 			struct ctl_port_entry entry, *list_entry;
2420 
2421 			if (list->fill_num >= list->alloc_num) {
2422 				list->dropped_num++;
2423 				continue;
2424 			}
2425 
2426 			entry.port_type = port->port_type;
2427 			strlcpy(entry.port_name, port->port_name,
2428 				sizeof(entry.port_name));
2429 			entry.targ_port = port->targ_port;
2430 			entry.physical_port = port->physical_port;
2431 			entry.virtual_port = port->virtual_port;
2432 			entry.wwnn = port->wwnn;
2433 			entry.wwpn = port->wwpn;
2434 			if (port->status & CTL_PORT_STATUS_ONLINE)
2435 				entry.online = 1;
2436 			else
2437 				entry.online = 0;
2438 
2439 			list_entry = &list->entries[i];
2440 
2441 			retval = copyout(&entry, list_entry, sizeof(entry));
2442 			if (retval != 0) {
2443 				printf("%s: CTL_GET_PORT_LIST: copyout "
2444 				       "returned %d\n", __func__, retval);
2445 				break;
2446 			}
2447 			i++;
2448 			list->fill_num++;
2449 			list->fill_len += sizeof(entry);
2450 		}
2451 		mtx_unlock(&softc->ctl_lock);
2452 
2453 		/*
2454 		 * If this is non-zero, we had a copyout fault, so there's
2455 		 * probably no point in attempting to set the status inside
2456 		 * the structure.
2457 		 */
2458 		if (retval != 0)
2459 			break;
2460 
2461 		if (list->dropped_num > 0)
2462 			list->status = CTL_PORT_LIST_NEED_MORE_SPACE;
2463 		else
2464 			list->status = CTL_PORT_LIST_OK;
2465 		break;
2466 	}
2467 	case CTL_DUMP_OOA: {
2468 		struct ctl_lun *lun;
2469 		union ctl_io *io;
2470 		char printbuf[128];
2471 		struct sbuf sb;
2472 
2473 		mtx_lock(&softc->ctl_lock);
2474 		printf("Dumping OOA queues:\n");
2475 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
2476 			mtx_lock(&lun->lun_lock);
2477 			for (io = (union ctl_io *)TAILQ_FIRST(
2478 			     &lun->ooa_queue); io != NULL;
2479 			     io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2480 			     ooa_links)) {
2481 				sbuf_new(&sb, printbuf, sizeof(printbuf),
2482 					 SBUF_FIXEDLEN);
2483 				sbuf_printf(&sb, "LUN %jd tag 0x%04x%s%s%s%s: ",
2484 					    (intmax_t)lun->lun,
2485 					    io->scsiio.tag_num,
2486 					    (io->io_hdr.flags &
2487 					    CTL_FLAG_BLOCKED) ? "" : " BLOCKED",
2488 					    (io->io_hdr.flags &
2489 					    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
2490 					    (io->io_hdr.flags &
2491 					    CTL_FLAG_ABORT) ? " ABORT" : "",
2492 			                    (io->io_hdr.flags &
2493 		                        CTL_FLAG_IS_WAS_ON_RTR) ? " RTR" : "");
2494 				ctl_scsi_command_string(&io->scsiio, NULL, &sb);
2495 				sbuf_finish(&sb);
2496 				printf("%s\n", sbuf_data(&sb));
2497 			}
2498 			mtx_unlock(&lun->lun_lock);
2499 		}
2500 		printf("OOA queues dump done\n");
2501 		mtx_unlock(&softc->ctl_lock);
2502 		break;
2503 	}
2504 	case CTL_GET_OOA: {
2505 		struct ctl_lun *lun;
2506 		struct ctl_ooa *ooa_hdr;
2507 		struct ctl_ooa_entry *entries;
2508 		uint32_t cur_fill_num;
2509 
2510 		ooa_hdr = (struct ctl_ooa *)addr;
2511 
2512 		if ((ooa_hdr->alloc_len == 0)
2513 		 || (ooa_hdr->alloc_num == 0)) {
2514 			printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2515 			       "must be non-zero\n", __func__,
2516 			       ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2517 			retval = EINVAL;
2518 			break;
2519 		}
2520 
2521 		if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2522 		    sizeof(struct ctl_ooa_entry))) {
2523 			printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2524 			       "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2525 			       __func__, ooa_hdr->alloc_len,
2526 			       ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2527 			retval = EINVAL;
2528 			break;
2529 		}
2530 
2531 		entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2532 		if (entries == NULL) {
2533 			printf("%s: could not allocate %d bytes for OOA "
2534 			       "dump\n", __func__, ooa_hdr->alloc_len);
2535 			retval = ENOMEM;
2536 			break;
2537 		}
2538 
2539 		mtx_lock(&softc->ctl_lock);
2540 		if (((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0)
2541 		 && ((ooa_hdr->lun_num > CTL_MAX_LUNS)
2542 		  || (softc->ctl_luns[ooa_hdr->lun_num] == NULL))) {
2543 			mtx_unlock(&softc->ctl_lock);
2544 			free(entries, M_CTL);
2545 			printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2546 			       __func__, (uintmax_t)ooa_hdr->lun_num);
2547 			retval = EINVAL;
2548 			break;
2549 		}
2550 
2551 		cur_fill_num = 0;
2552 
2553 		if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2554 			STAILQ_FOREACH(lun, &softc->lun_list, links) {
2555 				retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2556 					ooa_hdr, entries);
2557 				if (retval != 0)
2558 					break;
2559 			}
2560 			if (retval != 0) {
2561 				mtx_unlock(&softc->ctl_lock);
2562 				free(entries, M_CTL);
2563 				break;
2564 			}
2565 		} else {
2566 			lun = softc->ctl_luns[ooa_hdr->lun_num];
2567 
2568 			retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,ooa_hdr,
2569 						    entries);
2570 		}
2571 		mtx_unlock(&softc->ctl_lock);
2572 
2573 		ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2574 		ooa_hdr->fill_len = ooa_hdr->fill_num *
2575 			sizeof(struct ctl_ooa_entry);
2576 		retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2577 		if (retval != 0) {
2578 			printf("%s: error copying out %d bytes for OOA dump\n",
2579 			       __func__, ooa_hdr->fill_len);
2580 		}
2581 
2582 		getbintime(&ooa_hdr->cur_bt);
2583 
2584 		if (cur_fill_num > ooa_hdr->alloc_num) {
2585 			ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2586 			ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2587 		} else {
2588 			ooa_hdr->dropped_num = 0;
2589 			ooa_hdr->status = CTL_OOA_OK;
2590 		}
2591 
2592 		free(entries, M_CTL);
2593 		break;
2594 	}
2595 	case CTL_CHECK_OOA: {
2596 		union ctl_io *io;
2597 		struct ctl_lun *lun;
2598 		struct ctl_ooa_info *ooa_info;
2599 
2600 
2601 		ooa_info = (struct ctl_ooa_info *)addr;
2602 
2603 		if (ooa_info->lun_id >= CTL_MAX_LUNS) {
2604 			ooa_info->status = CTL_OOA_INVALID_LUN;
2605 			break;
2606 		}
2607 		mtx_lock(&softc->ctl_lock);
2608 		lun = softc->ctl_luns[ooa_info->lun_id];
2609 		if (lun == NULL) {
2610 			mtx_unlock(&softc->ctl_lock);
2611 			ooa_info->status = CTL_OOA_INVALID_LUN;
2612 			break;
2613 		}
2614 		mtx_lock(&lun->lun_lock);
2615 		mtx_unlock(&softc->ctl_lock);
2616 		ooa_info->num_entries = 0;
2617 		for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
2618 		     io != NULL; io = (union ctl_io *)TAILQ_NEXT(
2619 		     &io->io_hdr, ooa_links)) {
2620 			ooa_info->num_entries++;
2621 		}
2622 		mtx_unlock(&lun->lun_lock);
2623 
2624 		ooa_info->status = CTL_OOA_SUCCESS;
2625 
2626 		break;
2627 	}
2628 	case CTL_HARD_START:
2629 	case CTL_HARD_STOP: {
2630 		struct ctl_fe_ioctl_startstop_info ss_info;
2631 		struct cfi_metatask *metatask;
2632 		struct mtx hs_mtx;
2633 
2634 		mtx_init(&hs_mtx, "HS Mutex", NULL, MTX_DEF);
2635 
2636 		cv_init(&ss_info.sem, "hard start/stop cv" );
2637 
2638 		metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2639 		if (metatask == NULL) {
2640 			retval = ENOMEM;
2641 			mtx_destroy(&hs_mtx);
2642 			break;
2643 		}
2644 
2645 		if (cmd == CTL_HARD_START)
2646 			metatask->tasktype = CFI_TASK_STARTUP;
2647 		else
2648 			metatask->tasktype = CFI_TASK_SHUTDOWN;
2649 
2650 		metatask->callback = ctl_ioctl_hard_startstop_callback;
2651 		metatask->callback_arg = &ss_info;
2652 
2653 		cfi_action(metatask);
2654 
2655 		/* Wait for the callback */
2656 		mtx_lock(&hs_mtx);
2657 		cv_wait_sig(&ss_info.sem, &hs_mtx);
2658 		mtx_unlock(&hs_mtx);
2659 
2660 		/*
2661 		 * All information has been copied from the metatask by the
2662 		 * time cv_broadcast() is called, so we free the metatask here.
2663 		 */
2664 		cfi_free_metatask(metatask);
2665 
2666 		memcpy((void *)addr, &ss_info.hs_info, sizeof(ss_info.hs_info));
2667 
2668 		mtx_destroy(&hs_mtx);
2669 		break;
2670 	}
2671 	case CTL_BBRREAD: {
2672 		struct ctl_bbrread_info *bbr_info;
2673 		struct ctl_fe_ioctl_bbrread_info fe_bbr_info;
2674 		struct mtx bbr_mtx;
2675 		struct cfi_metatask *metatask;
2676 
2677 		bbr_info = (struct ctl_bbrread_info *)addr;
2678 
2679 		bzero(&fe_bbr_info, sizeof(fe_bbr_info));
2680 
2681 		bzero(&bbr_mtx, sizeof(bbr_mtx));
2682 		mtx_init(&bbr_mtx, "BBR Mutex", NULL, MTX_DEF);
2683 
2684 		fe_bbr_info.bbr_info = bbr_info;
2685 		fe_bbr_info.lock = &bbr_mtx;
2686 
2687 		cv_init(&fe_bbr_info.sem, "BBR read cv");
2688 		metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2689 
2690 		if (metatask == NULL) {
2691 			mtx_destroy(&bbr_mtx);
2692 			cv_destroy(&fe_bbr_info.sem);
2693 			retval = ENOMEM;
2694 			break;
2695 		}
2696 		metatask->tasktype = CFI_TASK_BBRREAD;
2697 		metatask->callback = ctl_ioctl_bbrread_callback;
2698 		metatask->callback_arg = &fe_bbr_info;
2699 		metatask->taskinfo.bbrread.lun_num = bbr_info->lun_num;
2700 		metatask->taskinfo.bbrread.lba = bbr_info->lba;
2701 		metatask->taskinfo.bbrread.len = bbr_info->len;
2702 
2703 		cfi_action(metatask);
2704 
2705 		mtx_lock(&bbr_mtx);
2706 		while (fe_bbr_info.wakeup_done == 0)
2707 			cv_wait_sig(&fe_bbr_info.sem, &bbr_mtx);
2708 		mtx_unlock(&bbr_mtx);
2709 
2710 		bbr_info->status = metatask->status;
2711 		bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2712 		bbr_info->scsi_status = metatask->taskinfo.bbrread.scsi_status;
2713 		memcpy(&bbr_info->sense_data,
2714 		       &metatask->taskinfo.bbrread.sense_data,
2715 		       ctl_min(sizeof(bbr_info->sense_data),
2716 			       sizeof(metatask->taskinfo.bbrread.sense_data)));
2717 
2718 		cfi_free_metatask(metatask);
2719 
2720 		mtx_destroy(&bbr_mtx);
2721 		cv_destroy(&fe_bbr_info.sem);
2722 
2723 		break;
2724 	}
2725 	case CTL_DELAY_IO: {
2726 		struct ctl_io_delay_info *delay_info;
2727 #ifdef CTL_IO_DELAY
2728 		struct ctl_lun *lun;
2729 #endif /* CTL_IO_DELAY */
2730 
2731 		delay_info = (struct ctl_io_delay_info *)addr;
2732 
2733 #ifdef CTL_IO_DELAY
2734 		mtx_lock(&softc->ctl_lock);
2735 
2736 		if ((delay_info->lun_id > CTL_MAX_LUNS)
2737 		 || (softc->ctl_luns[delay_info->lun_id] == NULL)) {
2738 			delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2739 		} else {
2740 			lun = softc->ctl_luns[delay_info->lun_id];
2741 			mtx_lock(&lun->lun_lock);
2742 
2743 			delay_info->status = CTL_DELAY_STATUS_OK;
2744 
2745 			switch (delay_info->delay_type) {
2746 			case CTL_DELAY_TYPE_CONT:
2747 				break;
2748 			case CTL_DELAY_TYPE_ONESHOT:
2749 				break;
2750 			default:
2751 				delay_info->status =
2752 					CTL_DELAY_STATUS_INVALID_TYPE;
2753 				break;
2754 			}
2755 
2756 			switch (delay_info->delay_loc) {
2757 			case CTL_DELAY_LOC_DATAMOVE:
2758 				lun->delay_info.datamove_type =
2759 					delay_info->delay_type;
2760 				lun->delay_info.datamove_delay =
2761 					delay_info->delay_secs;
2762 				break;
2763 			case CTL_DELAY_LOC_DONE:
2764 				lun->delay_info.done_type =
2765 					delay_info->delay_type;
2766 				lun->delay_info.done_delay =
2767 					delay_info->delay_secs;
2768 				break;
2769 			default:
2770 				delay_info->status =
2771 					CTL_DELAY_STATUS_INVALID_LOC;
2772 				break;
2773 			}
2774 			mtx_unlock(&lun->lun_lock);
2775 		}
2776 
2777 		mtx_unlock(&softc->ctl_lock);
2778 #else
2779 		delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2780 #endif /* CTL_IO_DELAY */
2781 		break;
2782 	}
2783 	case CTL_REALSYNC_SET: {
2784 		int *syncstate;
2785 
2786 		syncstate = (int *)addr;
2787 
2788 		mtx_lock(&softc->ctl_lock);
2789 		switch (*syncstate) {
2790 		case 0:
2791 			softc->flags &= ~CTL_FLAG_REAL_SYNC;
2792 			break;
2793 		case 1:
2794 			softc->flags |= CTL_FLAG_REAL_SYNC;
2795 			break;
2796 		default:
2797 			retval = EINVAL;
2798 			break;
2799 		}
2800 		mtx_unlock(&softc->ctl_lock);
2801 		break;
2802 	}
2803 	case CTL_REALSYNC_GET: {
2804 		int *syncstate;
2805 
2806 		syncstate = (int*)addr;
2807 
2808 		mtx_lock(&softc->ctl_lock);
2809 		if (softc->flags & CTL_FLAG_REAL_SYNC)
2810 			*syncstate = 1;
2811 		else
2812 			*syncstate = 0;
2813 		mtx_unlock(&softc->ctl_lock);
2814 
2815 		break;
2816 	}
2817 	case CTL_SETSYNC:
2818 	case CTL_GETSYNC: {
2819 		struct ctl_sync_info *sync_info;
2820 		struct ctl_lun *lun;
2821 
2822 		sync_info = (struct ctl_sync_info *)addr;
2823 
2824 		mtx_lock(&softc->ctl_lock);
2825 		lun = softc->ctl_luns[sync_info->lun_id];
2826 		if (lun == NULL) {
2827 			mtx_unlock(&softc->ctl_lock);
2828 			sync_info->status = CTL_GS_SYNC_NO_LUN;
2829 		}
2830 		/*
2831 		 * Get or set the sync interval.  We're not bounds checking
2832 		 * in the set case, hopefully the user won't do something
2833 		 * silly.
2834 		 */
2835 		mtx_lock(&lun->lun_lock);
2836 		mtx_unlock(&softc->ctl_lock);
2837 		if (cmd == CTL_GETSYNC)
2838 			sync_info->sync_interval = lun->sync_interval;
2839 		else
2840 			lun->sync_interval = sync_info->sync_interval;
2841 		mtx_unlock(&lun->lun_lock);
2842 
2843 		sync_info->status = CTL_GS_SYNC_OK;
2844 
2845 		break;
2846 	}
2847 	case CTL_GETSTATS: {
2848 		struct ctl_stats *stats;
2849 		struct ctl_lun *lun;
2850 		int i;
2851 
2852 		stats = (struct ctl_stats *)addr;
2853 
2854 		if ((sizeof(struct ctl_lun_io_stats) * softc->num_luns) >
2855 		     stats->alloc_len) {
2856 			stats->status = CTL_SS_NEED_MORE_SPACE;
2857 			stats->num_luns = softc->num_luns;
2858 			break;
2859 		}
2860 		/*
2861 		 * XXX KDM no locking here.  If the LUN list changes,
2862 		 * things can blow up.
2863 		 */
2864 		for (i = 0, lun = STAILQ_FIRST(&softc->lun_list); lun != NULL;
2865 		     i++, lun = STAILQ_NEXT(lun, links)) {
2866 			retval = copyout(&lun->stats, &stats->lun_stats[i],
2867 					 sizeof(lun->stats));
2868 			if (retval != 0)
2869 				break;
2870 		}
2871 		stats->num_luns = softc->num_luns;
2872 		stats->fill_len = sizeof(struct ctl_lun_io_stats) *
2873 				 softc->num_luns;
2874 		stats->status = CTL_SS_OK;
2875 #ifdef CTL_TIME_IO
2876 		stats->flags = CTL_STATS_FLAG_TIME_VALID;
2877 #else
2878 		stats->flags = CTL_STATS_FLAG_NONE;
2879 #endif
2880 		getnanouptime(&stats->timestamp);
2881 		break;
2882 	}
2883 	case CTL_ERROR_INJECT: {
2884 		struct ctl_error_desc *err_desc, *new_err_desc;
2885 		struct ctl_lun *lun;
2886 
2887 		err_desc = (struct ctl_error_desc *)addr;
2888 
2889 		new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2890 				      M_WAITOK | M_ZERO);
2891 		bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2892 
2893 		mtx_lock(&softc->ctl_lock);
2894 		lun = softc->ctl_luns[err_desc->lun_id];
2895 		if (lun == NULL) {
2896 			mtx_unlock(&softc->ctl_lock);
2897 			printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
2898 			       __func__, (uintmax_t)err_desc->lun_id);
2899 			retval = EINVAL;
2900 			break;
2901 		}
2902 		mtx_lock(&lun->lun_lock);
2903 		mtx_unlock(&softc->ctl_lock);
2904 
2905 		/*
2906 		 * We could do some checking here to verify the validity
2907 		 * of the request, but given the complexity of error
2908 		 * injection requests, the checking logic would be fairly
2909 		 * complex.
2910 		 *
2911 		 * For now, if the request is invalid, it just won't get
2912 		 * executed and might get deleted.
2913 		 */
2914 		STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
2915 
2916 		/*
2917 		 * XXX KDM check to make sure the serial number is unique,
2918 		 * in case we somehow manage to wrap.  That shouldn't
2919 		 * happen for a very long time, but it's the right thing to
2920 		 * do.
2921 		 */
2922 		new_err_desc->serial = lun->error_serial;
2923 		err_desc->serial = lun->error_serial;
2924 		lun->error_serial++;
2925 
2926 		mtx_unlock(&lun->lun_lock);
2927 		break;
2928 	}
2929 	case CTL_ERROR_INJECT_DELETE: {
2930 		struct ctl_error_desc *delete_desc, *desc, *desc2;
2931 		struct ctl_lun *lun;
2932 		int delete_done;
2933 
2934 		delete_desc = (struct ctl_error_desc *)addr;
2935 		delete_done = 0;
2936 
2937 		mtx_lock(&softc->ctl_lock);
2938 		lun = softc->ctl_luns[delete_desc->lun_id];
2939 		if (lun == NULL) {
2940 			mtx_unlock(&softc->ctl_lock);
2941 			printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
2942 			       __func__, (uintmax_t)delete_desc->lun_id);
2943 			retval = EINVAL;
2944 			break;
2945 		}
2946 		mtx_lock(&lun->lun_lock);
2947 		mtx_unlock(&softc->ctl_lock);
2948 		STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
2949 			if (desc->serial != delete_desc->serial)
2950 				continue;
2951 
2952 			STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
2953 				      links);
2954 			free(desc, M_CTL);
2955 			delete_done = 1;
2956 		}
2957 		mtx_unlock(&lun->lun_lock);
2958 		if (delete_done == 0) {
2959 			printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
2960 			       "error serial %ju on LUN %u\n", __func__,
2961 			       delete_desc->serial, delete_desc->lun_id);
2962 			retval = EINVAL;
2963 			break;
2964 		}
2965 		break;
2966 	}
2967 	case CTL_DUMP_STRUCTS: {
2968 		int i, j, k, idx;
2969 		struct ctl_port *port;
2970 		struct ctl_frontend *fe;
2971 
2972 		mtx_lock(&softc->ctl_lock);
2973 		printf("CTL Persistent Reservation information start:\n");
2974 		for (i = 0; i < CTL_MAX_LUNS; i++) {
2975 			struct ctl_lun *lun;
2976 
2977 			lun = softc->ctl_luns[i];
2978 
2979 			if ((lun == NULL)
2980 			 || ((lun->flags & CTL_LUN_DISABLED) != 0))
2981 				continue;
2982 
2983 			for (j = 0; j < (CTL_MAX_PORTS * 2); j++) {
2984 				for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
2985 					idx = j * CTL_MAX_INIT_PER_PORT + k;
2986 					if (lun->per_res[idx].registered == 0)
2987 						continue;
2988 					printf("  LUN %d port %d iid %d key "
2989 					       "%#jx\n", i, j, k,
2990 					       (uintmax_t)scsi_8btou64(
2991 					       lun->per_res[idx].res_key.key));
2992 				}
2993 			}
2994 		}
2995 		printf("CTL Persistent Reservation information end\n");
2996 		printf("CTL Ports:\n");
2997 		STAILQ_FOREACH(port, &softc->port_list, links) {
2998 			printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
2999 			       "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
3000 			       port->frontend->name, port->port_type,
3001 			       port->physical_port, port->virtual_port,
3002 			       (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
3003 			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3004 				if (port->wwpn_iid[j].in_use == 0 &&
3005 				    port->wwpn_iid[j].wwpn == 0 &&
3006 				    port->wwpn_iid[j].name == NULL)
3007 					continue;
3008 
3009 				printf("    iid %u use %d WWPN %#jx '%s'\n",
3010 				    j, port->wwpn_iid[j].in_use,
3011 				    (uintmax_t)port->wwpn_iid[j].wwpn,
3012 				    port->wwpn_iid[j].name);
3013 			}
3014 		}
3015 		printf("CTL Port information end\n");
3016 		mtx_unlock(&softc->ctl_lock);
3017 		/*
3018 		 * XXX KDM calling this without a lock.  We'd likely want
3019 		 * to drop the lock before calling the frontend's dump
3020 		 * routine anyway.
3021 		 */
3022 		printf("CTL Frontends:\n");
3023 		STAILQ_FOREACH(fe, &softc->fe_list, links) {
3024 			printf("  Frontend '%s'\n", fe->name);
3025 			if (fe->fe_dump != NULL)
3026 				fe->fe_dump();
3027 		}
3028 		printf("CTL Frontend information end\n");
3029 		break;
3030 	}
3031 	case CTL_LUN_REQ: {
3032 		struct ctl_lun_req *lun_req;
3033 		struct ctl_backend_driver *backend;
3034 
3035 		lun_req = (struct ctl_lun_req *)addr;
3036 
3037 		backend = ctl_backend_find(lun_req->backend);
3038 		if (backend == NULL) {
3039 			lun_req->status = CTL_LUN_ERROR;
3040 			snprintf(lun_req->error_str,
3041 				 sizeof(lun_req->error_str),
3042 				 "Backend \"%s\" not found.",
3043 				 lun_req->backend);
3044 			break;
3045 		}
3046 		if (lun_req->num_be_args > 0) {
3047 			lun_req->kern_be_args = ctl_copyin_args(
3048 				lun_req->num_be_args,
3049 				lun_req->be_args,
3050 				lun_req->error_str,
3051 				sizeof(lun_req->error_str));
3052 			if (lun_req->kern_be_args == NULL) {
3053 				lun_req->status = CTL_LUN_ERROR;
3054 				break;
3055 			}
3056 		}
3057 
3058 		retval = backend->ioctl(dev, cmd, addr, flag, td);
3059 
3060 		if (lun_req->num_be_args > 0) {
3061 			ctl_copyout_args(lun_req->num_be_args,
3062 				      lun_req->kern_be_args);
3063 			ctl_free_args(lun_req->num_be_args,
3064 				      lun_req->kern_be_args);
3065 		}
3066 		break;
3067 	}
3068 	case CTL_LUN_LIST: {
3069 		struct sbuf *sb;
3070 		struct ctl_lun *lun;
3071 		struct ctl_lun_list *list;
3072 		struct ctl_option *opt;
3073 
3074 		list = (struct ctl_lun_list *)addr;
3075 
3076 		/*
3077 		 * Allocate a fixed length sbuf here, based on the length
3078 		 * of the user's buffer.  We could allocate an auto-extending
3079 		 * buffer, and then tell the user how much larger our
3080 		 * amount of data is than his buffer, but that presents
3081 		 * some problems:
3082 		 *
3083 		 * 1.  The sbuf(9) routines use a blocking malloc, and so
3084 		 *     we can't hold a lock while calling them with an
3085 		 *     auto-extending buffer.
3086  		 *
3087 		 * 2.  There is not currently a LUN reference counting
3088 		 *     mechanism, outside of outstanding transactions on
3089 		 *     the LUN's OOA queue.  So a LUN could go away on us
3090 		 *     while we're getting the LUN number, backend-specific
3091 		 *     information, etc.  Thus, given the way things
3092 		 *     currently work, we need to hold the CTL lock while
3093 		 *     grabbing LUN information.
3094 		 *
3095 		 * So, from the user's standpoint, the best thing to do is
3096 		 * allocate what he thinks is a reasonable buffer length,
3097 		 * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
3098 		 * double the buffer length and try again.  (And repeat
3099 		 * that until he succeeds.)
3100 		 */
3101 		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3102 		if (sb == NULL) {
3103 			list->status = CTL_LUN_LIST_ERROR;
3104 			snprintf(list->error_str, sizeof(list->error_str),
3105 				 "Unable to allocate %d bytes for LUN list",
3106 				 list->alloc_len);
3107 			break;
3108 		}
3109 
3110 		sbuf_printf(sb, "<ctllunlist>\n");
3111 
3112 		mtx_lock(&softc->ctl_lock);
3113 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
3114 			mtx_lock(&lun->lun_lock);
3115 			retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3116 					     (uintmax_t)lun->lun);
3117 
3118 			/*
3119 			 * Bail out as soon as we see that we've overfilled
3120 			 * the buffer.
3121 			 */
3122 			if (retval != 0)
3123 				break;
3124 
3125 			retval = sbuf_printf(sb, "\t<backend_type>%s"
3126 					     "</backend_type>\n",
3127 					     (lun->backend == NULL) ?  "none" :
3128 					     lun->backend->name);
3129 
3130 			if (retval != 0)
3131 				break;
3132 
3133 			retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3134 					     lun->be_lun->lun_type);
3135 
3136 			if (retval != 0)
3137 				break;
3138 
3139 			if (lun->backend == NULL) {
3140 				retval = sbuf_printf(sb, "</lun>\n");
3141 				if (retval != 0)
3142 					break;
3143 				continue;
3144 			}
3145 
3146 			retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3147 					     (lun->be_lun->maxlba > 0) ?
3148 					     lun->be_lun->maxlba + 1 : 0);
3149 
3150 			if (retval != 0)
3151 				break;
3152 
3153 			retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3154 					     lun->be_lun->blocksize);
3155 
3156 			if (retval != 0)
3157 				break;
3158 
3159 			retval = sbuf_printf(sb, "\t<serial_number>");
3160 
3161 			if (retval != 0)
3162 				break;
3163 
3164 			retval = ctl_sbuf_printf_esc(sb,
3165 						     lun->be_lun->serial_num);
3166 
3167 			if (retval != 0)
3168 				break;
3169 
3170 			retval = sbuf_printf(sb, "</serial_number>\n");
3171 
3172 			if (retval != 0)
3173 				break;
3174 
3175 			retval = sbuf_printf(sb, "\t<device_id>");
3176 
3177 			if (retval != 0)
3178 				break;
3179 
3180 			retval = ctl_sbuf_printf_esc(sb,lun->be_lun->device_id);
3181 
3182 			if (retval != 0)
3183 				break;
3184 
3185 			retval = sbuf_printf(sb, "</device_id>\n");
3186 
3187 			if (retval != 0)
3188 				break;
3189 
3190 			if (lun->backend->lun_info != NULL) {
3191 				retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
3192 				if (retval != 0)
3193 					break;
3194 			}
3195 			STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
3196 				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3197 				    opt->name, opt->value, opt->name);
3198 				if (retval != 0)
3199 					break;
3200 			}
3201 
3202 			retval = sbuf_printf(sb, "</lun>\n");
3203 
3204 			if (retval != 0)
3205 				break;
3206 			mtx_unlock(&lun->lun_lock);
3207 		}
3208 		if (lun != NULL)
3209 			mtx_unlock(&lun->lun_lock);
3210 		mtx_unlock(&softc->ctl_lock);
3211 
3212 		if ((retval != 0)
3213 		 || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3214 			retval = 0;
3215 			sbuf_delete(sb);
3216 			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3217 			snprintf(list->error_str, sizeof(list->error_str),
3218 				 "Out of space, %d bytes is too small",
3219 				 list->alloc_len);
3220 			break;
3221 		}
3222 
3223 		sbuf_finish(sb);
3224 
3225 		retval = copyout(sbuf_data(sb), list->lun_xml,
3226 				 sbuf_len(sb) + 1);
3227 
3228 		list->fill_len = sbuf_len(sb) + 1;
3229 		list->status = CTL_LUN_LIST_OK;
3230 		sbuf_delete(sb);
3231 		break;
3232 	}
3233 	case CTL_ISCSI: {
3234 		struct ctl_iscsi *ci;
3235 		struct ctl_frontend *fe;
3236 
3237 		ci = (struct ctl_iscsi *)addr;
3238 
3239 		fe = ctl_frontend_find("iscsi");
3240 		if (fe == NULL) {
3241 			ci->status = CTL_ISCSI_ERROR;
3242 			snprintf(ci->error_str, sizeof(ci->error_str),
3243 			    "Frontend \"iscsi\" not found.");
3244 			break;
3245 		}
3246 
3247 		retval = fe->ioctl(dev, cmd, addr, flag, td);
3248 		break;
3249 	}
3250 	case CTL_PORT_REQ: {
3251 		struct ctl_req *req;
3252 		struct ctl_frontend *fe;
3253 
3254 		req = (struct ctl_req *)addr;
3255 
3256 		fe = ctl_frontend_find(req->driver);
3257 		if (fe == NULL) {
3258 			req->status = CTL_LUN_ERROR;
3259 			snprintf(req->error_str, sizeof(req->error_str),
3260 			    "Frontend \"%s\" not found.", req->driver);
3261 			break;
3262 		}
3263 		if (req->num_args > 0) {
3264 			req->kern_args = ctl_copyin_args(req->num_args,
3265 			    req->args, req->error_str, sizeof(req->error_str));
3266 			if (req->kern_args == NULL) {
3267 				req->status = CTL_LUN_ERROR;
3268 				break;
3269 			}
3270 		}
3271 
3272 		retval = fe->ioctl(dev, cmd, addr, flag, td);
3273 
3274 		if (req->num_args > 0) {
3275 			ctl_copyout_args(req->num_args, req->kern_args);
3276 			ctl_free_args(req->num_args, req->kern_args);
3277 		}
3278 		break;
3279 	}
3280 	case CTL_PORT_LIST: {
3281 		struct sbuf *sb;
3282 		struct ctl_port *port;
3283 		struct ctl_lun_list *list;
3284 		struct ctl_option *opt;
3285 
3286 		list = (struct ctl_lun_list *)addr;
3287 
3288 		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3289 		if (sb == NULL) {
3290 			list->status = CTL_LUN_LIST_ERROR;
3291 			snprintf(list->error_str, sizeof(list->error_str),
3292 				 "Unable to allocate %d bytes for LUN list",
3293 				 list->alloc_len);
3294 			break;
3295 		}
3296 
3297 		sbuf_printf(sb, "<ctlportlist>\n");
3298 
3299 		mtx_lock(&softc->ctl_lock);
3300 		STAILQ_FOREACH(port, &softc->port_list, links) {
3301 			retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3302 					     (uintmax_t)port->targ_port);
3303 
3304 			/*
3305 			 * Bail out as soon as we see that we've overfilled
3306 			 * the buffer.
3307 			 */
3308 			if (retval != 0)
3309 				break;
3310 
3311 			retval = sbuf_printf(sb, "\t<frontend_type>%s"
3312 			    "</frontend_type>\n", port->frontend->name);
3313 			if (retval != 0)
3314 				break;
3315 
3316 			retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3317 					     port->port_type);
3318 			if (retval != 0)
3319 				break;
3320 
3321 			retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3322 			    (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3323 			if (retval != 0)
3324 				break;
3325 
3326 			retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3327 			    port->port_name);
3328 			if (retval != 0)
3329 				break;
3330 
3331 			retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3332 			    port->physical_port);
3333 			if (retval != 0)
3334 				break;
3335 
3336 			retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3337 			    port->virtual_port);
3338 			if (retval != 0)
3339 				break;
3340 
3341 			retval = sbuf_printf(sb, "\t<wwnn>%#jx</wwnn>\n",
3342 			    (uintmax_t)port->wwnn);
3343 			if (retval != 0)
3344 				break;
3345 
3346 			retval = sbuf_printf(sb, "\t<wwpn>%#jx</wwpn>\n",
3347 			    (uintmax_t)port->wwpn);
3348 			if (retval != 0)
3349 				break;
3350 
3351 			if (port->port_info != NULL) {
3352 				retval = port->port_info(port->onoff_arg, sb);
3353 				if (retval != 0)
3354 					break;
3355 			}
3356 			STAILQ_FOREACH(opt, &port->options, links) {
3357 				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3358 				    opt->name, opt->value, opt->name);
3359 				if (retval != 0)
3360 					break;
3361 			}
3362 
3363 			retval = sbuf_printf(sb, "</targ_port>\n");
3364 			if (retval != 0)
3365 				break;
3366 		}
3367 		mtx_unlock(&softc->ctl_lock);
3368 
3369 		if ((retval != 0)
3370 		 || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3371 			retval = 0;
3372 			sbuf_delete(sb);
3373 			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3374 			snprintf(list->error_str, sizeof(list->error_str),
3375 				 "Out of space, %d bytes is too small",
3376 				 list->alloc_len);
3377 			break;
3378 		}
3379 
3380 		sbuf_finish(sb);
3381 
3382 		retval = copyout(sbuf_data(sb), list->lun_xml,
3383 				 sbuf_len(sb) + 1);
3384 
3385 		list->fill_len = sbuf_len(sb) + 1;
3386 		list->status = CTL_LUN_LIST_OK;
3387 		sbuf_delete(sb);
3388 		break;
3389 	}
3390 	default: {
3391 		/* XXX KDM should we fix this? */
3392 #if 0
3393 		struct ctl_backend_driver *backend;
3394 		unsigned int type;
3395 		int found;
3396 
3397 		found = 0;
3398 
3399 		/*
3400 		 * We encode the backend type as the ioctl type for backend
3401 		 * ioctls.  So parse it out here, and then search for a
3402 		 * backend of this type.
3403 		 */
3404 		type = _IOC_TYPE(cmd);
3405 
3406 		STAILQ_FOREACH(backend, &softc->be_list, links) {
3407 			if (backend->type == type) {
3408 				found = 1;
3409 				break;
3410 			}
3411 		}
3412 		if (found == 0) {
3413 			printf("ctl: unknown ioctl command %#lx or backend "
3414 			       "%d\n", cmd, type);
3415 			retval = EINVAL;
3416 			break;
3417 		}
3418 		retval = backend->ioctl(dev, cmd, addr, flag, td);
3419 #endif
3420 		retval = ENOTTY;
3421 		break;
3422 	}
3423 	}
3424 	return (retval);
3425 }
3426 
3427 uint32_t
3428 ctl_get_initindex(struct ctl_nexus *nexus)
3429 {
3430 	if (nexus->targ_port < CTL_MAX_PORTS)
3431 		return (nexus->initid.id +
3432 			(nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3433 	else
3434 		return (nexus->initid.id +
3435 		       ((nexus->targ_port - CTL_MAX_PORTS) *
3436 			CTL_MAX_INIT_PER_PORT));
3437 }
3438 
3439 uint32_t
3440 ctl_get_resindex(struct ctl_nexus *nexus)
3441 {
3442 	return (nexus->initid.id + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3443 }
3444 
3445 uint32_t
3446 ctl_port_idx(int port_num)
3447 {
3448 	if (port_num < CTL_MAX_PORTS)
3449 		return(port_num);
3450 	else
3451 		return(port_num - CTL_MAX_PORTS);
3452 }
3453 
3454 static uint32_t
3455 ctl_map_lun(int port_num, uint32_t lun_id)
3456 {
3457 	struct ctl_port *port;
3458 
3459 	port = control_softc->ctl_ports[ctl_port_idx(port_num)];
3460 	if (port == NULL)
3461 		return (UINT32_MAX);
3462 	if (port->lun_map == NULL)
3463 		return (lun_id);
3464 	return (port->lun_map(port->targ_lun_arg, lun_id));
3465 }
3466 
3467 static uint32_t
3468 ctl_map_lun_back(int port_num, uint32_t lun_id)
3469 {
3470 	struct ctl_port *port;
3471 	uint32_t i;
3472 
3473 	port = control_softc->ctl_ports[ctl_port_idx(port_num)];
3474 	if (port->lun_map == NULL)
3475 		return (lun_id);
3476 	for (i = 0; i < CTL_MAX_LUNS; i++) {
3477 		if (port->lun_map(port->targ_lun_arg, i) == lun_id)
3478 			return (i);
3479 	}
3480 	return (UINT32_MAX);
3481 }
3482 
3483 /*
3484  * Note:  This only works for bitmask sizes that are at least 32 bits, and
3485  * that are a power of 2.
3486  */
3487 int
3488 ctl_ffz(uint32_t *mask, uint32_t size)
3489 {
3490 	uint32_t num_chunks, num_pieces;
3491 	int i, j;
3492 
3493 	num_chunks = (size >> 5);
3494 	if (num_chunks == 0)
3495 		num_chunks++;
3496 	num_pieces = ctl_min((sizeof(uint32_t) * 8), size);
3497 
3498 	for (i = 0; i < num_chunks; i++) {
3499 		for (j = 0; j < num_pieces; j++) {
3500 			if ((mask[i] & (1 << j)) == 0)
3501 				return ((i << 5) + j);
3502 		}
3503 	}
3504 
3505 	return (-1);
3506 }
3507 
3508 int
3509 ctl_set_mask(uint32_t *mask, uint32_t bit)
3510 {
3511 	uint32_t chunk, piece;
3512 
3513 	chunk = bit >> 5;
3514 	piece = bit % (sizeof(uint32_t) * 8);
3515 
3516 	if ((mask[chunk] & (1 << piece)) != 0)
3517 		return (-1);
3518 	else
3519 		mask[chunk] |= (1 << piece);
3520 
3521 	return (0);
3522 }
3523 
3524 int
3525 ctl_clear_mask(uint32_t *mask, uint32_t bit)
3526 {
3527 	uint32_t chunk, piece;
3528 
3529 	chunk = bit >> 5;
3530 	piece = bit % (sizeof(uint32_t) * 8);
3531 
3532 	if ((mask[chunk] & (1 << piece)) == 0)
3533 		return (-1);
3534 	else
3535 		mask[chunk] &= ~(1 << piece);
3536 
3537 	return (0);
3538 }
3539 
3540 int
3541 ctl_is_set(uint32_t *mask, uint32_t bit)
3542 {
3543 	uint32_t chunk, piece;
3544 
3545 	chunk = bit >> 5;
3546 	piece = bit % (sizeof(uint32_t) * 8);
3547 
3548 	if ((mask[chunk] & (1 << piece)) == 0)
3549 		return (0);
3550 	else
3551 		return (1);
3552 }
3553 
3554 #ifdef unused
3555 /*
3556  * The bus, target and lun are optional, they can be filled in later.
3557  * can_wait is used to determine whether we can wait on the malloc or not.
3558  */
3559 union ctl_io*
3560 ctl_malloc_io(ctl_io_type io_type, uint32_t targ_port, uint32_t targ_target,
3561 	      uint32_t targ_lun, int can_wait)
3562 {
3563 	union ctl_io *io;
3564 
3565 	if (can_wait)
3566 		io = (union ctl_io *)malloc(sizeof(*io), M_CTL, M_WAITOK);
3567 	else
3568 		io = (union ctl_io *)malloc(sizeof(*io), M_CTL, M_NOWAIT);
3569 
3570 	if (io != NULL) {
3571 		io->io_hdr.io_type = io_type;
3572 		io->io_hdr.targ_port = targ_port;
3573 		/*
3574 		 * XXX KDM this needs to change/go away.  We need to move
3575 		 * to a preallocated pool of ctl_scsiio structures.
3576 		 */
3577 		io->io_hdr.nexus.targ_target.id = targ_target;
3578 		io->io_hdr.nexus.targ_lun = targ_lun;
3579 	}
3580 
3581 	return (io);
3582 }
3583 
3584 void
3585 ctl_kfree_io(union ctl_io *io)
3586 {
3587 	free(io, M_CTL);
3588 }
3589 #endif /* unused */
3590 
3591 /*
3592  * ctl_softc, pool_type, total_ctl_io are passed in.
3593  * npool is passed out.
3594  */
3595 int
3596 ctl_pool_create(struct ctl_softc *ctl_softc, ctl_pool_type pool_type,
3597 		uint32_t total_ctl_io, struct ctl_io_pool **npool)
3598 {
3599 	uint32_t i;
3600 	union ctl_io *cur_io, *next_io;
3601 	struct ctl_io_pool *pool;
3602 	int retval;
3603 
3604 	retval = 0;
3605 
3606 	pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3607 					    M_NOWAIT | M_ZERO);
3608 	if (pool == NULL) {
3609 		retval = ENOMEM;
3610 		goto bailout;
3611 	}
3612 
3613 	pool->type = pool_type;
3614 	pool->ctl_softc = ctl_softc;
3615 
3616 	mtx_lock(&ctl_softc->pool_lock);
3617 	pool->id = ctl_softc->cur_pool_id++;
3618 	mtx_unlock(&ctl_softc->pool_lock);
3619 
3620 	pool->flags = CTL_POOL_FLAG_NONE;
3621 	pool->refcount = 1;		/* Reference for validity. */
3622 	STAILQ_INIT(&pool->free_queue);
3623 
3624 	/*
3625 	 * XXX KDM other options here:
3626 	 * - allocate a page at a time
3627 	 * - allocate one big chunk of memory.
3628 	 * Page allocation might work well, but would take a little more
3629 	 * tracking.
3630 	 */
3631 	for (i = 0; i < total_ctl_io; i++) {
3632 		cur_io = (union ctl_io *)malloc(sizeof(*cur_io), M_CTLIO,
3633 						M_NOWAIT);
3634 		if (cur_io == NULL) {
3635 			retval = ENOMEM;
3636 			break;
3637 		}
3638 		cur_io->io_hdr.pool = pool;
3639 		STAILQ_INSERT_TAIL(&pool->free_queue, &cur_io->io_hdr, links);
3640 		pool->total_ctl_io++;
3641 		pool->free_ctl_io++;
3642 	}
3643 
3644 	if (retval != 0) {
3645 		for (cur_io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue);
3646 		     cur_io != NULL; cur_io = next_io) {
3647 			next_io = (union ctl_io *)STAILQ_NEXT(&cur_io->io_hdr,
3648 							      links);
3649 			STAILQ_REMOVE(&pool->free_queue, &cur_io->io_hdr,
3650 				      ctl_io_hdr, links);
3651 			free(cur_io, M_CTLIO);
3652 		}
3653 
3654 		free(pool, M_CTL);
3655 		goto bailout;
3656 	}
3657 	mtx_lock(&ctl_softc->pool_lock);
3658 	ctl_softc->num_pools++;
3659 	STAILQ_INSERT_TAIL(&ctl_softc->io_pools, pool, links);
3660 	/*
3661 	 * Increment our usage count if this is an external consumer, so we
3662 	 * can't get unloaded until the external consumer (most likely a
3663 	 * FETD) unloads and frees his pool.
3664 	 *
3665 	 * XXX KDM will this increment the caller's module use count, or
3666 	 * mine?
3667 	 */
3668 #if 0
3669 	if ((pool_type != CTL_POOL_EMERGENCY)
3670 	 && (pool_type != CTL_POOL_INTERNAL)
3671 	 && (pool_type != CTL_POOL_4OTHERSC))
3672 		MOD_INC_USE_COUNT;
3673 #endif
3674 
3675 	mtx_unlock(&ctl_softc->pool_lock);
3676 
3677 	*npool = pool;
3678 
3679 bailout:
3680 
3681 	return (retval);
3682 }
3683 
3684 static int
3685 ctl_pool_acquire(struct ctl_io_pool *pool)
3686 {
3687 
3688 	mtx_assert(&pool->ctl_softc->pool_lock, MA_OWNED);
3689 
3690 	if (pool->flags & CTL_POOL_FLAG_INVALID)
3691 		return (EINVAL);
3692 
3693 	pool->refcount++;
3694 
3695 	return (0);
3696 }
3697 
3698 static void
3699 ctl_pool_release(struct ctl_io_pool *pool)
3700 {
3701 	struct ctl_softc *ctl_softc = pool->ctl_softc;
3702 	union ctl_io *io;
3703 
3704 	mtx_assert(&ctl_softc->pool_lock, MA_OWNED);
3705 
3706 	if (--pool->refcount != 0)
3707 		return;
3708 
3709 	while ((io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue)) != NULL) {
3710 		STAILQ_REMOVE(&pool->free_queue, &io->io_hdr, ctl_io_hdr,
3711 			      links);
3712 		free(io, M_CTLIO);
3713 	}
3714 
3715 	STAILQ_REMOVE(&ctl_softc->io_pools, pool, ctl_io_pool, links);
3716 	ctl_softc->num_pools--;
3717 
3718 	/*
3719 	 * XXX KDM will this decrement the caller's usage count or mine?
3720 	 */
3721 #if 0
3722 	if ((pool->type != CTL_POOL_EMERGENCY)
3723 	 && (pool->type != CTL_POOL_INTERNAL)
3724 	 && (pool->type != CTL_POOL_4OTHERSC))
3725 		MOD_DEC_USE_COUNT;
3726 #endif
3727 
3728 	free(pool, M_CTL);
3729 }
3730 
3731 void
3732 ctl_pool_free(struct ctl_io_pool *pool)
3733 {
3734 	struct ctl_softc *ctl_softc;
3735 
3736 	if (pool == NULL)
3737 		return;
3738 
3739 	ctl_softc = pool->ctl_softc;
3740 	mtx_lock(&ctl_softc->pool_lock);
3741 	pool->flags |= CTL_POOL_FLAG_INVALID;
3742 	ctl_pool_release(pool);
3743 	mtx_unlock(&ctl_softc->pool_lock);
3744 }
3745 
3746 /*
3747  * This routine does not block (except for spinlocks of course).
3748  * It tries to allocate a ctl_io union from the caller's pool as quickly as
3749  * possible.
3750  */
3751 union ctl_io *
3752 ctl_alloc_io(void *pool_ref)
3753 {
3754 	union ctl_io *io;
3755 	struct ctl_softc *ctl_softc;
3756 	struct ctl_io_pool *pool, *npool;
3757 	struct ctl_io_pool *emergency_pool;
3758 
3759 	pool = (struct ctl_io_pool *)pool_ref;
3760 
3761 	if (pool == NULL) {
3762 		printf("%s: pool is NULL\n", __func__);
3763 		return (NULL);
3764 	}
3765 
3766 	emergency_pool = NULL;
3767 
3768 	ctl_softc = pool->ctl_softc;
3769 
3770 	mtx_lock(&ctl_softc->pool_lock);
3771 	/*
3772 	 * First, try to get the io structure from the user's pool.
3773 	 */
3774 	if (ctl_pool_acquire(pool) == 0) {
3775 		io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue);
3776 		if (io != NULL) {
3777 			STAILQ_REMOVE_HEAD(&pool->free_queue, links);
3778 			pool->total_allocated++;
3779 			pool->free_ctl_io--;
3780 			mtx_unlock(&ctl_softc->pool_lock);
3781 			return (io);
3782 		} else
3783 			ctl_pool_release(pool);
3784 	}
3785 	/*
3786 	 * If he doesn't have any io structures left, search for an
3787 	 * emergency pool and grab one from there.
3788 	 */
3789 	STAILQ_FOREACH(npool, &ctl_softc->io_pools, links) {
3790 		if (npool->type != CTL_POOL_EMERGENCY)
3791 			continue;
3792 
3793 		if (ctl_pool_acquire(npool) != 0)
3794 			continue;
3795 
3796 		emergency_pool = npool;
3797 
3798 		io = (union ctl_io *)STAILQ_FIRST(&npool->free_queue);
3799 		if (io != NULL) {
3800 			STAILQ_REMOVE_HEAD(&npool->free_queue, links);
3801 			npool->total_allocated++;
3802 			npool->free_ctl_io--;
3803 			mtx_unlock(&ctl_softc->pool_lock);
3804 			return (io);
3805 		} else
3806 			ctl_pool_release(npool);
3807 	}
3808 
3809 	/* Drop the spinlock before we malloc */
3810 	mtx_unlock(&ctl_softc->pool_lock);
3811 
3812 	/*
3813 	 * The emergency pool (if it exists) didn't have one, so try an
3814 	 * atomic (i.e. nonblocking) malloc and see if we get lucky.
3815 	 */
3816 	io = (union ctl_io *)malloc(sizeof(*io), M_CTLIO, M_NOWAIT);
3817 	if (io != NULL) {
3818 		/*
3819 		 * If the emergency pool exists but is empty, add this
3820 		 * ctl_io to its list when it gets freed.
3821 		 */
3822 		if (emergency_pool != NULL) {
3823 			mtx_lock(&ctl_softc->pool_lock);
3824 			if (ctl_pool_acquire(emergency_pool) == 0) {
3825 				io->io_hdr.pool = emergency_pool;
3826 				emergency_pool->total_ctl_io++;
3827 				/*
3828 				 * Need to bump this, otherwise
3829 				 * total_allocated and total_freed won't
3830 				 * match when we no longer have anything
3831 				 * outstanding.
3832 				 */
3833 				emergency_pool->total_allocated++;
3834 			}
3835 			mtx_unlock(&ctl_softc->pool_lock);
3836 		} else
3837 			io->io_hdr.pool = NULL;
3838 	}
3839 
3840 	return (io);
3841 }
3842 
3843 void
3844 ctl_free_io(union ctl_io *io)
3845 {
3846 	if (io == NULL)
3847 		return;
3848 
3849 	/*
3850 	 * If this ctl_io has a pool, return it to that pool.
3851 	 */
3852 	if (io->io_hdr.pool != NULL) {
3853 		struct ctl_io_pool *pool;
3854 
3855 		pool = (struct ctl_io_pool *)io->io_hdr.pool;
3856 		mtx_lock(&pool->ctl_softc->pool_lock);
3857 		io->io_hdr.io_type = 0xff;
3858 		STAILQ_INSERT_TAIL(&pool->free_queue, &io->io_hdr, links);
3859 		pool->total_freed++;
3860 		pool->free_ctl_io++;
3861 		ctl_pool_release(pool);
3862 		mtx_unlock(&pool->ctl_softc->pool_lock);
3863 	} else {
3864 		/*
3865 		 * Otherwise, just free it.  We probably malloced it and
3866 		 * the emergency pool wasn't available.
3867 		 */
3868 		free(io, M_CTLIO);
3869 	}
3870 
3871 }
3872 
3873 void
3874 ctl_zero_io(union ctl_io *io)
3875 {
3876 	void *pool_ref;
3877 
3878 	if (io == NULL)
3879 		return;
3880 
3881 	/*
3882 	 * May need to preserve linked list pointers at some point too.
3883 	 */
3884 	pool_ref = io->io_hdr.pool;
3885 
3886 	memset(io, 0, sizeof(*io));
3887 
3888 	io->io_hdr.pool = pool_ref;
3889 }
3890 
3891 /*
3892  * This routine is currently used for internal copies of ctl_ios that need
3893  * to persist for some reason after we've already returned status to the
3894  * FETD.  (Thus the flag set.)
3895  *
3896  * XXX XXX
3897  * Note that this makes a blind copy of all fields in the ctl_io, except
3898  * for the pool reference.  This includes any memory that has been
3899  * allocated!  That memory will no longer be valid after done has been
3900  * called, so this would be VERY DANGEROUS for command that actually does
3901  * any reads or writes.  Right now (11/7/2005), this is only used for immediate
3902  * start and stop commands, which don't transfer any data, so this is not a
3903  * problem.  If it is used for anything else, the caller would also need to
3904  * allocate data buffer space and this routine would need to be modified to
3905  * copy the data buffer(s) as well.
3906  */
3907 void
3908 ctl_copy_io(union ctl_io *src, union ctl_io *dest)
3909 {
3910 	void *pool_ref;
3911 
3912 	if ((src == NULL)
3913 	 || (dest == NULL))
3914 		return;
3915 
3916 	/*
3917 	 * May need to preserve linked list pointers at some point too.
3918 	 */
3919 	pool_ref = dest->io_hdr.pool;
3920 
3921 	memcpy(dest, src, ctl_min(sizeof(*src), sizeof(*dest)));
3922 
3923 	dest->io_hdr.pool = pool_ref;
3924 	/*
3925 	 * We need to know that this is an internal copy, and doesn't need
3926 	 * to get passed back to the FETD that allocated it.
3927 	 */
3928 	dest->io_hdr.flags |= CTL_FLAG_INT_COPY;
3929 }
3930 
3931 #ifdef NEEDTOPORT
3932 static void
3933 ctl_update_power_subpage(struct copan_power_subpage *page)
3934 {
3935 	int num_luns, num_partitions, config_type;
3936 	struct ctl_softc *softc;
3937 	cs_BOOL_t aor_present, shelf_50pct_power;
3938 	cs_raidset_personality_t rs_type;
3939 	int max_active_luns;
3940 
3941 	softc = control_softc;
3942 
3943 	/* subtract out the processor LUN */
3944 	num_luns = softc->num_luns - 1;
3945 	/*
3946 	 * Default to 7 LUNs active, which was the only number we allowed
3947 	 * in the past.
3948 	 */
3949 	max_active_luns = 7;
3950 
3951 	num_partitions = config_GetRsPartitionInfo();
3952 	config_type = config_GetConfigType();
3953 	shelf_50pct_power = config_GetShelfPowerMode();
3954 	aor_present = config_IsAorRsPresent();
3955 
3956 	rs_type = ddb_GetRsRaidType(1);
3957 	if ((rs_type != CS_RAIDSET_PERSONALITY_RAID5)
3958 	 && (rs_type != CS_RAIDSET_PERSONALITY_RAID1)) {
3959 		EPRINT(0, "Unsupported RS type %d!", rs_type);
3960 	}
3961 
3962 
3963 	page->total_luns = num_luns;
3964 
3965 	switch (config_type) {
3966 	case 40:
3967 		/*
3968 		 * In a 40 drive configuration, it doesn't matter what DC
3969 		 * cards we have, whether we have AOR enabled or not,
3970 		 * partitioning or not, or what type of RAIDset we have.
3971 		 * In that scenario, we can power up every LUN we present
3972 		 * to the user.
3973 		 */
3974 		max_active_luns = num_luns;
3975 
3976 		break;
3977 	case 64:
3978 		if (shelf_50pct_power == CS_FALSE) {
3979 			/* 25% power */
3980 			if (aor_present == CS_TRUE) {
3981 				if (rs_type ==
3982 				     CS_RAIDSET_PERSONALITY_RAID5) {
3983 					max_active_luns = 7;
3984 				} else if (rs_type ==
3985 					 CS_RAIDSET_PERSONALITY_RAID1){
3986 					max_active_luns = 14;
3987 				} else {
3988 					/* XXX KDM now what?? */
3989 				}
3990 			} else {
3991 				if (rs_type ==
3992 				     CS_RAIDSET_PERSONALITY_RAID5) {
3993 					max_active_luns = 8;
3994 				} else if (rs_type ==
3995 					 CS_RAIDSET_PERSONALITY_RAID1){
3996 					max_active_luns = 16;
3997 				} else {
3998 					/* XXX KDM now what?? */
3999 				}
4000 			}
4001 		} else {
4002 			/* 50% power */
4003 			/*
4004 			 * With 50% power in a 64 drive configuration, we
4005 			 * can power all LUNs we present.
4006 			 */
4007 			max_active_luns = num_luns;
4008 		}
4009 		break;
4010 	case 112:
4011 		if (shelf_50pct_power == CS_FALSE) {
4012 			/* 25% power */
4013 			if (aor_present == CS_TRUE) {
4014 				if (rs_type ==
4015 				     CS_RAIDSET_PERSONALITY_RAID5) {
4016 					max_active_luns = 7;
4017 				} else if (rs_type ==
4018 					 CS_RAIDSET_PERSONALITY_RAID1){
4019 					max_active_luns = 14;
4020 				} else {
4021 					/* XXX KDM now what?? */
4022 				}
4023 			} else {
4024 				if (rs_type ==
4025 				     CS_RAIDSET_PERSONALITY_RAID5) {
4026 					max_active_luns = 8;
4027 				} else if (rs_type ==
4028 					 CS_RAIDSET_PERSONALITY_RAID1){
4029 					max_active_luns = 16;
4030 				} else {
4031 					/* XXX KDM now what?? */
4032 				}
4033 			}
4034 		} else {
4035 			/* 50% power */
4036 			if (aor_present == CS_TRUE) {
4037 				if (rs_type ==
4038 				     CS_RAIDSET_PERSONALITY_RAID5) {
4039 					max_active_luns = 14;
4040 				} else if (rs_type ==
4041 					 CS_RAIDSET_PERSONALITY_RAID1){
4042 					/*
4043 					 * We're assuming here that disk
4044 					 * caching is enabled, and so we're
4045 					 * able to power up half of each
4046 					 * LUN, and cache all writes.
4047 					 */
4048 					max_active_luns = num_luns;
4049 				} else {
4050 					/* XXX KDM now what?? */
4051 				}
4052 			} else {
4053 				if (rs_type ==
4054 				     CS_RAIDSET_PERSONALITY_RAID5) {
4055 					max_active_luns = 15;
4056 				} else if (rs_type ==
4057 					 CS_RAIDSET_PERSONALITY_RAID1){
4058 					max_active_luns = 30;
4059 				} else {
4060 					/* XXX KDM now what?? */
4061 				}
4062 			}
4063 		}
4064 		break;
4065 	default:
4066 		/*
4067 		 * In this case, we have an unknown configuration, so we
4068 		 * just use the default from above.
4069 		 */
4070 		break;
4071 	}
4072 
4073 	page->max_active_luns = max_active_luns;
4074 #if 0
4075 	printk("%s: total_luns = %d, max_active_luns = %d\n", __func__,
4076 	       page->total_luns, page->max_active_luns);
4077 #endif
4078 }
4079 #endif /* NEEDTOPORT */
4080 
4081 /*
4082  * This routine could be used in the future to load default and/or saved
4083  * mode page parameters for a particuar lun.
4084  */
4085 static int
4086 ctl_init_page_index(struct ctl_lun *lun)
4087 {
4088 	int i;
4089 	struct ctl_page_index *page_index;
4090 	struct ctl_softc *softc;
4091 
4092 	memcpy(&lun->mode_pages.index, page_index_template,
4093 	       sizeof(page_index_template));
4094 
4095 	softc = lun->ctl_softc;
4096 
4097 	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
4098 
4099 		page_index = &lun->mode_pages.index[i];
4100 		/*
4101 		 * If this is a disk-only mode page, there's no point in
4102 		 * setting it up.  For some pages, we have to have some
4103 		 * basic information about the disk in order to calculate the
4104 		 * mode page data.
4105 		 */
4106 		if ((lun->be_lun->lun_type != T_DIRECT)
4107 		 && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
4108 			continue;
4109 
4110 		switch (page_index->page_code & SMPH_PC_MASK) {
4111 		case SMS_FORMAT_DEVICE_PAGE: {
4112 			struct scsi_format_page *format_page;
4113 
4114 			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4115 				panic("subpage is incorrect!");
4116 
4117 			/*
4118 			 * Sectors per track are set above.  Bytes per
4119 			 * sector need to be set here on a per-LUN basis.
4120 			 */
4121 			memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
4122 			       &format_page_default,
4123 			       sizeof(format_page_default));
4124 			memcpy(&lun->mode_pages.format_page[
4125 			       CTL_PAGE_CHANGEABLE], &format_page_changeable,
4126 			       sizeof(format_page_changeable));
4127 			memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
4128 			       &format_page_default,
4129 			       sizeof(format_page_default));
4130 			memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
4131 			       &format_page_default,
4132 			       sizeof(format_page_default));
4133 
4134 			format_page = &lun->mode_pages.format_page[
4135 				CTL_PAGE_CURRENT];
4136 			scsi_ulto2b(lun->be_lun->blocksize,
4137 				    format_page->bytes_per_sector);
4138 
4139 			format_page = &lun->mode_pages.format_page[
4140 				CTL_PAGE_DEFAULT];
4141 			scsi_ulto2b(lun->be_lun->blocksize,
4142 				    format_page->bytes_per_sector);
4143 
4144 			format_page = &lun->mode_pages.format_page[
4145 				CTL_PAGE_SAVED];
4146 			scsi_ulto2b(lun->be_lun->blocksize,
4147 				    format_page->bytes_per_sector);
4148 
4149 			page_index->page_data =
4150 				(uint8_t *)lun->mode_pages.format_page;
4151 			break;
4152 		}
4153 		case SMS_RIGID_DISK_PAGE: {
4154 			struct scsi_rigid_disk_page *rigid_disk_page;
4155 			uint32_t sectors_per_cylinder;
4156 			uint64_t cylinders;
4157 #ifndef	__XSCALE__
4158 			int shift;
4159 #endif /* !__XSCALE__ */
4160 
4161 			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4162 				panic("invalid subpage value %d",
4163 				      page_index->subpage);
4164 
4165 			/*
4166 			 * Rotation rate and sectors per track are set
4167 			 * above.  We calculate the cylinders here based on
4168 			 * capacity.  Due to the number of heads and
4169 			 * sectors per track we're using, smaller arrays
4170 			 * may turn out to have 0 cylinders.  Linux and
4171 			 * FreeBSD don't pay attention to these mode pages
4172 			 * to figure out capacity, but Solaris does.  It
4173 			 * seems to deal with 0 cylinders just fine, and
4174 			 * works out a fake geometry based on the capacity.
4175 			 */
4176 			memcpy(&lun->mode_pages.rigid_disk_page[
4177 			       CTL_PAGE_CURRENT], &rigid_disk_page_default,
4178 			       sizeof(rigid_disk_page_default));
4179 			memcpy(&lun->mode_pages.rigid_disk_page[
4180 			       CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
4181 			       sizeof(rigid_disk_page_changeable));
4182 			memcpy(&lun->mode_pages.rigid_disk_page[
4183 			       CTL_PAGE_DEFAULT], &rigid_disk_page_default,
4184 			       sizeof(rigid_disk_page_default));
4185 			memcpy(&lun->mode_pages.rigid_disk_page[
4186 			       CTL_PAGE_SAVED], &rigid_disk_page_default,
4187 			       sizeof(rigid_disk_page_default));
4188 
4189 			sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
4190 				CTL_DEFAULT_HEADS;
4191 
4192 			/*
4193 			 * The divide method here will be more accurate,
4194 			 * probably, but results in floating point being
4195 			 * used in the kernel on i386 (__udivdi3()).  On the
4196 			 * XScale, though, __udivdi3() is implemented in
4197 			 * software.
4198 			 *
4199 			 * The shift method for cylinder calculation is
4200 			 * accurate if sectors_per_cylinder is a power of
4201 			 * 2.  Otherwise it might be slightly off -- you
4202 			 * might have a bit of a truncation problem.
4203 			 */
4204 #ifdef	__XSCALE__
4205 			cylinders = (lun->be_lun->maxlba + 1) /
4206 				sectors_per_cylinder;
4207 #else
4208 			for (shift = 31; shift > 0; shift--) {
4209 				if (sectors_per_cylinder & (1 << shift))
4210 					break;
4211 			}
4212 			cylinders = (lun->be_lun->maxlba + 1) >> shift;
4213 #endif
4214 
4215 			/*
4216 			 * We've basically got 3 bytes, or 24 bits for the
4217 			 * cylinder size in the mode page.  If we're over,
4218 			 * just round down to 2^24.
4219 			 */
4220 			if (cylinders > 0xffffff)
4221 				cylinders = 0xffffff;
4222 
4223 			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4224 				CTL_PAGE_CURRENT];
4225 			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4226 
4227 			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4228 				CTL_PAGE_DEFAULT];
4229 			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4230 
4231 			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4232 				CTL_PAGE_SAVED];
4233 			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4234 
4235 			page_index->page_data =
4236 				(uint8_t *)lun->mode_pages.rigid_disk_page;
4237 			break;
4238 		}
4239 		case SMS_CACHING_PAGE: {
4240 
4241 			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4242 				panic("invalid subpage value %d",
4243 				      page_index->subpage);
4244 			/*
4245 			 * Defaults should be okay here, no calculations
4246 			 * needed.
4247 			 */
4248 			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4249 			       &caching_page_default,
4250 			       sizeof(caching_page_default));
4251 			memcpy(&lun->mode_pages.caching_page[
4252 			       CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4253 			       sizeof(caching_page_changeable));
4254 			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4255 			       &caching_page_default,
4256 			       sizeof(caching_page_default));
4257 			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4258 			       &caching_page_default,
4259 			       sizeof(caching_page_default));
4260 			page_index->page_data =
4261 				(uint8_t *)lun->mode_pages.caching_page;
4262 			break;
4263 		}
4264 		case SMS_CONTROL_MODE_PAGE: {
4265 
4266 			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4267 				panic("invalid subpage value %d",
4268 				      page_index->subpage);
4269 
4270 			/*
4271 			 * Defaults should be okay here, no calculations
4272 			 * needed.
4273 			 */
4274 			memcpy(&lun->mode_pages.control_page[CTL_PAGE_CURRENT],
4275 			       &control_page_default,
4276 			       sizeof(control_page_default));
4277 			memcpy(&lun->mode_pages.control_page[
4278 			       CTL_PAGE_CHANGEABLE], &control_page_changeable,
4279 			       sizeof(control_page_changeable));
4280 			memcpy(&lun->mode_pages.control_page[CTL_PAGE_DEFAULT],
4281 			       &control_page_default,
4282 			       sizeof(control_page_default));
4283 			memcpy(&lun->mode_pages.control_page[CTL_PAGE_SAVED],
4284 			       &control_page_default,
4285 			       sizeof(control_page_default));
4286 			page_index->page_data =
4287 				(uint8_t *)lun->mode_pages.control_page;
4288 			break;
4289 
4290 		}
4291 		case SMS_VENDOR_SPECIFIC_PAGE:{
4292 			switch (page_index->subpage) {
4293 			case PWR_SUBPAGE_CODE: {
4294 				struct copan_power_subpage *current_page,
4295 							   *saved_page;
4296 
4297 				memcpy(&lun->mode_pages.power_subpage[
4298 				       CTL_PAGE_CURRENT],
4299 				       &power_page_default,
4300 				       sizeof(power_page_default));
4301 				memcpy(&lun->mode_pages.power_subpage[
4302 				       CTL_PAGE_CHANGEABLE],
4303 				       &power_page_changeable,
4304 				       sizeof(power_page_changeable));
4305 				memcpy(&lun->mode_pages.power_subpage[
4306 				       CTL_PAGE_DEFAULT],
4307 				       &power_page_default,
4308 				       sizeof(power_page_default));
4309 				memcpy(&lun->mode_pages.power_subpage[
4310 				       CTL_PAGE_SAVED],
4311 				       &power_page_default,
4312 				       sizeof(power_page_default));
4313 				page_index->page_data =
4314 				    (uint8_t *)lun->mode_pages.power_subpage;
4315 
4316 				current_page = (struct copan_power_subpage *)
4317 					(page_index->page_data +
4318 					 (page_index->page_len *
4319 					  CTL_PAGE_CURRENT));
4320 			        saved_page = (struct copan_power_subpage *)
4321 				        (page_index->page_data +
4322 					 (page_index->page_len *
4323 					  CTL_PAGE_SAVED));
4324 				break;
4325 			}
4326 			case APS_SUBPAGE_CODE: {
4327 				struct copan_aps_subpage *current_page,
4328 							 *saved_page;
4329 
4330 				// This gets set multiple times but
4331 				// it should always be the same. It's
4332 				// only done during init so who cares.
4333 				index_to_aps_page = i;
4334 
4335 				memcpy(&lun->mode_pages.aps_subpage[
4336 				       CTL_PAGE_CURRENT],
4337 				       &aps_page_default,
4338 				       sizeof(aps_page_default));
4339 				memcpy(&lun->mode_pages.aps_subpage[
4340 				       CTL_PAGE_CHANGEABLE],
4341 				       &aps_page_changeable,
4342 				       sizeof(aps_page_changeable));
4343 				memcpy(&lun->mode_pages.aps_subpage[
4344 				       CTL_PAGE_DEFAULT],
4345 				       &aps_page_default,
4346 				       sizeof(aps_page_default));
4347 				memcpy(&lun->mode_pages.aps_subpage[
4348 				       CTL_PAGE_SAVED],
4349 				       &aps_page_default,
4350 				       sizeof(aps_page_default));
4351 				page_index->page_data =
4352 					(uint8_t *)lun->mode_pages.aps_subpage;
4353 
4354 				current_page = (struct copan_aps_subpage *)
4355 					(page_index->page_data +
4356 					 (page_index->page_len *
4357 					  CTL_PAGE_CURRENT));
4358 				saved_page = (struct copan_aps_subpage *)
4359 					(page_index->page_data +
4360 					 (page_index->page_len *
4361 					  CTL_PAGE_SAVED));
4362 				break;
4363 			}
4364 			case DBGCNF_SUBPAGE_CODE: {
4365 				struct copan_debugconf_subpage *current_page,
4366 							       *saved_page;
4367 
4368 				memcpy(&lun->mode_pages.debugconf_subpage[
4369 				       CTL_PAGE_CURRENT],
4370 				       &debugconf_page_default,
4371 				       sizeof(debugconf_page_default));
4372 				memcpy(&lun->mode_pages.debugconf_subpage[
4373 				       CTL_PAGE_CHANGEABLE],
4374 				       &debugconf_page_changeable,
4375 				       sizeof(debugconf_page_changeable));
4376 				memcpy(&lun->mode_pages.debugconf_subpage[
4377 				       CTL_PAGE_DEFAULT],
4378 				       &debugconf_page_default,
4379 				       sizeof(debugconf_page_default));
4380 				memcpy(&lun->mode_pages.debugconf_subpage[
4381 				       CTL_PAGE_SAVED],
4382 				       &debugconf_page_default,
4383 				       sizeof(debugconf_page_default));
4384 				page_index->page_data =
4385 					(uint8_t *)lun->mode_pages.debugconf_subpage;
4386 
4387 				current_page = (struct copan_debugconf_subpage *)
4388 					(page_index->page_data +
4389 					 (page_index->page_len *
4390 					  CTL_PAGE_CURRENT));
4391 				saved_page = (struct copan_debugconf_subpage *)
4392 					(page_index->page_data +
4393 					 (page_index->page_len *
4394 					  CTL_PAGE_SAVED));
4395 				break;
4396 			}
4397 			default:
4398 				panic("invalid subpage value %d",
4399 				      page_index->subpage);
4400 				break;
4401 			}
4402    			break;
4403 		}
4404 		default:
4405 			panic("invalid page value %d",
4406 			      page_index->page_code & SMPH_PC_MASK);
4407 			break;
4408     	}
4409 	}
4410 
4411 	return (CTL_RETVAL_COMPLETE);
4412 }
4413 
4414 /*
4415  * LUN allocation.
4416  *
4417  * Requirements:
4418  * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4419  *   wants us to allocate the LUN and he can block.
4420  * - ctl_softc is always set
4421  * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4422  *
4423  * Returns 0 for success, non-zero (errno) for failure.
4424  */
4425 static int
4426 ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4427 	      struct ctl_be_lun *const be_lun, struct ctl_id target_id)
4428 {
4429 	struct ctl_lun *nlun, *lun;
4430 	struct ctl_port *port;
4431 	struct scsi_vpd_id_descriptor *desc;
4432 	struct scsi_vpd_id_t10 *t10id;
4433 	const char *eui, *naa, *scsiname, *vendor;
4434 	int lun_number, i, lun_malloced;
4435 	int devidlen, idlen1, idlen2 = 0, len;
4436 
4437 	if (be_lun == NULL)
4438 		return (EINVAL);
4439 
4440 	/*
4441 	 * We currently only support Direct Access or Processor LUN types.
4442 	 */
4443 	switch (be_lun->lun_type) {
4444 	case T_DIRECT:
4445 		break;
4446 	case T_PROCESSOR:
4447 		break;
4448 	case T_SEQUENTIAL:
4449 	case T_CHANGER:
4450 	default:
4451 		be_lun->lun_config_status(be_lun->be_lun,
4452 					  CTL_LUN_CONFIG_FAILURE);
4453 		break;
4454 	}
4455 	if (ctl_lun == NULL) {
4456 		lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4457 		lun_malloced = 1;
4458 	} else {
4459 		lun_malloced = 0;
4460 		lun = ctl_lun;
4461 	}
4462 
4463 	memset(lun, 0, sizeof(*lun));
4464 	if (lun_malloced)
4465 		lun->flags = CTL_LUN_MALLOCED;
4466 
4467 	/* Generate LUN ID. */
4468 	devidlen = max(CTL_DEVID_MIN_LEN,
4469 	    strnlen(be_lun->device_id, CTL_DEVID_LEN));
4470 	idlen1 = sizeof(*t10id) + devidlen;
4471 	len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4472 	scsiname = ctl_get_opt(&be_lun->options, "scsiname");
4473 	if (scsiname != NULL) {
4474 		idlen2 = roundup2(strlen(scsiname) + 1, 4);
4475 		len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4476 	}
4477 	eui = ctl_get_opt(&be_lun->options, "eui");
4478 	if (eui != NULL) {
4479 		len += sizeof(struct scsi_vpd_id_descriptor) + 8;
4480 	}
4481 	naa = ctl_get_opt(&be_lun->options, "naa");
4482 	if (naa != NULL) {
4483 		len += sizeof(struct scsi_vpd_id_descriptor) + 8;
4484 	}
4485 	lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4486 	    M_CTL, M_WAITOK | M_ZERO);
4487 	lun->lun_devid->len = len;
4488 	desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4489 	desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4490 	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4491 	desc->length = idlen1;
4492 	t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4493 	memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4494 	if ((vendor = ctl_get_opt(&be_lun->options, "vendor")) == NULL) {
4495 		strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4496 	} else {
4497 		strncpy(t10id->vendor, vendor,
4498 		    min(sizeof(t10id->vendor), strlen(vendor)));
4499 	}
4500 	strncpy((char *)t10id->vendor_spec_id,
4501 	    (char *)be_lun->device_id, devidlen);
4502 	if (scsiname != NULL) {
4503 		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4504 		    desc->length);
4505 		desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4506 		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4507 		    SVPD_ID_TYPE_SCSI_NAME;
4508 		desc->length = idlen2;
4509 		strlcpy(desc->identifier, scsiname, idlen2);
4510 	}
4511 	if (eui != NULL) {
4512 		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4513 		    desc->length);
4514 		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4515 		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4516 		    SVPD_ID_TYPE_EUI64;
4517 		desc->length = 8;
4518 		scsi_u64to8b(strtouq(eui, NULL, 0), desc->identifier);
4519 	}
4520 	if (naa != NULL) {
4521 		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4522 		    desc->length);
4523 		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4524 		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4525 		    SVPD_ID_TYPE_NAA;
4526 		desc->length = 8;
4527 		scsi_u64to8b(strtouq(naa, NULL, 0), desc->identifier);
4528 	}
4529 
4530 	mtx_lock(&ctl_softc->ctl_lock);
4531 	/*
4532 	 * See if the caller requested a particular LUN number.  If so, see
4533 	 * if it is available.  Otherwise, allocate the first available LUN.
4534 	 */
4535 	if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4536 		if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4537 		 || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4538 			mtx_unlock(&ctl_softc->ctl_lock);
4539 			if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4540 				printf("ctl: requested LUN ID %d is higher "
4541 				       "than CTL_MAX_LUNS - 1 (%d)\n",
4542 				       be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4543 			} else {
4544 				/*
4545 				 * XXX KDM return an error, or just assign
4546 				 * another LUN ID in this case??
4547 				 */
4548 				printf("ctl: requested LUN ID %d is already "
4549 				       "in use\n", be_lun->req_lun_id);
4550 			}
4551 			if (lun->flags & CTL_LUN_MALLOCED)
4552 				free(lun, M_CTL);
4553 			be_lun->lun_config_status(be_lun->be_lun,
4554 						  CTL_LUN_CONFIG_FAILURE);
4555 			return (ENOSPC);
4556 		}
4557 		lun_number = be_lun->req_lun_id;
4558 	} else {
4559 		lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, CTL_MAX_LUNS);
4560 		if (lun_number == -1) {
4561 			mtx_unlock(&ctl_softc->ctl_lock);
4562 			printf("ctl: can't allocate LUN on target %ju, out of "
4563 			       "LUNs\n", (uintmax_t)target_id.id);
4564 			if (lun->flags & CTL_LUN_MALLOCED)
4565 				free(lun, M_CTL);
4566 			be_lun->lun_config_status(be_lun->be_lun,
4567 						  CTL_LUN_CONFIG_FAILURE);
4568 			return (ENOSPC);
4569 		}
4570 	}
4571 	ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4572 
4573 	mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4574 	lun->target = target_id;
4575 	lun->lun = lun_number;
4576 	lun->be_lun = be_lun;
4577 	/*
4578 	 * The processor LUN is always enabled.  Disk LUNs come on line
4579 	 * disabled, and must be enabled by the backend.
4580 	 */
4581 	lun->flags |= CTL_LUN_DISABLED;
4582 	lun->backend = be_lun->be;
4583 	be_lun->ctl_lun = lun;
4584 	be_lun->lun_id = lun_number;
4585 	atomic_add_int(&be_lun->be->num_luns, 1);
4586 	if (be_lun->flags & CTL_LUN_FLAG_POWERED_OFF)
4587 		lun->flags |= CTL_LUN_STOPPED;
4588 
4589 	if (be_lun->flags & CTL_LUN_FLAG_INOPERABLE)
4590 		lun->flags |= CTL_LUN_INOPERABLE;
4591 
4592 	if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4593 		lun->flags |= CTL_LUN_PRIMARY_SC;
4594 
4595 	lun->ctl_softc = ctl_softc;
4596 	TAILQ_INIT(&lun->ooa_queue);
4597 	TAILQ_INIT(&lun->blocked_queue);
4598 	STAILQ_INIT(&lun->error_list);
4599 	ctl_tpc_init(lun);
4600 
4601 	/*
4602 	 * Initialize the mode page index.
4603 	 */
4604 	ctl_init_page_index(lun);
4605 
4606 	/*
4607 	 * Set the poweron UA for all initiators on this LUN only.
4608 	 */
4609 	for (i = 0; i < CTL_MAX_INITIATORS; i++)
4610 		lun->pending_ua[i] = CTL_UA_POWERON;
4611 
4612 	/*
4613 	 * Now, before we insert this lun on the lun list, set the lun
4614 	 * inventory changed UA for all other luns.
4615 	 */
4616 	STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4617 		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
4618 			nlun->pending_ua[i] |= CTL_UA_LUN_CHANGE;
4619 		}
4620 	}
4621 
4622 	STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4623 
4624 	ctl_softc->ctl_luns[lun_number] = lun;
4625 
4626 	ctl_softc->num_luns++;
4627 
4628 	/* Setup statistics gathering */
4629 	lun->stats.device_type = be_lun->lun_type;
4630 	lun->stats.lun_number = lun_number;
4631 	if (lun->stats.device_type == T_DIRECT)
4632 		lun->stats.blocksize = be_lun->blocksize;
4633 	else
4634 		lun->stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4635 	for (i = 0;i < CTL_MAX_PORTS;i++)
4636 		lun->stats.ports[i].targ_port = i;
4637 
4638 	mtx_unlock(&ctl_softc->ctl_lock);
4639 
4640 	lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4641 
4642 	/*
4643 	 * Run through each registered FETD and bring it online if it isn't
4644 	 * already.  Enable the target ID if it hasn't been enabled, and
4645 	 * enable this particular LUN.
4646 	 */
4647 	STAILQ_FOREACH(port, &ctl_softc->port_list, links) {
4648 		int retval;
4649 
4650 		retval = port->lun_enable(port->targ_lun_arg, target_id,lun_number);
4651 		if (retval != 0) {
4652 			printf("ctl_alloc_lun: FETD %s port %d returned error "
4653 			       "%d for lun_enable on target %ju lun %d\n",
4654 			       port->port_name, port->targ_port, retval,
4655 			       (uintmax_t)target_id.id, lun_number);
4656 		} else
4657 			port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4658 	}
4659 	return (0);
4660 }
4661 
4662 /*
4663  * Delete a LUN.
4664  * Assumptions:
4665  * - LUN has already been marked invalid and any pending I/O has been taken
4666  *   care of.
4667  */
4668 static int
4669 ctl_free_lun(struct ctl_lun *lun)
4670 {
4671 	struct ctl_softc *softc;
4672 #if 0
4673 	struct ctl_port *port;
4674 #endif
4675 	struct ctl_lun *nlun;
4676 	int i;
4677 
4678 	softc = lun->ctl_softc;
4679 
4680 	mtx_assert(&softc->ctl_lock, MA_OWNED);
4681 
4682 	STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4683 
4684 	ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4685 
4686 	softc->ctl_luns[lun->lun] = NULL;
4687 
4688 	if (!TAILQ_EMPTY(&lun->ooa_queue))
4689 		panic("Freeing a LUN %p with outstanding I/O!!\n", lun);
4690 
4691 	softc->num_luns--;
4692 
4693 	/*
4694 	 * XXX KDM this scheme only works for a single target/multiple LUN
4695 	 * setup.  It needs to be revamped for a multiple target scheme.
4696 	 *
4697 	 * XXX KDM this results in port->lun_disable() getting called twice,
4698 	 * once when ctl_disable_lun() is called, and a second time here.
4699 	 * We really need to re-think the LUN disable semantics.  There
4700 	 * should probably be several steps/levels to LUN removal:
4701 	 *  - disable
4702 	 *  - invalidate
4703 	 *  - free
4704  	 *
4705 	 * Right now we only have a disable method when communicating to
4706 	 * the front end ports, at least for individual LUNs.
4707 	 */
4708 #if 0
4709 	STAILQ_FOREACH(port, &softc->port_list, links) {
4710 		int retval;
4711 
4712 		retval = port->lun_disable(port->targ_lun_arg, lun->target,
4713 					 lun->lun);
4714 		if (retval != 0) {
4715 			printf("ctl_free_lun: FETD %s port %d returned error "
4716 			       "%d for lun_disable on target %ju lun %jd\n",
4717 			       port->port_name, port->targ_port, retval,
4718 			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4719 		}
4720 
4721 		if (STAILQ_FIRST(&softc->lun_list) == NULL) {
4722 			port->status &= ~CTL_PORT_STATUS_LUN_ONLINE;
4723 
4724 			retval = port->targ_disable(port->targ_lun_arg,lun->target);
4725 			if (retval != 0) {
4726 				printf("ctl_free_lun: FETD %s port %d "
4727 				       "returned error %d for targ_disable on "
4728 				       "target %ju\n", port->port_name,
4729 				       port->targ_port, retval,
4730 				       (uintmax_t)lun->target.id);
4731 			} else
4732 				port->status &= ~CTL_PORT_STATUS_TARG_ONLINE;
4733 
4734 			if ((port->status & CTL_PORT_STATUS_TARG_ONLINE) != 0)
4735 				continue;
4736 
4737 #if 0
4738 			port->port_offline(port->onoff_arg);
4739 			port->status &= ~CTL_PORT_STATUS_ONLINE;
4740 #endif
4741 		}
4742 	}
4743 #endif
4744 
4745 	/*
4746 	 * Tell the backend to free resources, if this LUN has a backend.
4747 	 */
4748 	atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4749 	lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4750 
4751 	ctl_tpc_shutdown(lun);
4752 	mtx_destroy(&lun->lun_lock);
4753 	free(lun->lun_devid, M_CTL);
4754 	if (lun->flags & CTL_LUN_MALLOCED)
4755 		free(lun, M_CTL);
4756 
4757 	STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4758 		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
4759 			nlun->pending_ua[i] |= CTL_UA_LUN_CHANGE;
4760 		}
4761 	}
4762 
4763 	return (0);
4764 }
4765 
4766 static void
4767 ctl_create_lun(struct ctl_be_lun *be_lun)
4768 {
4769 	struct ctl_softc *ctl_softc;
4770 
4771 	ctl_softc = control_softc;
4772 
4773 	/*
4774 	 * ctl_alloc_lun() should handle all potential failure cases.
4775 	 */
4776 	ctl_alloc_lun(ctl_softc, NULL, be_lun, ctl_softc->target);
4777 }
4778 
4779 int
4780 ctl_add_lun(struct ctl_be_lun *be_lun)
4781 {
4782 	struct ctl_softc *ctl_softc = control_softc;
4783 
4784 	mtx_lock(&ctl_softc->ctl_lock);
4785 	STAILQ_INSERT_TAIL(&ctl_softc->pending_lun_queue, be_lun, links);
4786 	mtx_unlock(&ctl_softc->ctl_lock);
4787 	wakeup(&ctl_softc->pending_lun_queue);
4788 
4789 	return (0);
4790 }
4791 
4792 int
4793 ctl_enable_lun(struct ctl_be_lun *be_lun)
4794 {
4795 	struct ctl_softc *ctl_softc;
4796 	struct ctl_port *port, *nport;
4797 	struct ctl_lun *lun;
4798 	int retval;
4799 
4800 	ctl_softc = control_softc;
4801 
4802 	lun = (struct ctl_lun *)be_lun->ctl_lun;
4803 
4804 	mtx_lock(&ctl_softc->ctl_lock);
4805 	mtx_lock(&lun->lun_lock);
4806 	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4807 		/*
4808 		 * eh?  Why did we get called if the LUN is already
4809 		 * enabled?
4810 		 */
4811 		mtx_unlock(&lun->lun_lock);
4812 		mtx_unlock(&ctl_softc->ctl_lock);
4813 		return (0);
4814 	}
4815 	lun->flags &= ~CTL_LUN_DISABLED;
4816 	mtx_unlock(&lun->lun_lock);
4817 
4818 	for (port = STAILQ_FIRST(&ctl_softc->port_list); port != NULL; port = nport) {
4819 		nport = STAILQ_NEXT(port, links);
4820 
4821 		/*
4822 		 * Drop the lock while we call the FETD's enable routine.
4823 		 * This can lead to a callback into CTL (at least in the
4824 		 * case of the internal initiator frontend.
4825 		 */
4826 		mtx_unlock(&ctl_softc->ctl_lock);
4827 		retval = port->lun_enable(port->targ_lun_arg, lun->target,lun->lun);
4828 		mtx_lock(&ctl_softc->ctl_lock);
4829 		if (retval != 0) {
4830 			printf("%s: FETD %s port %d returned error "
4831 			       "%d for lun_enable on target %ju lun %jd\n",
4832 			       __func__, port->port_name, port->targ_port, retval,
4833 			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4834 		}
4835 #if 0
4836 		 else {
4837             /* NOTE:  TODO:  why does lun enable affect port status? */
4838 			port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4839 		}
4840 #endif
4841 	}
4842 
4843 	mtx_unlock(&ctl_softc->ctl_lock);
4844 
4845 	return (0);
4846 }
4847 
4848 int
4849 ctl_disable_lun(struct ctl_be_lun *be_lun)
4850 {
4851 	struct ctl_softc *ctl_softc;
4852 	struct ctl_port *port;
4853 	struct ctl_lun *lun;
4854 	int retval;
4855 
4856 	ctl_softc = control_softc;
4857 
4858 	lun = (struct ctl_lun *)be_lun->ctl_lun;
4859 
4860 	mtx_lock(&ctl_softc->ctl_lock);
4861 	mtx_lock(&lun->lun_lock);
4862 	if (lun->flags & CTL_LUN_DISABLED) {
4863 		mtx_unlock(&lun->lun_lock);
4864 		mtx_unlock(&ctl_softc->ctl_lock);
4865 		return (0);
4866 	}
4867 	lun->flags |= CTL_LUN_DISABLED;
4868 	mtx_unlock(&lun->lun_lock);
4869 
4870 	STAILQ_FOREACH(port, &ctl_softc->port_list, links) {
4871 		mtx_unlock(&ctl_softc->ctl_lock);
4872 		/*
4873 		 * Drop the lock before we call the frontend's disable
4874 		 * routine, to avoid lock order reversals.
4875 		 *
4876 		 * XXX KDM what happens if the frontend list changes while
4877 		 * we're traversing it?  It's unlikely, but should be handled.
4878 		 */
4879 		retval = port->lun_disable(port->targ_lun_arg, lun->target,
4880 					 lun->lun);
4881 		mtx_lock(&ctl_softc->ctl_lock);
4882 		if (retval != 0) {
4883 			printf("ctl_alloc_lun: FETD %s port %d returned error "
4884 			       "%d for lun_disable on target %ju lun %jd\n",
4885 			       port->port_name, port->targ_port, retval,
4886 			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4887 		}
4888 	}
4889 
4890 	mtx_unlock(&ctl_softc->ctl_lock);
4891 
4892 	return (0);
4893 }
4894 
4895 int
4896 ctl_start_lun(struct ctl_be_lun *be_lun)
4897 {
4898 	struct ctl_softc *ctl_softc;
4899 	struct ctl_lun *lun;
4900 
4901 	ctl_softc = control_softc;
4902 
4903 	lun = (struct ctl_lun *)be_lun->ctl_lun;
4904 
4905 	mtx_lock(&lun->lun_lock);
4906 	lun->flags &= ~CTL_LUN_STOPPED;
4907 	mtx_unlock(&lun->lun_lock);
4908 
4909 	return (0);
4910 }
4911 
4912 int
4913 ctl_stop_lun(struct ctl_be_lun *be_lun)
4914 {
4915 	struct ctl_softc *ctl_softc;
4916 	struct ctl_lun *lun;
4917 
4918 	ctl_softc = control_softc;
4919 
4920 	lun = (struct ctl_lun *)be_lun->ctl_lun;
4921 
4922 	mtx_lock(&lun->lun_lock);
4923 	lun->flags |= CTL_LUN_STOPPED;
4924 	mtx_unlock(&lun->lun_lock);
4925 
4926 	return (0);
4927 }
4928 
4929 int
4930 ctl_lun_offline(struct ctl_be_lun *be_lun)
4931 {
4932 	struct ctl_softc *ctl_softc;
4933 	struct ctl_lun *lun;
4934 
4935 	ctl_softc = control_softc;
4936 
4937 	lun = (struct ctl_lun *)be_lun->ctl_lun;
4938 
4939 	mtx_lock(&lun->lun_lock);
4940 	lun->flags |= CTL_LUN_OFFLINE;
4941 	mtx_unlock(&lun->lun_lock);
4942 
4943 	return (0);
4944 }
4945 
4946 int
4947 ctl_lun_online(struct ctl_be_lun *be_lun)
4948 {
4949 	struct ctl_softc *ctl_softc;
4950 	struct ctl_lun *lun;
4951 
4952 	ctl_softc = control_softc;
4953 
4954 	lun = (struct ctl_lun *)be_lun->ctl_lun;
4955 
4956 	mtx_lock(&lun->lun_lock);
4957 	lun->flags &= ~CTL_LUN_OFFLINE;
4958 	mtx_unlock(&lun->lun_lock);
4959 
4960 	return (0);
4961 }
4962 
4963 int
4964 ctl_invalidate_lun(struct ctl_be_lun *be_lun)
4965 {
4966 	struct ctl_softc *ctl_softc;
4967 	struct ctl_lun *lun;
4968 
4969 	ctl_softc = control_softc;
4970 
4971 	lun = (struct ctl_lun *)be_lun->ctl_lun;
4972 
4973 	mtx_lock(&lun->lun_lock);
4974 
4975 	/*
4976 	 * The LUN needs to be disabled before it can be marked invalid.
4977 	 */
4978 	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4979 		mtx_unlock(&lun->lun_lock);
4980 		return (-1);
4981 	}
4982 	/*
4983 	 * Mark the LUN invalid.
4984 	 */
4985 	lun->flags |= CTL_LUN_INVALID;
4986 
4987 	/*
4988 	 * If there is nothing in the OOA queue, go ahead and free the LUN.
4989 	 * If we have something in the OOA queue, we'll free it when the
4990 	 * last I/O completes.
4991 	 */
4992 	if (TAILQ_EMPTY(&lun->ooa_queue)) {
4993 		mtx_unlock(&lun->lun_lock);
4994 		mtx_lock(&ctl_softc->ctl_lock);
4995 		ctl_free_lun(lun);
4996 		mtx_unlock(&ctl_softc->ctl_lock);
4997 	} else
4998 		mtx_unlock(&lun->lun_lock);
4999 
5000 	return (0);
5001 }
5002 
5003 int
5004 ctl_lun_inoperable(struct ctl_be_lun *be_lun)
5005 {
5006 	struct ctl_softc *ctl_softc;
5007 	struct ctl_lun *lun;
5008 
5009 	ctl_softc = control_softc;
5010 	lun = (struct ctl_lun *)be_lun->ctl_lun;
5011 
5012 	mtx_lock(&lun->lun_lock);
5013 	lun->flags |= CTL_LUN_INOPERABLE;
5014 	mtx_unlock(&lun->lun_lock);
5015 
5016 	return (0);
5017 }
5018 
5019 int
5020 ctl_lun_operable(struct ctl_be_lun *be_lun)
5021 {
5022 	struct ctl_softc *ctl_softc;
5023 	struct ctl_lun *lun;
5024 
5025 	ctl_softc = control_softc;
5026 	lun = (struct ctl_lun *)be_lun->ctl_lun;
5027 
5028 	mtx_lock(&lun->lun_lock);
5029 	lun->flags &= ~CTL_LUN_INOPERABLE;
5030 	mtx_unlock(&lun->lun_lock);
5031 
5032 	return (0);
5033 }
5034 
5035 int
5036 ctl_lun_power_lock(struct ctl_be_lun *be_lun, struct ctl_nexus *nexus,
5037 		   int lock)
5038 {
5039 	struct ctl_softc *softc;
5040 	struct ctl_lun *lun;
5041 	struct copan_aps_subpage *current_sp;
5042 	struct ctl_page_index *page_index;
5043 	int i;
5044 
5045 	softc = control_softc;
5046 
5047 	mtx_lock(&softc->ctl_lock);
5048 
5049 	lun = (struct ctl_lun *)be_lun->ctl_lun;
5050 	mtx_lock(&lun->lun_lock);
5051 
5052 	page_index = NULL;
5053 	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
5054 		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
5055 		     APS_PAGE_CODE)
5056 			continue;
5057 
5058 		if (lun->mode_pages.index[i].subpage != APS_SUBPAGE_CODE)
5059 			continue;
5060 		page_index = &lun->mode_pages.index[i];
5061 	}
5062 
5063 	if (page_index == NULL) {
5064 		mtx_unlock(&lun->lun_lock);
5065 		mtx_unlock(&softc->ctl_lock);
5066 		printf("%s: APS subpage not found for lun %ju!\n", __func__,
5067 		       (uintmax_t)lun->lun);
5068 		return (1);
5069 	}
5070 #if 0
5071 	if ((softc->aps_locked_lun != 0)
5072 	 && (softc->aps_locked_lun != lun->lun)) {
5073 		printf("%s: attempt to lock LUN %llu when %llu is already "
5074 		       "locked\n");
5075 		mtx_unlock(&lun->lun_lock);
5076 		mtx_unlock(&softc->ctl_lock);
5077 		return (1);
5078 	}
5079 #endif
5080 
5081 	current_sp = (struct copan_aps_subpage *)(page_index->page_data +
5082 		(page_index->page_len * CTL_PAGE_CURRENT));
5083 
5084 	if (lock != 0) {
5085 		current_sp->lock_active = APS_LOCK_ACTIVE;
5086 		softc->aps_locked_lun = lun->lun;
5087 	} else {
5088 		current_sp->lock_active = 0;
5089 		softc->aps_locked_lun = 0;
5090 	}
5091 
5092 
5093 	/*
5094 	 * If we're in HA mode, try to send the lock message to the other
5095 	 * side.
5096 	 */
5097 	if (ctl_is_single == 0) {
5098 		int isc_retval;
5099 		union ctl_ha_msg lock_msg;
5100 
5101 		lock_msg.hdr.nexus = *nexus;
5102 		lock_msg.hdr.msg_type = CTL_MSG_APS_LOCK;
5103 		if (lock != 0)
5104 			lock_msg.aps.lock_flag = 1;
5105 		else
5106 			lock_msg.aps.lock_flag = 0;
5107 		isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &lock_msg,
5108 					 sizeof(lock_msg), 0);
5109 		if (isc_retval > CTL_HA_STATUS_SUCCESS) {
5110 			printf("%s: APS (lock=%d) error returned from "
5111 			       "ctl_ha_msg_send: %d\n", __func__, lock, isc_retval);
5112 			mtx_unlock(&lun->lun_lock);
5113 			mtx_unlock(&softc->ctl_lock);
5114 			return (1);
5115 		}
5116 	}
5117 
5118 	mtx_unlock(&lun->lun_lock);
5119 	mtx_unlock(&softc->ctl_lock);
5120 
5121 	return (0);
5122 }
5123 
5124 void
5125 ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
5126 {
5127 	struct ctl_lun *lun;
5128 	struct ctl_softc *softc;
5129 	int i;
5130 
5131 	softc = control_softc;
5132 
5133 	lun = (struct ctl_lun *)be_lun->ctl_lun;
5134 
5135 	mtx_lock(&lun->lun_lock);
5136 
5137 	for (i = 0; i < CTL_MAX_INITIATORS; i++)
5138 		lun->pending_ua[i] |= CTL_UA_CAPACITY_CHANGED;
5139 
5140 	mtx_unlock(&lun->lun_lock);
5141 }
5142 
5143 /*
5144  * Backend "memory move is complete" callback for requests that never
5145  * make it down to say RAIDCore's configuration code.
5146  */
5147 int
5148 ctl_config_move_done(union ctl_io *io)
5149 {
5150 	int retval;
5151 
5152 	retval = CTL_RETVAL_COMPLETE;
5153 
5154 
5155 	CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
5156 	/*
5157 	 * XXX KDM this shouldn't happen, but what if it does?
5158 	 */
5159 	if (io->io_hdr.io_type != CTL_IO_SCSI)
5160 		panic("I/O type isn't CTL_IO_SCSI!");
5161 
5162 	if ((io->io_hdr.port_status == 0)
5163 	 && ((io->io_hdr.flags & CTL_FLAG_ABORT) == 0)
5164 	 && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE))
5165 		io->io_hdr.status = CTL_SUCCESS;
5166 	else if ((io->io_hdr.port_status != 0)
5167 	      && ((io->io_hdr.flags & CTL_FLAG_ABORT) == 0)
5168 	      && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE)){
5169 		/*
5170 		 * For hardware error sense keys, the sense key
5171 		 * specific value is defined to be a retry count,
5172 		 * but we use it to pass back an internal FETD
5173 		 * error code.  XXX KDM  Hopefully the FETD is only
5174 		 * using 16 bits for an error code, since that's
5175 		 * all the space we have in the sks field.
5176 		 */
5177 		ctl_set_internal_failure(&io->scsiio,
5178 					 /*sks_valid*/ 1,
5179 					 /*retry_count*/
5180 					 io->io_hdr.port_status);
5181 		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5182 			free(io->scsiio.kern_data_ptr, M_CTL);
5183 		ctl_done(io);
5184 		goto bailout;
5185 	}
5186 
5187 	if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
5188 	 || ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)
5189 	 || ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
5190 		/*
5191 		 * XXX KDM just assuming a single pointer here, and not a
5192 		 * S/G list.  If we start using S/G lists for config data,
5193 		 * we'll need to know how to clean them up here as well.
5194 		 */
5195 		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5196 			free(io->scsiio.kern_data_ptr, M_CTL);
5197 		/* Hopefully the user has already set the status... */
5198 		ctl_done(io);
5199 	} else {
5200 		/*
5201 		 * XXX KDM now we need to continue data movement.  Some
5202 		 * options:
5203 		 * - call ctl_scsiio() again?  We don't do this for data
5204 		 *   writes, because for those at least we know ahead of
5205 		 *   time where the write will go and how long it is.  For
5206 		 *   config writes, though, that information is largely
5207 		 *   contained within the write itself, thus we need to
5208 		 *   parse out the data again.
5209 		 *
5210 		 * - Call some other function once the data is in?
5211 		 */
5212 
5213 		/*
5214 		 * XXX KDM call ctl_scsiio() again for now, and check flag
5215 		 * bits to see whether we're allocated or not.
5216 		 */
5217 		retval = ctl_scsiio(&io->scsiio);
5218 	}
5219 bailout:
5220 	return (retval);
5221 }
5222 
5223 /*
5224  * This gets called by a backend driver when it is done with a
5225  * data_submit method.
5226  */
5227 void
5228 ctl_data_submit_done(union ctl_io *io)
5229 {
5230 	/*
5231 	 * If the IO_CONT flag is set, we need to call the supplied
5232 	 * function to continue processing the I/O, instead of completing
5233 	 * the I/O just yet.
5234 	 *
5235 	 * If there is an error, though, we don't want to keep processing.
5236 	 * Instead, just send status back to the initiator.
5237 	 */
5238 	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5239 	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5240 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5241 	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5242 		io->scsiio.io_cont(io);
5243 		return;
5244 	}
5245 	ctl_done(io);
5246 }
5247 
5248 /*
5249  * This gets called by a backend driver when it is done with a
5250  * configuration write.
5251  */
5252 void
5253 ctl_config_write_done(union ctl_io *io)
5254 {
5255 	/*
5256 	 * If the IO_CONT flag is set, we need to call the supplied
5257 	 * function to continue processing the I/O, instead of completing
5258 	 * the I/O just yet.
5259 	 *
5260 	 * If there is an error, though, we don't want to keep processing.
5261 	 * Instead, just send status back to the initiator.
5262 	 */
5263 	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT)
5264 	 && (((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE)
5265 	  || ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS))) {
5266 		io->scsiio.io_cont(io);
5267 		return;
5268 	}
5269 	/*
5270 	 * Since a configuration write can be done for commands that actually
5271 	 * have data allocated, like write buffer, and commands that have
5272 	 * no data, like start/stop unit, we need to check here.
5273 	 */
5274 	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT)
5275 		free(io->scsiio.kern_data_ptr, M_CTL);
5276 	ctl_done(io);
5277 }
5278 
5279 /*
5280  * SCSI release command.
5281  */
5282 int
5283 ctl_scsi_release(struct ctl_scsiio *ctsio)
5284 {
5285 	int length, longid, thirdparty_id, resv_id;
5286 	struct ctl_softc *ctl_softc;
5287 	struct ctl_lun *lun;
5288 
5289 	length = 0;
5290 	resv_id = 0;
5291 
5292 	CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5293 
5294 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5295 	ctl_softc = control_softc;
5296 
5297 	switch (ctsio->cdb[0]) {
5298 	case RELEASE_10: {
5299 		struct scsi_release_10 *cdb;
5300 
5301 		cdb = (struct scsi_release_10 *)ctsio->cdb;
5302 
5303 		if (cdb->byte2 & SR10_LONGID)
5304 			longid = 1;
5305 		else
5306 			thirdparty_id = cdb->thirdparty_id;
5307 
5308 		resv_id = cdb->resv_id;
5309 		length = scsi_2btoul(cdb->length);
5310 		break;
5311 	}
5312 	}
5313 
5314 
5315 	/*
5316 	 * XXX KDM right now, we only support LUN reservation.  We don't
5317 	 * support 3rd party reservations, or extent reservations, which
5318 	 * might actually need the parameter list.  If we've gotten this
5319 	 * far, we've got a LUN reservation.  Anything else got kicked out
5320 	 * above.  So, according to SPC, ignore the length.
5321 	 */
5322 	length = 0;
5323 
5324 	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5325 	 && (length > 0)) {
5326 		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5327 		ctsio->kern_data_len = length;
5328 		ctsio->kern_total_len = length;
5329 		ctsio->kern_data_resid = 0;
5330 		ctsio->kern_rel_offset = 0;
5331 		ctsio->kern_sg_entries = 0;
5332 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5333 		ctsio->be_move_done = ctl_config_move_done;
5334 		ctl_datamove((union ctl_io *)ctsio);
5335 
5336 		return (CTL_RETVAL_COMPLETE);
5337 	}
5338 
5339 	if (length > 0)
5340 		thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5341 
5342 	mtx_lock(&lun->lun_lock);
5343 
5344 	/*
5345 	 * According to SPC, it is not an error for an intiator to attempt
5346 	 * to release a reservation on a LUN that isn't reserved, or that
5347 	 * is reserved by another initiator.  The reservation can only be
5348 	 * released, though, by the initiator who made it or by one of
5349 	 * several reset type events.
5350 	 */
5351 	if (lun->flags & CTL_LUN_RESERVED) {
5352 		if ((ctsio->io_hdr.nexus.initid.id == lun->rsv_nexus.initid.id)
5353 		 && (ctsio->io_hdr.nexus.targ_port == lun->rsv_nexus.targ_port)
5354 		 && (ctsio->io_hdr.nexus.targ_target.id ==
5355 		     lun->rsv_nexus.targ_target.id)) {
5356 			lun->flags &= ~CTL_LUN_RESERVED;
5357 		}
5358 	}
5359 
5360 	mtx_unlock(&lun->lun_lock);
5361 
5362 	ctsio->scsi_status = SCSI_STATUS_OK;
5363 	ctsio->io_hdr.status = CTL_SUCCESS;
5364 
5365 	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5366 		free(ctsio->kern_data_ptr, M_CTL);
5367 		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5368 	}
5369 
5370 	ctl_done((union ctl_io *)ctsio);
5371 	return (CTL_RETVAL_COMPLETE);
5372 }
5373 
5374 int
5375 ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5376 {
5377 	int extent, thirdparty, longid;
5378 	int resv_id, length;
5379 	uint64_t thirdparty_id;
5380 	struct ctl_softc *ctl_softc;
5381 	struct ctl_lun *lun;
5382 
5383 	extent = 0;
5384 	thirdparty = 0;
5385 	longid = 0;
5386 	resv_id = 0;
5387 	length = 0;
5388 	thirdparty_id = 0;
5389 
5390 	CTL_DEBUG_PRINT(("ctl_reserve\n"));
5391 
5392 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5393 	ctl_softc = control_softc;
5394 
5395 	switch (ctsio->cdb[0]) {
5396 	case RESERVE_10: {
5397 		struct scsi_reserve_10 *cdb;
5398 
5399 		cdb = (struct scsi_reserve_10 *)ctsio->cdb;
5400 
5401 		if (cdb->byte2 & SR10_LONGID)
5402 			longid = 1;
5403 		else
5404 			thirdparty_id = cdb->thirdparty_id;
5405 
5406 		resv_id = cdb->resv_id;
5407 		length = scsi_2btoul(cdb->length);
5408 		break;
5409 	}
5410 	}
5411 
5412 	/*
5413 	 * XXX KDM right now, we only support LUN reservation.  We don't
5414 	 * support 3rd party reservations, or extent reservations, which
5415 	 * might actually need the parameter list.  If we've gotten this
5416 	 * far, we've got a LUN reservation.  Anything else got kicked out
5417 	 * above.  So, according to SPC, ignore the length.
5418 	 */
5419 	length = 0;
5420 
5421 	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5422 	 && (length > 0)) {
5423 		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5424 		ctsio->kern_data_len = length;
5425 		ctsio->kern_total_len = length;
5426 		ctsio->kern_data_resid = 0;
5427 		ctsio->kern_rel_offset = 0;
5428 		ctsio->kern_sg_entries = 0;
5429 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5430 		ctsio->be_move_done = ctl_config_move_done;
5431 		ctl_datamove((union ctl_io *)ctsio);
5432 
5433 		return (CTL_RETVAL_COMPLETE);
5434 	}
5435 
5436 	if (length > 0)
5437 		thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5438 
5439 	mtx_lock(&lun->lun_lock);
5440 	if (lun->flags & CTL_LUN_RESERVED) {
5441 		if ((ctsio->io_hdr.nexus.initid.id != lun->rsv_nexus.initid.id)
5442 		 || (ctsio->io_hdr.nexus.targ_port != lun->rsv_nexus.targ_port)
5443 		 || (ctsio->io_hdr.nexus.targ_target.id !=
5444 		     lun->rsv_nexus.targ_target.id)) {
5445 			ctsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
5446 			ctsio->io_hdr.status = CTL_SCSI_ERROR;
5447 			goto bailout;
5448 		}
5449 	}
5450 
5451 	lun->flags |= CTL_LUN_RESERVED;
5452 	lun->rsv_nexus = ctsio->io_hdr.nexus;
5453 
5454 	ctsio->scsi_status = SCSI_STATUS_OK;
5455 	ctsio->io_hdr.status = CTL_SUCCESS;
5456 
5457 bailout:
5458 	mtx_unlock(&lun->lun_lock);
5459 
5460 	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5461 		free(ctsio->kern_data_ptr, M_CTL);
5462 		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5463 	}
5464 
5465 	ctl_done((union ctl_io *)ctsio);
5466 	return (CTL_RETVAL_COMPLETE);
5467 }
5468 
5469 int
5470 ctl_start_stop(struct ctl_scsiio *ctsio)
5471 {
5472 	struct scsi_start_stop_unit *cdb;
5473 	struct ctl_lun *lun;
5474 	struct ctl_softc *ctl_softc;
5475 	int retval;
5476 
5477 	CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5478 
5479 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5480 	ctl_softc = control_softc;
5481 	retval = 0;
5482 
5483 	cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5484 
5485 	/*
5486 	 * XXX KDM
5487 	 * We don't support the immediate bit on a stop unit.  In order to
5488 	 * do that, we would need to code up a way to know that a stop is
5489 	 * pending, and hold off any new commands until it completes, one
5490 	 * way or another.  Then we could accept or reject those commands
5491 	 * depending on its status.  We would almost need to do the reverse
5492 	 * of what we do below for an immediate start -- return the copy of
5493 	 * the ctl_io to the FETD with status to send to the host (and to
5494 	 * free the copy!) and then free the original I/O once the stop
5495 	 * actually completes.  That way, the OOA queue mechanism can work
5496 	 * to block commands that shouldn't proceed.  Another alternative
5497 	 * would be to put the copy in the queue in place of the original,
5498 	 * and return the original back to the caller.  That could be
5499 	 * slightly safer..
5500 	 */
5501 	if ((cdb->byte2 & SSS_IMMED)
5502 	 && ((cdb->how & SSS_START) == 0)) {
5503 		ctl_set_invalid_field(ctsio,
5504 				      /*sks_valid*/ 1,
5505 				      /*command*/ 1,
5506 				      /*field*/ 1,
5507 				      /*bit_valid*/ 1,
5508 				      /*bit*/ 0);
5509 		ctl_done((union ctl_io *)ctsio);
5510 		return (CTL_RETVAL_COMPLETE);
5511 	}
5512 
5513 	if ((lun->flags & CTL_LUN_PR_RESERVED)
5514 	 && ((cdb->how & SSS_START)==0)) {
5515 		uint32_t residx;
5516 
5517 		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5518 		if (!lun->per_res[residx].registered
5519 		 || (lun->pr_res_idx!=residx && lun->res_type < 4)) {
5520 
5521 			ctl_set_reservation_conflict(ctsio);
5522 			ctl_done((union ctl_io *)ctsio);
5523 			return (CTL_RETVAL_COMPLETE);
5524 		}
5525 	}
5526 
5527 	/*
5528 	 * If there is no backend on this device, we can't start or stop
5529 	 * it.  In theory we shouldn't get any start/stop commands in the
5530 	 * first place at this level if the LUN doesn't have a backend.
5531 	 * That should get stopped by the command decode code.
5532 	 */
5533 	if (lun->backend == NULL) {
5534 		ctl_set_invalid_opcode(ctsio);
5535 		ctl_done((union ctl_io *)ctsio);
5536 		return (CTL_RETVAL_COMPLETE);
5537 	}
5538 
5539 	/*
5540 	 * XXX KDM Copan-specific offline behavior.
5541 	 * Figure out a reasonable way to port this?
5542 	 */
5543 #ifdef NEEDTOPORT
5544 	mtx_lock(&lun->lun_lock);
5545 
5546 	if (((cdb->byte2 & SSS_ONOFFLINE) == 0)
5547 	 && (lun->flags & CTL_LUN_OFFLINE)) {
5548 		/*
5549 		 * If the LUN is offline, and the on/offline bit isn't set,
5550 		 * reject the start or stop.  Otherwise, let it through.
5551 		 */
5552 		mtx_unlock(&lun->lun_lock);
5553 		ctl_set_lun_not_ready(ctsio);
5554 		ctl_done((union ctl_io *)ctsio);
5555 	} else {
5556 		mtx_unlock(&lun->lun_lock);
5557 #endif /* NEEDTOPORT */
5558 		/*
5559 		 * This could be a start or a stop when we're online,
5560 		 * or a stop/offline or start/online.  A start or stop when
5561 		 * we're offline is covered in the case above.
5562 		 */
5563 		/*
5564 		 * In the non-immediate case, we send the request to
5565 		 * the backend and return status to the user when
5566 		 * it is done.
5567 		 *
5568 		 * In the immediate case, we allocate a new ctl_io
5569 		 * to hold a copy of the request, and send that to
5570 		 * the backend.  We then set good status on the
5571 		 * user's request and return it immediately.
5572 		 */
5573 		if (cdb->byte2 & SSS_IMMED) {
5574 			union ctl_io *new_io;
5575 
5576 			new_io = ctl_alloc_io(ctsio->io_hdr.pool);
5577 			if (new_io == NULL) {
5578 				ctl_set_busy(ctsio);
5579 				ctl_done((union ctl_io *)ctsio);
5580 			} else {
5581 				ctl_copy_io((union ctl_io *)ctsio,
5582 					    new_io);
5583 				retval = lun->backend->config_write(new_io);
5584 				ctl_set_success(ctsio);
5585 				ctl_done((union ctl_io *)ctsio);
5586 			}
5587 		} else {
5588 			retval = lun->backend->config_write(
5589 				(union ctl_io *)ctsio);
5590 		}
5591 #ifdef NEEDTOPORT
5592 	}
5593 #endif
5594 	return (retval);
5595 }
5596 
5597 /*
5598  * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5599  * we don't really do anything with the LBA and length fields if the user
5600  * passes them in.  Instead we'll just flush out the cache for the entire
5601  * LUN.
5602  */
5603 int
5604 ctl_sync_cache(struct ctl_scsiio *ctsio)
5605 {
5606 	struct ctl_lun *lun;
5607 	struct ctl_softc *ctl_softc;
5608 	uint64_t starting_lba;
5609 	uint32_t block_count;
5610 	int retval;
5611 
5612 	CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5613 
5614 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5615 	ctl_softc = control_softc;
5616 	retval = 0;
5617 
5618 	switch (ctsio->cdb[0]) {
5619 	case SYNCHRONIZE_CACHE: {
5620 		struct scsi_sync_cache *cdb;
5621 		cdb = (struct scsi_sync_cache *)ctsio->cdb;
5622 
5623 		starting_lba = scsi_4btoul(cdb->begin_lba);
5624 		block_count = scsi_2btoul(cdb->lb_count);
5625 		break;
5626 	}
5627 	case SYNCHRONIZE_CACHE_16: {
5628 		struct scsi_sync_cache_16 *cdb;
5629 		cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5630 
5631 		starting_lba = scsi_8btou64(cdb->begin_lba);
5632 		block_count = scsi_4btoul(cdb->lb_count);
5633 		break;
5634 	}
5635 	default:
5636 		ctl_set_invalid_opcode(ctsio);
5637 		ctl_done((union ctl_io *)ctsio);
5638 		goto bailout;
5639 		break; /* NOTREACHED */
5640 	}
5641 
5642 	/*
5643 	 * We check the LBA and length, but don't do anything with them.
5644 	 * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5645 	 * get flushed.  This check will just help satisfy anyone who wants
5646 	 * to see an error for an out of range LBA.
5647 	 */
5648 	if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5649 		ctl_set_lba_out_of_range(ctsio);
5650 		ctl_done((union ctl_io *)ctsio);
5651 		goto bailout;
5652 	}
5653 
5654 	/*
5655 	 * If this LUN has no backend, we can't flush the cache anyway.
5656 	 */
5657 	if (lun->backend == NULL) {
5658 		ctl_set_invalid_opcode(ctsio);
5659 		ctl_done((union ctl_io *)ctsio);
5660 		goto bailout;
5661 	}
5662 
5663 	/*
5664 	 * Check to see whether we're configured to send the SYNCHRONIZE
5665 	 * CACHE command directly to the back end.
5666 	 */
5667 	mtx_lock(&lun->lun_lock);
5668 	if ((ctl_softc->flags & CTL_FLAG_REAL_SYNC)
5669 	 && (++(lun->sync_count) >= lun->sync_interval)) {
5670 		lun->sync_count = 0;
5671 		mtx_unlock(&lun->lun_lock);
5672 		retval = lun->backend->config_write((union ctl_io *)ctsio);
5673 	} else {
5674 		mtx_unlock(&lun->lun_lock);
5675 		ctl_set_success(ctsio);
5676 		ctl_done((union ctl_io *)ctsio);
5677 	}
5678 
5679 bailout:
5680 
5681 	return (retval);
5682 }
5683 
5684 int
5685 ctl_format(struct ctl_scsiio *ctsio)
5686 {
5687 	struct scsi_format *cdb;
5688 	struct ctl_lun *lun;
5689 	struct ctl_softc *ctl_softc;
5690 	int length, defect_list_len;
5691 
5692 	CTL_DEBUG_PRINT(("ctl_format\n"));
5693 
5694 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5695 	ctl_softc = control_softc;
5696 
5697 	cdb = (struct scsi_format *)ctsio->cdb;
5698 
5699 	length = 0;
5700 	if (cdb->byte2 & SF_FMTDATA) {
5701 		if (cdb->byte2 & SF_LONGLIST)
5702 			length = sizeof(struct scsi_format_header_long);
5703 		else
5704 			length = sizeof(struct scsi_format_header_short);
5705 	}
5706 
5707 	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5708 	 && (length > 0)) {
5709 		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5710 		ctsio->kern_data_len = length;
5711 		ctsio->kern_total_len = length;
5712 		ctsio->kern_data_resid = 0;
5713 		ctsio->kern_rel_offset = 0;
5714 		ctsio->kern_sg_entries = 0;
5715 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5716 		ctsio->be_move_done = ctl_config_move_done;
5717 		ctl_datamove((union ctl_io *)ctsio);
5718 
5719 		return (CTL_RETVAL_COMPLETE);
5720 	}
5721 
5722 	defect_list_len = 0;
5723 
5724 	if (cdb->byte2 & SF_FMTDATA) {
5725 		if (cdb->byte2 & SF_LONGLIST) {
5726 			struct scsi_format_header_long *header;
5727 
5728 			header = (struct scsi_format_header_long *)
5729 				ctsio->kern_data_ptr;
5730 
5731 			defect_list_len = scsi_4btoul(header->defect_list_len);
5732 			if (defect_list_len != 0) {
5733 				ctl_set_invalid_field(ctsio,
5734 						      /*sks_valid*/ 1,
5735 						      /*command*/ 0,
5736 						      /*field*/ 2,
5737 						      /*bit_valid*/ 0,
5738 						      /*bit*/ 0);
5739 				goto bailout;
5740 			}
5741 		} else {
5742 			struct scsi_format_header_short *header;
5743 
5744 			header = (struct scsi_format_header_short *)
5745 				ctsio->kern_data_ptr;
5746 
5747 			defect_list_len = scsi_2btoul(header->defect_list_len);
5748 			if (defect_list_len != 0) {
5749 				ctl_set_invalid_field(ctsio,
5750 						      /*sks_valid*/ 1,
5751 						      /*command*/ 0,
5752 						      /*field*/ 2,
5753 						      /*bit_valid*/ 0,
5754 						      /*bit*/ 0);
5755 				goto bailout;
5756 			}
5757 		}
5758 	}
5759 
5760 	/*
5761 	 * The format command will clear out the "Medium format corrupted"
5762 	 * status if set by the configuration code.  That status is really
5763 	 * just a way to notify the host that we have lost the media, and
5764 	 * get them to issue a command that will basically make them think
5765 	 * they're blowing away the media.
5766 	 */
5767 	mtx_lock(&lun->lun_lock);
5768 	lun->flags &= ~CTL_LUN_INOPERABLE;
5769 	mtx_unlock(&lun->lun_lock);
5770 
5771 	ctsio->scsi_status = SCSI_STATUS_OK;
5772 	ctsio->io_hdr.status = CTL_SUCCESS;
5773 bailout:
5774 
5775 	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5776 		free(ctsio->kern_data_ptr, M_CTL);
5777 		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5778 	}
5779 
5780 	ctl_done((union ctl_io *)ctsio);
5781 	return (CTL_RETVAL_COMPLETE);
5782 }
5783 
5784 int
5785 ctl_read_buffer(struct ctl_scsiio *ctsio)
5786 {
5787 	struct scsi_read_buffer *cdb;
5788 	struct ctl_lun *lun;
5789 	int buffer_offset, len;
5790 	static uint8_t descr[4];
5791 	static uint8_t echo_descr[4] = { 0 };
5792 
5793 	CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5794 
5795 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5796 	cdb = (struct scsi_read_buffer *)ctsio->cdb;
5797 
5798 	if (lun->flags & CTL_LUN_PR_RESERVED) {
5799 		uint32_t residx;
5800 
5801 		/*
5802 		 * XXX KDM need a lock here.
5803 		 */
5804 		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5805 		if ((lun->res_type == SPR_TYPE_EX_AC
5806 		  && residx != lun->pr_res_idx)
5807 		 || ((lun->res_type == SPR_TYPE_EX_AC_RO
5808 		   || lun->res_type == SPR_TYPE_EX_AC_AR)
5809 		  && !lun->per_res[residx].registered)) {
5810 			ctl_set_reservation_conflict(ctsio);
5811 			ctl_done((union ctl_io *)ctsio);
5812 			return (CTL_RETVAL_COMPLETE);
5813 	        }
5814 	}
5815 
5816 	if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA &&
5817 	    (cdb->byte2 & RWB_MODE) != RWB_MODE_ECHO_DESCR &&
5818 	    (cdb->byte2 & RWB_MODE) != RWB_MODE_DESCR) {
5819 		ctl_set_invalid_field(ctsio,
5820 				      /*sks_valid*/ 1,
5821 				      /*command*/ 1,
5822 				      /*field*/ 1,
5823 				      /*bit_valid*/ 1,
5824 				      /*bit*/ 4);
5825 		ctl_done((union ctl_io *)ctsio);
5826 		return (CTL_RETVAL_COMPLETE);
5827 	}
5828 
5829 	len = scsi_3btoul(cdb->length);
5830 	buffer_offset = scsi_3btoul(cdb->offset);
5831 
5832 	if (buffer_offset + len > sizeof(lun->write_buffer)) {
5833 		ctl_set_invalid_field(ctsio,
5834 				      /*sks_valid*/ 1,
5835 				      /*command*/ 1,
5836 				      /*field*/ 6,
5837 				      /*bit_valid*/ 0,
5838 				      /*bit*/ 0);
5839 		ctl_done((union ctl_io *)ctsio);
5840 		return (CTL_RETVAL_COMPLETE);
5841 	}
5842 
5843 	if ((cdb->byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5844 		descr[0] = 0;
5845 		scsi_ulto3b(sizeof(lun->write_buffer), &descr[1]);
5846 		ctsio->kern_data_ptr = descr;
5847 		len = min(len, sizeof(descr));
5848 	} else if ((cdb->byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5849 		ctsio->kern_data_ptr = echo_descr;
5850 		len = min(len, sizeof(echo_descr));
5851 	} else
5852 		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5853 	ctsio->kern_data_len = len;
5854 	ctsio->kern_total_len = len;
5855 	ctsio->kern_data_resid = 0;
5856 	ctsio->kern_rel_offset = 0;
5857 	ctsio->kern_sg_entries = 0;
5858 	ctsio->be_move_done = ctl_config_move_done;
5859 	ctl_datamove((union ctl_io *)ctsio);
5860 
5861 	return (CTL_RETVAL_COMPLETE);
5862 }
5863 
5864 int
5865 ctl_write_buffer(struct ctl_scsiio *ctsio)
5866 {
5867 	struct scsi_write_buffer *cdb;
5868 	struct ctl_lun *lun;
5869 	int buffer_offset, len;
5870 
5871 	CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5872 
5873 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5874 	cdb = (struct scsi_write_buffer *)ctsio->cdb;
5875 
5876 	if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA) {
5877 		ctl_set_invalid_field(ctsio,
5878 				      /*sks_valid*/ 1,
5879 				      /*command*/ 1,
5880 				      /*field*/ 1,
5881 				      /*bit_valid*/ 1,
5882 				      /*bit*/ 4);
5883 		ctl_done((union ctl_io *)ctsio);
5884 		return (CTL_RETVAL_COMPLETE);
5885 	}
5886 
5887 	len = scsi_3btoul(cdb->length);
5888 	buffer_offset = scsi_3btoul(cdb->offset);
5889 
5890 	if (buffer_offset + len > sizeof(lun->write_buffer)) {
5891 		ctl_set_invalid_field(ctsio,
5892 				      /*sks_valid*/ 1,
5893 				      /*command*/ 1,
5894 				      /*field*/ 6,
5895 				      /*bit_valid*/ 0,
5896 				      /*bit*/ 0);
5897 		ctl_done((union ctl_io *)ctsio);
5898 		return (CTL_RETVAL_COMPLETE);
5899 	}
5900 
5901 	/*
5902 	 * If we've got a kernel request that hasn't been malloced yet,
5903 	 * malloc it and tell the caller the data buffer is here.
5904 	 */
5905 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5906 		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5907 		ctsio->kern_data_len = len;
5908 		ctsio->kern_total_len = len;
5909 		ctsio->kern_data_resid = 0;
5910 		ctsio->kern_rel_offset = 0;
5911 		ctsio->kern_sg_entries = 0;
5912 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5913 		ctsio->be_move_done = ctl_config_move_done;
5914 		ctl_datamove((union ctl_io *)ctsio);
5915 
5916 		return (CTL_RETVAL_COMPLETE);
5917 	}
5918 
5919 	ctl_done((union ctl_io *)ctsio);
5920 
5921 	return (CTL_RETVAL_COMPLETE);
5922 }
5923 
5924 int
5925 ctl_write_same(struct ctl_scsiio *ctsio)
5926 {
5927 	struct ctl_lun *lun;
5928 	struct ctl_lba_len_flags *lbalen;
5929 	uint64_t lba;
5930 	uint32_t num_blocks;
5931 	int len, retval;
5932 	uint8_t byte2;
5933 
5934 	retval = CTL_RETVAL_COMPLETE;
5935 
5936 	CTL_DEBUG_PRINT(("ctl_write_same\n"));
5937 
5938 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5939 
5940 	switch (ctsio->cdb[0]) {
5941 	case WRITE_SAME_10: {
5942 		struct scsi_write_same_10 *cdb;
5943 
5944 		cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5945 
5946 		lba = scsi_4btoul(cdb->addr);
5947 		num_blocks = scsi_2btoul(cdb->length);
5948 		byte2 = cdb->byte2;
5949 		break;
5950 	}
5951 	case WRITE_SAME_16: {
5952 		struct scsi_write_same_16 *cdb;
5953 
5954 		cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5955 
5956 		lba = scsi_8btou64(cdb->addr);
5957 		num_blocks = scsi_4btoul(cdb->length);
5958 		byte2 = cdb->byte2;
5959 		break;
5960 	}
5961 	default:
5962 		/*
5963 		 * We got a command we don't support.  This shouldn't
5964 		 * happen, commands should be filtered out above us.
5965 		 */
5966 		ctl_set_invalid_opcode(ctsio);
5967 		ctl_done((union ctl_io *)ctsio);
5968 
5969 		return (CTL_RETVAL_COMPLETE);
5970 		break; /* NOTREACHED */
5971 	}
5972 
5973 	/*
5974 	 * The first check is to make sure we're in bounds, the second
5975 	 * check is to catch wrap-around problems.  If the lba + num blocks
5976 	 * is less than the lba, then we've wrapped around and the block
5977 	 * range is invalid anyway.
5978 	 */
5979 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5980 	 || ((lba + num_blocks) < lba)) {
5981 		ctl_set_lba_out_of_range(ctsio);
5982 		ctl_done((union ctl_io *)ctsio);
5983 		return (CTL_RETVAL_COMPLETE);
5984 	}
5985 
5986 	/* Zero number of blocks means "to the last logical block" */
5987 	if (num_blocks == 0) {
5988 		if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5989 			ctl_set_invalid_field(ctsio,
5990 					      /*sks_valid*/ 0,
5991 					      /*command*/ 1,
5992 					      /*field*/ 0,
5993 					      /*bit_valid*/ 0,
5994 					      /*bit*/ 0);
5995 			ctl_done((union ctl_io *)ctsio);
5996 			return (CTL_RETVAL_COMPLETE);
5997 		}
5998 		num_blocks = (lun->be_lun->maxlba + 1) - lba;
5999 	}
6000 
6001 	len = lun->be_lun->blocksize;
6002 
6003 	/*
6004 	 * If we've got a kernel request that hasn't been malloced yet,
6005 	 * malloc it and tell the caller the data buffer is here.
6006 	 */
6007 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6008 		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
6009 		ctsio->kern_data_len = len;
6010 		ctsio->kern_total_len = len;
6011 		ctsio->kern_data_resid = 0;
6012 		ctsio->kern_rel_offset = 0;
6013 		ctsio->kern_sg_entries = 0;
6014 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6015 		ctsio->be_move_done = ctl_config_move_done;
6016 		ctl_datamove((union ctl_io *)ctsio);
6017 
6018 		return (CTL_RETVAL_COMPLETE);
6019 	}
6020 
6021 	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
6022 	lbalen->lba = lba;
6023 	lbalen->len = num_blocks;
6024 	lbalen->flags = byte2;
6025 	retval = lun->backend->config_write((union ctl_io *)ctsio);
6026 
6027 	return (retval);
6028 }
6029 
6030 int
6031 ctl_unmap(struct ctl_scsiio *ctsio)
6032 {
6033 	struct ctl_lun *lun;
6034 	struct scsi_unmap *cdb;
6035 	struct ctl_ptr_len_flags *ptrlen;
6036 	struct scsi_unmap_header *hdr;
6037 	struct scsi_unmap_desc *buf, *end;
6038 	uint64_t lba;
6039 	uint32_t num_blocks;
6040 	int len, retval;
6041 	uint8_t byte2;
6042 
6043 	retval = CTL_RETVAL_COMPLETE;
6044 
6045 	CTL_DEBUG_PRINT(("ctl_unmap\n"));
6046 
6047 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6048 	cdb = (struct scsi_unmap *)ctsio->cdb;
6049 
6050 	len = scsi_2btoul(cdb->length);
6051 	byte2 = cdb->byte2;
6052 
6053 	/*
6054 	 * If we've got a kernel request that hasn't been malloced yet,
6055 	 * malloc it and tell the caller the data buffer is here.
6056 	 */
6057 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6058 		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
6059 		ctsio->kern_data_len = len;
6060 		ctsio->kern_total_len = len;
6061 		ctsio->kern_data_resid = 0;
6062 		ctsio->kern_rel_offset = 0;
6063 		ctsio->kern_sg_entries = 0;
6064 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6065 		ctsio->be_move_done = ctl_config_move_done;
6066 		ctl_datamove((union ctl_io *)ctsio);
6067 
6068 		return (CTL_RETVAL_COMPLETE);
6069 	}
6070 
6071 	len = ctsio->kern_total_len - ctsio->kern_data_resid;
6072 	hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
6073 	if (len < sizeof (*hdr) ||
6074 	    len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
6075 	    len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
6076 	    scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
6077 		ctl_set_invalid_field(ctsio,
6078 				      /*sks_valid*/ 0,
6079 				      /*command*/ 0,
6080 				      /*field*/ 0,
6081 				      /*bit_valid*/ 0,
6082 				      /*bit*/ 0);
6083 		ctl_done((union ctl_io *)ctsio);
6084 		return (CTL_RETVAL_COMPLETE);
6085 	}
6086 	len = scsi_2btoul(hdr->desc_length);
6087 	buf = (struct scsi_unmap_desc *)(hdr + 1);
6088 	end = buf + len / sizeof(*buf);
6089 
6090 	ptrlen = (struct ctl_ptr_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
6091 	ptrlen->ptr = (void *)buf;
6092 	ptrlen->len = len;
6093 	ptrlen->flags = byte2;
6094 
6095 	for (; buf < end; buf++) {
6096 		lba = scsi_8btou64(buf->lba);
6097 		num_blocks = scsi_4btoul(buf->length);
6098 		if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
6099 		 || ((lba + num_blocks) < lba)) {
6100 			ctl_set_lba_out_of_range(ctsio);
6101 			ctl_done((union ctl_io *)ctsio);
6102 			return (CTL_RETVAL_COMPLETE);
6103 		}
6104 	}
6105 
6106 	retval = lun->backend->config_write((union ctl_io *)ctsio);
6107 
6108 	return (retval);
6109 }
6110 
6111 /*
6112  * Note that this function currently doesn't actually do anything inside
6113  * CTL to enforce things if the DQue bit is turned on.
6114  *
6115  * Also note that this function can't be used in the default case, because
6116  * the DQue bit isn't set in the changeable mask for the control mode page
6117  * anyway.  This is just here as an example for how to implement a page
6118  * handler, and a placeholder in case we want to allow the user to turn
6119  * tagged queueing on and off.
6120  *
6121  * The D_SENSE bit handling is functional, however, and will turn
6122  * descriptor sense on and off for a given LUN.
6123  */
6124 int
6125 ctl_control_page_handler(struct ctl_scsiio *ctsio,
6126 			 struct ctl_page_index *page_index, uint8_t *page_ptr)
6127 {
6128 	struct scsi_control_page *current_cp, *saved_cp, *user_cp;
6129 	struct ctl_lun *lun;
6130 	struct ctl_softc *softc;
6131 	int set_ua;
6132 	uint32_t initidx;
6133 
6134 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6135 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6136 	set_ua = 0;
6137 
6138 	user_cp = (struct scsi_control_page *)page_ptr;
6139 	current_cp = (struct scsi_control_page *)
6140 		(page_index->page_data + (page_index->page_len *
6141 		CTL_PAGE_CURRENT));
6142 	saved_cp = (struct scsi_control_page *)
6143 		(page_index->page_data + (page_index->page_len *
6144 		CTL_PAGE_SAVED));
6145 
6146 	softc = control_softc;
6147 
6148 	mtx_lock(&lun->lun_lock);
6149 	if (((current_cp->rlec & SCP_DSENSE) == 0)
6150 	 && ((user_cp->rlec & SCP_DSENSE) != 0)) {
6151 		/*
6152 		 * Descriptor sense is currently turned off and the user
6153 		 * wants to turn it on.
6154 		 */
6155 		current_cp->rlec |= SCP_DSENSE;
6156 		saved_cp->rlec |= SCP_DSENSE;
6157 		lun->flags |= CTL_LUN_SENSE_DESC;
6158 		set_ua = 1;
6159 	} else if (((current_cp->rlec & SCP_DSENSE) != 0)
6160 		&& ((user_cp->rlec & SCP_DSENSE) == 0)) {
6161 		/*
6162 		 * Descriptor sense is currently turned on, and the user
6163 		 * wants to turn it off.
6164 		 */
6165 		current_cp->rlec &= ~SCP_DSENSE;
6166 		saved_cp->rlec &= ~SCP_DSENSE;
6167 		lun->flags &= ~CTL_LUN_SENSE_DESC;
6168 		set_ua = 1;
6169 	}
6170 	if (current_cp->queue_flags & SCP_QUEUE_DQUE) {
6171 		if (user_cp->queue_flags & SCP_QUEUE_DQUE) {
6172 #ifdef NEEDTOPORT
6173 			csevent_log(CSC_CTL | CSC_SHELF_SW |
6174 				    CTL_UNTAG_TO_UNTAG,
6175 				    csevent_LogType_Trace,
6176 				    csevent_Severity_Information,
6177 				    csevent_AlertLevel_Green,
6178 				    csevent_FRU_Firmware,
6179 				    csevent_FRU_Unknown,
6180 				    "Received untagged to untagged transition");
6181 #endif /* NEEDTOPORT */
6182 		} else {
6183 #ifdef NEEDTOPORT
6184 			csevent_log(CSC_CTL | CSC_SHELF_SW |
6185 				    CTL_UNTAG_TO_TAG,
6186 				    csevent_LogType_ConfigChange,
6187 				    csevent_Severity_Information,
6188 				    csevent_AlertLevel_Green,
6189 				    csevent_FRU_Firmware,
6190 				    csevent_FRU_Unknown,
6191 				    "Received untagged to tagged "
6192 				    "queueing transition");
6193 #endif /* NEEDTOPORT */
6194 
6195 			current_cp->queue_flags &= ~SCP_QUEUE_DQUE;
6196 			saved_cp->queue_flags &= ~SCP_QUEUE_DQUE;
6197 			set_ua = 1;
6198 		}
6199 	} else {
6200 		if (user_cp->queue_flags & SCP_QUEUE_DQUE) {
6201 #ifdef NEEDTOPORT
6202 			csevent_log(CSC_CTL | CSC_SHELF_SW |
6203 				    CTL_TAG_TO_UNTAG,
6204 				    csevent_LogType_ConfigChange,
6205 				    csevent_Severity_Warning,
6206 				    csevent_AlertLevel_Yellow,
6207 				    csevent_FRU_Firmware,
6208 				    csevent_FRU_Unknown,
6209 				    "Received tagged queueing to untagged "
6210 				    "transition");
6211 #endif /* NEEDTOPORT */
6212 
6213 			current_cp->queue_flags |= SCP_QUEUE_DQUE;
6214 			saved_cp->queue_flags |= SCP_QUEUE_DQUE;
6215 			set_ua = 1;
6216 		} else {
6217 #ifdef NEEDTOPORT
6218 			csevent_log(CSC_CTL | CSC_SHELF_SW |
6219 				    CTL_TAG_TO_TAG,
6220 				    csevent_LogType_Trace,
6221 				    csevent_Severity_Information,
6222 				    csevent_AlertLevel_Green,
6223 				    csevent_FRU_Firmware,
6224 				    csevent_FRU_Unknown,
6225 				    "Received tagged queueing to tagged "
6226 				    "queueing transition");
6227 #endif /* NEEDTOPORT */
6228 		}
6229 	}
6230 	if (set_ua != 0) {
6231 		int i;
6232 		/*
6233 		 * Let other initiators know that the mode
6234 		 * parameters for this LUN have changed.
6235 		 */
6236 		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
6237 			if (i == initidx)
6238 				continue;
6239 
6240 			lun->pending_ua[i] |= CTL_UA_MODE_CHANGE;
6241 		}
6242 	}
6243 	mtx_unlock(&lun->lun_lock);
6244 
6245 	return (0);
6246 }
6247 
6248 int
6249 ctl_power_sp_handler(struct ctl_scsiio *ctsio,
6250 		     struct ctl_page_index *page_index, uint8_t *page_ptr)
6251 {
6252 	return (0);
6253 }
6254 
6255 int
6256 ctl_power_sp_sense_handler(struct ctl_scsiio *ctsio,
6257 			   struct ctl_page_index *page_index, int pc)
6258 {
6259 	struct copan_power_subpage *page;
6260 
6261 	page = (struct copan_power_subpage *)page_index->page_data +
6262 		(page_index->page_len * pc);
6263 
6264 	switch (pc) {
6265 	case SMS_PAGE_CTRL_CHANGEABLE >> 6:
6266 		/*
6267 		 * We don't update the changable bits for this page.
6268 		 */
6269 		break;
6270 	case SMS_PAGE_CTRL_CURRENT >> 6:
6271 	case SMS_PAGE_CTRL_DEFAULT >> 6:
6272 	case SMS_PAGE_CTRL_SAVED >> 6:
6273 #ifdef NEEDTOPORT
6274 		ctl_update_power_subpage(page);
6275 #endif
6276 		break;
6277 	default:
6278 #ifdef NEEDTOPORT
6279 		EPRINT(0, "Invalid PC %d!!", pc);
6280 #endif
6281 		break;
6282 	}
6283 	return (0);
6284 }
6285 
6286 
6287 int
6288 ctl_aps_sp_handler(struct ctl_scsiio *ctsio,
6289 		   struct ctl_page_index *page_index, uint8_t *page_ptr)
6290 {
6291 	struct copan_aps_subpage *user_sp;
6292 	struct copan_aps_subpage *current_sp;
6293 	union ctl_modepage_info *modepage_info;
6294 	struct ctl_softc *softc;
6295 	struct ctl_lun *lun;
6296 	int retval;
6297 
6298 	retval = CTL_RETVAL_COMPLETE;
6299 	current_sp = (struct copan_aps_subpage *)(page_index->page_data +
6300 		     (page_index->page_len * CTL_PAGE_CURRENT));
6301 	softc = control_softc;
6302 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6303 
6304 	user_sp = (struct copan_aps_subpage *)page_ptr;
6305 
6306 	modepage_info = (union ctl_modepage_info *)
6307 		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6308 
6309 	modepage_info->header.page_code = page_index->page_code & SMPH_PC_MASK;
6310 	modepage_info->header.subpage = page_index->subpage;
6311 	modepage_info->aps.lock_active = user_sp->lock_active;
6312 
6313 	mtx_lock(&softc->ctl_lock);
6314 
6315 	/*
6316 	 * If there is a request to lock the LUN and another LUN is locked
6317 	 * this is an error. If the requested LUN is already locked ignore
6318 	 * the request. If no LUN is locked attempt to lock it.
6319 	 * if there is a request to unlock the LUN and the LUN is currently
6320 	 * locked attempt to unlock it. Otherwise ignore the request. i.e.
6321 	 * if another LUN is locked or no LUN is locked.
6322 	 */
6323 	if (user_sp->lock_active & APS_LOCK_ACTIVE) {
6324 		if (softc->aps_locked_lun == lun->lun) {
6325 			/*
6326 			 * This LUN is already locked, so we're done.
6327 			 */
6328 			retval = CTL_RETVAL_COMPLETE;
6329 		} else if (softc->aps_locked_lun == 0) {
6330 			/*
6331 			 * No one has the lock, pass the request to the
6332 			 * backend.
6333 			 */
6334 			retval = lun->backend->config_write(
6335 				(union ctl_io *)ctsio);
6336 		} else {
6337 			/*
6338 			 * Someone else has the lock, throw out the request.
6339 			 */
6340 			ctl_set_already_locked(ctsio);
6341 			free(ctsio->kern_data_ptr, M_CTL);
6342 			ctl_done((union ctl_io *)ctsio);
6343 
6344 			/*
6345 			 * Set the return value so that ctl_do_mode_select()
6346 			 * won't try to complete the command.  We already
6347 			 * completed it here.
6348 			 */
6349 			retval = CTL_RETVAL_ERROR;
6350 		}
6351 	} else if (softc->aps_locked_lun == lun->lun) {
6352 		/*
6353 		 * This LUN is locked, so pass the unlock request to the
6354 		 * backend.
6355 		 */
6356 		retval = lun->backend->config_write((union ctl_io *)ctsio);
6357 	}
6358 	mtx_unlock(&softc->ctl_lock);
6359 
6360 	return (retval);
6361 }
6362 
6363 int
6364 ctl_debugconf_sp_select_handler(struct ctl_scsiio *ctsio,
6365 				struct ctl_page_index *page_index,
6366 				uint8_t *page_ptr)
6367 {
6368 	uint8_t *c;
6369 	int i;
6370 
6371 	c = ((struct copan_debugconf_subpage *)page_ptr)->ctl_time_io_secs;
6372 	ctl_time_io_secs =
6373 		(c[0] << 8) |
6374 		(c[1] << 0) |
6375 		0;
6376 	CTL_DEBUG_PRINT(("set ctl_time_io_secs to %d\n", ctl_time_io_secs));
6377 	printf("set ctl_time_io_secs to %d\n", ctl_time_io_secs);
6378 	printf("page data:");
6379 	for (i=0; i<8; i++)
6380 		printf(" %.2x",page_ptr[i]);
6381 	printf("\n");
6382 	return (0);
6383 }
6384 
6385 int
6386 ctl_debugconf_sp_sense_handler(struct ctl_scsiio *ctsio,
6387 			       struct ctl_page_index *page_index,
6388 			       int pc)
6389 {
6390 	struct copan_debugconf_subpage *page;
6391 
6392 	page = (struct copan_debugconf_subpage *)page_index->page_data +
6393 		(page_index->page_len * pc);
6394 
6395 	switch (pc) {
6396 	case SMS_PAGE_CTRL_CHANGEABLE >> 6:
6397 	case SMS_PAGE_CTRL_DEFAULT >> 6:
6398 	case SMS_PAGE_CTRL_SAVED >> 6:
6399 		/*
6400 		 * We don't update the changable or default bits for this page.
6401 		 */
6402 		break;
6403 	case SMS_PAGE_CTRL_CURRENT >> 6:
6404 		page->ctl_time_io_secs[0] = ctl_time_io_secs >> 8;
6405 		page->ctl_time_io_secs[1] = ctl_time_io_secs >> 0;
6406 		break;
6407 	default:
6408 #ifdef NEEDTOPORT
6409 		EPRINT(0, "Invalid PC %d!!", pc);
6410 #endif /* NEEDTOPORT */
6411 		break;
6412 	}
6413 	return (0);
6414 }
6415 
6416 
6417 static int
6418 ctl_do_mode_select(union ctl_io *io)
6419 {
6420 	struct scsi_mode_page_header *page_header;
6421 	struct ctl_page_index *page_index;
6422 	struct ctl_scsiio *ctsio;
6423 	int control_dev, page_len;
6424 	int page_len_offset, page_len_size;
6425 	union ctl_modepage_info *modepage_info;
6426 	struct ctl_lun *lun;
6427 	int *len_left, *len_used;
6428 	int retval, i;
6429 
6430 	ctsio = &io->scsiio;
6431 	page_index = NULL;
6432 	page_len = 0;
6433 	retval = CTL_RETVAL_COMPLETE;
6434 
6435 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6436 
6437 	if (lun->be_lun->lun_type != T_DIRECT)
6438 		control_dev = 1;
6439 	else
6440 		control_dev = 0;
6441 
6442 	modepage_info = (union ctl_modepage_info *)
6443 		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6444 	len_left = &modepage_info->header.len_left;
6445 	len_used = &modepage_info->header.len_used;
6446 
6447 do_next_page:
6448 
6449 	page_header = (struct scsi_mode_page_header *)
6450 		(ctsio->kern_data_ptr + *len_used);
6451 
6452 	if (*len_left == 0) {
6453 		free(ctsio->kern_data_ptr, M_CTL);
6454 		ctl_set_success(ctsio);
6455 		ctl_done((union ctl_io *)ctsio);
6456 		return (CTL_RETVAL_COMPLETE);
6457 	} else if (*len_left < sizeof(struct scsi_mode_page_header)) {
6458 
6459 		free(ctsio->kern_data_ptr, M_CTL);
6460 		ctl_set_param_len_error(ctsio);
6461 		ctl_done((union ctl_io *)ctsio);
6462 		return (CTL_RETVAL_COMPLETE);
6463 
6464 	} else if ((page_header->page_code & SMPH_SPF)
6465 		&& (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
6466 
6467 		free(ctsio->kern_data_ptr, M_CTL);
6468 		ctl_set_param_len_error(ctsio);
6469 		ctl_done((union ctl_io *)ctsio);
6470 		return (CTL_RETVAL_COMPLETE);
6471 	}
6472 
6473 
6474 	/*
6475 	 * XXX KDM should we do something with the block descriptor?
6476 	 */
6477 	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6478 
6479 		if ((control_dev != 0)
6480 		 && (lun->mode_pages.index[i].page_flags &
6481 		     CTL_PAGE_FLAG_DISK_ONLY))
6482 			continue;
6483 
6484 		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
6485 		    (page_header->page_code & SMPH_PC_MASK))
6486 			continue;
6487 
6488 		/*
6489 		 * If neither page has a subpage code, then we've got a
6490 		 * match.
6491 		 */
6492 		if (((lun->mode_pages.index[i].page_code & SMPH_SPF) == 0)
6493 		 && ((page_header->page_code & SMPH_SPF) == 0)) {
6494 			page_index = &lun->mode_pages.index[i];
6495 			page_len = page_header->page_length;
6496 			break;
6497 		}
6498 
6499 		/*
6500 		 * If both pages have subpages, then the subpage numbers
6501 		 * have to match.
6502 		 */
6503 		if ((lun->mode_pages.index[i].page_code & SMPH_SPF)
6504 		  && (page_header->page_code & SMPH_SPF)) {
6505 			struct scsi_mode_page_header_sp *sph;
6506 
6507 			sph = (struct scsi_mode_page_header_sp *)page_header;
6508 
6509 			if (lun->mode_pages.index[i].subpage ==
6510 			    sph->subpage) {
6511 				page_index = &lun->mode_pages.index[i];
6512 				page_len = scsi_2btoul(sph->page_length);
6513 				break;
6514 			}
6515 		}
6516 	}
6517 
6518 	/*
6519 	 * If we couldn't find the page, or if we don't have a mode select
6520 	 * handler for it, send back an error to the user.
6521 	 */
6522 	if ((page_index == NULL)
6523 	 || (page_index->select_handler == NULL)) {
6524 		ctl_set_invalid_field(ctsio,
6525 				      /*sks_valid*/ 1,
6526 				      /*command*/ 0,
6527 				      /*field*/ *len_used,
6528 				      /*bit_valid*/ 0,
6529 				      /*bit*/ 0);
6530 		free(ctsio->kern_data_ptr, M_CTL);
6531 		ctl_done((union ctl_io *)ctsio);
6532 		return (CTL_RETVAL_COMPLETE);
6533 	}
6534 
6535 	if (page_index->page_code & SMPH_SPF) {
6536 		page_len_offset = 2;
6537 		page_len_size = 2;
6538 	} else {
6539 		page_len_size = 1;
6540 		page_len_offset = 1;
6541 	}
6542 
6543 	/*
6544 	 * If the length the initiator gives us isn't the one we specify in
6545 	 * the mode page header, or if they didn't specify enough data in
6546 	 * the CDB to avoid truncating this page, kick out the request.
6547 	 */
6548 	if ((page_len != (page_index->page_len - page_len_offset -
6549 			  page_len_size))
6550 	 || (*len_left < page_index->page_len)) {
6551 
6552 
6553 		ctl_set_invalid_field(ctsio,
6554 				      /*sks_valid*/ 1,
6555 				      /*command*/ 0,
6556 				      /*field*/ *len_used + page_len_offset,
6557 				      /*bit_valid*/ 0,
6558 				      /*bit*/ 0);
6559 		free(ctsio->kern_data_ptr, M_CTL);
6560 		ctl_done((union ctl_io *)ctsio);
6561 		return (CTL_RETVAL_COMPLETE);
6562 	}
6563 
6564 	/*
6565 	 * Run through the mode page, checking to make sure that the bits
6566 	 * the user changed are actually legal for him to change.
6567 	 */
6568 	for (i = 0; i < page_index->page_len; i++) {
6569 		uint8_t *user_byte, *change_mask, *current_byte;
6570 		int bad_bit;
6571 		int j;
6572 
6573 		user_byte = (uint8_t *)page_header + i;
6574 		change_mask = page_index->page_data +
6575 			      (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6576 		current_byte = page_index->page_data +
6577 			       (page_index->page_len * CTL_PAGE_CURRENT) + i;
6578 
6579 		/*
6580 		 * Check to see whether the user set any bits in this byte
6581 		 * that he is not allowed to set.
6582 		 */
6583 		if ((*user_byte & ~(*change_mask)) ==
6584 		    (*current_byte & ~(*change_mask)))
6585 			continue;
6586 
6587 		/*
6588 		 * Go through bit by bit to determine which one is illegal.
6589 		 */
6590 		bad_bit = 0;
6591 		for (j = 7; j >= 0; j--) {
6592 			if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6593 			    (((1 << i) & ~(*change_mask)) & *current_byte)) {
6594 				bad_bit = i;
6595 				break;
6596 			}
6597 		}
6598 		ctl_set_invalid_field(ctsio,
6599 				      /*sks_valid*/ 1,
6600 				      /*command*/ 0,
6601 				      /*field*/ *len_used + i,
6602 				      /*bit_valid*/ 1,
6603 				      /*bit*/ bad_bit);
6604 		free(ctsio->kern_data_ptr, M_CTL);
6605 		ctl_done((union ctl_io *)ctsio);
6606 		return (CTL_RETVAL_COMPLETE);
6607 	}
6608 
6609 	/*
6610 	 * Decrement these before we call the page handler, since we may
6611 	 * end up getting called back one way or another before the handler
6612 	 * returns to this context.
6613 	 */
6614 	*len_left -= page_index->page_len;
6615 	*len_used += page_index->page_len;
6616 
6617 	retval = page_index->select_handler(ctsio, page_index,
6618 					    (uint8_t *)page_header);
6619 
6620 	/*
6621 	 * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6622 	 * wait until this queued command completes to finish processing
6623 	 * the mode page.  If it returns anything other than
6624 	 * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6625 	 * already set the sense information, freed the data pointer, and
6626 	 * completed the io for us.
6627 	 */
6628 	if (retval != CTL_RETVAL_COMPLETE)
6629 		goto bailout_no_done;
6630 
6631 	/*
6632 	 * If the initiator sent us more than one page, parse the next one.
6633 	 */
6634 	if (*len_left > 0)
6635 		goto do_next_page;
6636 
6637 	ctl_set_success(ctsio);
6638 	free(ctsio->kern_data_ptr, M_CTL);
6639 	ctl_done((union ctl_io *)ctsio);
6640 
6641 bailout_no_done:
6642 
6643 	return (CTL_RETVAL_COMPLETE);
6644 
6645 }
6646 
6647 int
6648 ctl_mode_select(struct ctl_scsiio *ctsio)
6649 {
6650 	int param_len, pf, sp;
6651 	int header_size, bd_len;
6652 	int len_left, len_used;
6653 	struct ctl_page_index *page_index;
6654 	struct ctl_lun *lun;
6655 	int control_dev, page_len;
6656 	union ctl_modepage_info *modepage_info;
6657 	int retval;
6658 
6659 	pf = 0;
6660 	sp = 0;
6661 	page_len = 0;
6662 	len_used = 0;
6663 	len_left = 0;
6664 	retval = 0;
6665 	bd_len = 0;
6666 	page_index = NULL;
6667 
6668 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6669 
6670 	if (lun->be_lun->lun_type != T_DIRECT)
6671 		control_dev = 1;
6672 	else
6673 		control_dev = 0;
6674 
6675 	switch (ctsio->cdb[0]) {
6676 	case MODE_SELECT_6: {
6677 		struct scsi_mode_select_6 *cdb;
6678 
6679 		cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6680 
6681 		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6682 		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6683 
6684 		param_len = cdb->length;
6685 		header_size = sizeof(struct scsi_mode_header_6);
6686 		break;
6687 	}
6688 	case MODE_SELECT_10: {
6689 		struct scsi_mode_select_10 *cdb;
6690 
6691 		cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6692 
6693 		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6694 		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6695 
6696 		param_len = scsi_2btoul(cdb->length);
6697 		header_size = sizeof(struct scsi_mode_header_10);
6698 		break;
6699 	}
6700 	default:
6701 		ctl_set_invalid_opcode(ctsio);
6702 		ctl_done((union ctl_io *)ctsio);
6703 		return (CTL_RETVAL_COMPLETE);
6704 		break; /* NOTREACHED */
6705 	}
6706 
6707 	/*
6708 	 * From SPC-3:
6709 	 * "A parameter list length of zero indicates that the Data-Out Buffer
6710 	 * shall be empty. This condition shall not be considered as an error."
6711 	 */
6712 	if (param_len == 0) {
6713 		ctl_set_success(ctsio);
6714 		ctl_done((union ctl_io *)ctsio);
6715 		return (CTL_RETVAL_COMPLETE);
6716 	}
6717 
6718 	/*
6719 	 * Since we'll hit this the first time through, prior to
6720 	 * allocation, we don't need to free a data buffer here.
6721 	 */
6722 	if (param_len < header_size) {
6723 		ctl_set_param_len_error(ctsio);
6724 		ctl_done((union ctl_io *)ctsio);
6725 		return (CTL_RETVAL_COMPLETE);
6726 	}
6727 
6728 	/*
6729 	 * Allocate the data buffer and grab the user's data.  In theory,
6730 	 * we shouldn't have to sanity check the parameter list length here
6731 	 * because the maximum size is 64K.  We should be able to malloc
6732 	 * that much without too many problems.
6733 	 */
6734 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6735 		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6736 		ctsio->kern_data_len = param_len;
6737 		ctsio->kern_total_len = param_len;
6738 		ctsio->kern_data_resid = 0;
6739 		ctsio->kern_rel_offset = 0;
6740 		ctsio->kern_sg_entries = 0;
6741 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6742 		ctsio->be_move_done = ctl_config_move_done;
6743 		ctl_datamove((union ctl_io *)ctsio);
6744 
6745 		return (CTL_RETVAL_COMPLETE);
6746 	}
6747 
6748 	switch (ctsio->cdb[0]) {
6749 	case MODE_SELECT_6: {
6750 		struct scsi_mode_header_6 *mh6;
6751 
6752 		mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6753 		bd_len = mh6->blk_desc_len;
6754 		break;
6755 	}
6756 	case MODE_SELECT_10: {
6757 		struct scsi_mode_header_10 *mh10;
6758 
6759 		mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6760 		bd_len = scsi_2btoul(mh10->blk_desc_len);
6761 		break;
6762 	}
6763 	default:
6764 		panic("Invalid CDB type %#x", ctsio->cdb[0]);
6765 		break;
6766 	}
6767 
6768 	if (param_len < (header_size + bd_len)) {
6769 		free(ctsio->kern_data_ptr, M_CTL);
6770 		ctl_set_param_len_error(ctsio);
6771 		ctl_done((union ctl_io *)ctsio);
6772 		return (CTL_RETVAL_COMPLETE);
6773 	}
6774 
6775 	/*
6776 	 * Set the IO_CONT flag, so that if this I/O gets passed to
6777 	 * ctl_config_write_done(), it'll get passed back to
6778 	 * ctl_do_mode_select() for further processing, or completion if
6779 	 * we're all done.
6780 	 */
6781 	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6782 	ctsio->io_cont = ctl_do_mode_select;
6783 
6784 	modepage_info = (union ctl_modepage_info *)
6785 		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6786 
6787 	memset(modepage_info, 0, sizeof(*modepage_info));
6788 
6789 	len_left = param_len - header_size - bd_len;
6790 	len_used = header_size + bd_len;
6791 
6792 	modepage_info->header.len_left = len_left;
6793 	modepage_info->header.len_used = len_used;
6794 
6795 	return (ctl_do_mode_select((union ctl_io *)ctsio));
6796 }
6797 
6798 int
6799 ctl_mode_sense(struct ctl_scsiio *ctsio)
6800 {
6801 	struct ctl_lun *lun;
6802 	int pc, page_code, dbd, llba, subpage;
6803 	int alloc_len, page_len, header_len, total_len;
6804 	struct scsi_mode_block_descr *block_desc;
6805 	struct ctl_page_index *page_index;
6806 	int control_dev;
6807 
6808 	dbd = 0;
6809 	llba = 0;
6810 	block_desc = NULL;
6811 	page_index = NULL;
6812 
6813 	CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6814 
6815 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6816 
6817 	if (lun->be_lun->lun_type != T_DIRECT)
6818 		control_dev = 1;
6819 	else
6820 		control_dev = 0;
6821 
6822 	if (lun->flags & CTL_LUN_PR_RESERVED) {
6823 		uint32_t residx;
6824 
6825 		/*
6826 		 * XXX KDM need a lock here.
6827 		 */
6828 		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
6829 		if ((lun->res_type == SPR_TYPE_EX_AC
6830 		  && residx != lun->pr_res_idx)
6831 		 || ((lun->res_type == SPR_TYPE_EX_AC_RO
6832 		   || lun->res_type == SPR_TYPE_EX_AC_AR)
6833 		  && !lun->per_res[residx].registered)) {
6834 			ctl_set_reservation_conflict(ctsio);
6835 			ctl_done((union ctl_io *)ctsio);
6836 			return (CTL_RETVAL_COMPLETE);
6837 		}
6838 	}
6839 
6840 	switch (ctsio->cdb[0]) {
6841 	case MODE_SENSE_6: {
6842 		struct scsi_mode_sense_6 *cdb;
6843 
6844 		cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6845 
6846 		header_len = sizeof(struct scsi_mode_hdr_6);
6847 		if (cdb->byte2 & SMS_DBD)
6848 			dbd = 1;
6849 		else
6850 			header_len += sizeof(struct scsi_mode_block_descr);
6851 
6852 		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6853 		page_code = cdb->page & SMS_PAGE_CODE;
6854 		subpage = cdb->subpage;
6855 		alloc_len = cdb->length;
6856 		break;
6857 	}
6858 	case MODE_SENSE_10: {
6859 		struct scsi_mode_sense_10 *cdb;
6860 
6861 		cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6862 
6863 		header_len = sizeof(struct scsi_mode_hdr_10);
6864 
6865 		if (cdb->byte2 & SMS_DBD)
6866 			dbd = 1;
6867 		else
6868 			header_len += sizeof(struct scsi_mode_block_descr);
6869 		if (cdb->byte2 & SMS10_LLBAA)
6870 			llba = 1;
6871 		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6872 		page_code = cdb->page & SMS_PAGE_CODE;
6873 		subpage = cdb->subpage;
6874 		alloc_len = scsi_2btoul(cdb->length);
6875 		break;
6876 	}
6877 	default:
6878 		ctl_set_invalid_opcode(ctsio);
6879 		ctl_done((union ctl_io *)ctsio);
6880 		return (CTL_RETVAL_COMPLETE);
6881 		break; /* NOTREACHED */
6882 	}
6883 
6884 	/*
6885 	 * We have to make a first pass through to calculate the size of
6886 	 * the pages that match the user's query.  Then we allocate enough
6887 	 * memory to hold it, and actually copy the data into the buffer.
6888 	 */
6889 	switch (page_code) {
6890 	case SMS_ALL_PAGES_PAGE: {
6891 		int i;
6892 
6893 		page_len = 0;
6894 
6895 		/*
6896 		 * At the moment, values other than 0 and 0xff here are
6897 		 * reserved according to SPC-3.
6898 		 */
6899 		if ((subpage != SMS_SUBPAGE_PAGE_0)
6900 		 && (subpage != SMS_SUBPAGE_ALL)) {
6901 			ctl_set_invalid_field(ctsio,
6902 					      /*sks_valid*/ 1,
6903 					      /*command*/ 1,
6904 					      /*field*/ 3,
6905 					      /*bit_valid*/ 0,
6906 					      /*bit*/ 0);
6907 			ctl_done((union ctl_io *)ctsio);
6908 			return (CTL_RETVAL_COMPLETE);
6909 		}
6910 
6911 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6912 			if ((control_dev != 0)
6913 			 && (lun->mode_pages.index[i].page_flags &
6914 			     CTL_PAGE_FLAG_DISK_ONLY))
6915 				continue;
6916 
6917 			/*
6918 			 * We don't use this subpage if the user didn't
6919 			 * request all subpages.
6920 			 */
6921 			if ((lun->mode_pages.index[i].subpage != 0)
6922 			 && (subpage == SMS_SUBPAGE_PAGE_0))
6923 				continue;
6924 
6925 #if 0
6926 			printf("found page %#x len %d\n",
6927 			       lun->mode_pages.index[i].page_code &
6928 			       SMPH_PC_MASK,
6929 			       lun->mode_pages.index[i].page_len);
6930 #endif
6931 			page_len += lun->mode_pages.index[i].page_len;
6932 		}
6933 		break;
6934 	}
6935 	default: {
6936 		int i;
6937 
6938 		page_len = 0;
6939 
6940 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6941 			/* Look for the right page code */
6942 			if ((lun->mode_pages.index[i].page_code &
6943 			     SMPH_PC_MASK) != page_code)
6944 				continue;
6945 
6946 			/* Look for the right subpage or the subpage wildcard*/
6947 			if ((lun->mode_pages.index[i].subpage != subpage)
6948 			 && (subpage != SMS_SUBPAGE_ALL))
6949 				continue;
6950 
6951 			/* Make sure the page is supported for this dev type */
6952 			if ((control_dev != 0)
6953 			 && (lun->mode_pages.index[i].page_flags &
6954 			     CTL_PAGE_FLAG_DISK_ONLY))
6955 				continue;
6956 
6957 #if 0
6958 			printf("found page %#x len %d\n",
6959 			       lun->mode_pages.index[i].page_code &
6960 			       SMPH_PC_MASK,
6961 			       lun->mode_pages.index[i].page_len);
6962 #endif
6963 
6964 			page_len += lun->mode_pages.index[i].page_len;
6965 		}
6966 
6967 		if (page_len == 0) {
6968 			ctl_set_invalid_field(ctsio,
6969 					      /*sks_valid*/ 1,
6970 					      /*command*/ 1,
6971 					      /*field*/ 2,
6972 					      /*bit_valid*/ 1,
6973 					      /*bit*/ 5);
6974 			ctl_done((union ctl_io *)ctsio);
6975 			return (CTL_RETVAL_COMPLETE);
6976 		}
6977 		break;
6978 	}
6979 	}
6980 
6981 	total_len = header_len + page_len;
6982 #if 0
6983 	printf("header_len = %d, page_len = %d, total_len = %d\n",
6984 	       header_len, page_len, total_len);
6985 #endif
6986 
6987 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6988 	ctsio->kern_sg_entries = 0;
6989 	ctsio->kern_data_resid = 0;
6990 	ctsio->kern_rel_offset = 0;
6991 	if (total_len < alloc_len) {
6992 		ctsio->residual = alloc_len - total_len;
6993 		ctsio->kern_data_len = total_len;
6994 		ctsio->kern_total_len = total_len;
6995 	} else {
6996 		ctsio->residual = 0;
6997 		ctsio->kern_data_len = alloc_len;
6998 		ctsio->kern_total_len = alloc_len;
6999 	}
7000 
7001 	switch (ctsio->cdb[0]) {
7002 	case MODE_SENSE_6: {
7003 		struct scsi_mode_hdr_6 *header;
7004 
7005 		header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
7006 
7007 		header->datalen = ctl_min(total_len - 1, 254);
7008 
7009 		if (dbd)
7010 			header->block_descr_len = 0;
7011 		else
7012 			header->block_descr_len =
7013 				sizeof(struct scsi_mode_block_descr);
7014 		block_desc = (struct scsi_mode_block_descr *)&header[1];
7015 		break;
7016 	}
7017 	case MODE_SENSE_10: {
7018 		struct scsi_mode_hdr_10 *header;
7019 		int datalen;
7020 
7021 		header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
7022 
7023 		datalen = ctl_min(total_len - 2, 65533);
7024 		scsi_ulto2b(datalen, header->datalen);
7025 		if (dbd)
7026 			scsi_ulto2b(0, header->block_descr_len);
7027 		else
7028 			scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
7029 				    header->block_descr_len);
7030 		block_desc = (struct scsi_mode_block_descr *)&header[1];
7031 		break;
7032 	}
7033 	default:
7034 		panic("invalid CDB type %#x", ctsio->cdb[0]);
7035 		break; /* NOTREACHED */
7036 	}
7037 
7038 	/*
7039 	 * If we've got a disk, use its blocksize in the block
7040 	 * descriptor.  Otherwise, just set it to 0.
7041 	 */
7042 	if (dbd == 0) {
7043 		if (control_dev != 0)
7044 			scsi_ulto3b(lun->be_lun->blocksize,
7045 				    block_desc->block_len);
7046 		else
7047 			scsi_ulto3b(0, block_desc->block_len);
7048 	}
7049 
7050 	switch (page_code) {
7051 	case SMS_ALL_PAGES_PAGE: {
7052 		int i, data_used;
7053 
7054 		data_used = header_len;
7055 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
7056 			struct ctl_page_index *page_index;
7057 
7058 			page_index = &lun->mode_pages.index[i];
7059 
7060 			if ((control_dev != 0)
7061 			 && (page_index->page_flags &
7062 			    CTL_PAGE_FLAG_DISK_ONLY))
7063 				continue;
7064 
7065 			/*
7066 			 * We don't use this subpage if the user didn't
7067 			 * request all subpages.  We already checked (above)
7068 			 * to make sure the user only specified a subpage
7069 			 * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
7070 			 */
7071 			if ((page_index->subpage != 0)
7072 			 && (subpage == SMS_SUBPAGE_PAGE_0))
7073 				continue;
7074 
7075 			/*
7076 			 * Call the handler, if it exists, to update the
7077 			 * page to the latest values.
7078 			 */
7079 			if (page_index->sense_handler != NULL)
7080 				page_index->sense_handler(ctsio, page_index,pc);
7081 
7082 			memcpy(ctsio->kern_data_ptr + data_used,
7083 			       page_index->page_data +
7084 			       (page_index->page_len * pc),
7085 			       page_index->page_len);
7086 			data_used += page_index->page_len;
7087 		}
7088 		break;
7089 	}
7090 	default: {
7091 		int i, data_used;
7092 
7093 		data_used = header_len;
7094 
7095 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
7096 			struct ctl_page_index *page_index;
7097 
7098 			page_index = &lun->mode_pages.index[i];
7099 
7100 			/* Look for the right page code */
7101 			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
7102 				continue;
7103 
7104 			/* Look for the right subpage or the subpage wildcard*/
7105 			if ((page_index->subpage != subpage)
7106 			 && (subpage != SMS_SUBPAGE_ALL))
7107 				continue;
7108 
7109 			/* Make sure the page is supported for this dev type */
7110 			if ((control_dev != 0)
7111 			 && (page_index->page_flags &
7112 			     CTL_PAGE_FLAG_DISK_ONLY))
7113 				continue;
7114 
7115 			/*
7116 			 * Call the handler, if it exists, to update the
7117 			 * page to the latest values.
7118 			 */
7119 			if (page_index->sense_handler != NULL)
7120 				page_index->sense_handler(ctsio, page_index,pc);
7121 
7122 			memcpy(ctsio->kern_data_ptr + data_used,
7123 			       page_index->page_data +
7124 			       (page_index->page_len * pc),
7125 			       page_index->page_len);
7126 			data_used += page_index->page_len;
7127 		}
7128 		break;
7129 	}
7130 	}
7131 
7132 	ctsio->scsi_status = SCSI_STATUS_OK;
7133 
7134 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7135 	ctsio->be_move_done = ctl_config_move_done;
7136 	ctl_datamove((union ctl_io *)ctsio);
7137 
7138 	return (CTL_RETVAL_COMPLETE);
7139 }
7140 
7141 int
7142 ctl_read_capacity(struct ctl_scsiio *ctsio)
7143 {
7144 	struct scsi_read_capacity *cdb;
7145 	struct scsi_read_capacity_data *data;
7146 	struct ctl_lun *lun;
7147 	uint32_t lba;
7148 
7149 	CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
7150 
7151 	cdb = (struct scsi_read_capacity *)ctsio->cdb;
7152 
7153 	lba = scsi_4btoul(cdb->addr);
7154 	if (((cdb->pmi & SRC_PMI) == 0)
7155 	 && (lba != 0)) {
7156 		ctl_set_invalid_field(/*ctsio*/ ctsio,
7157 				      /*sks_valid*/ 1,
7158 				      /*command*/ 1,
7159 				      /*field*/ 2,
7160 				      /*bit_valid*/ 0,
7161 				      /*bit*/ 0);
7162 		ctl_done((union ctl_io *)ctsio);
7163 		return (CTL_RETVAL_COMPLETE);
7164 	}
7165 
7166 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7167 
7168 	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7169 	data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
7170 	ctsio->residual = 0;
7171 	ctsio->kern_data_len = sizeof(*data);
7172 	ctsio->kern_total_len = sizeof(*data);
7173 	ctsio->kern_data_resid = 0;
7174 	ctsio->kern_rel_offset = 0;
7175 	ctsio->kern_sg_entries = 0;
7176 
7177 	/*
7178 	 * If the maximum LBA is greater than 0xfffffffe, the user must
7179 	 * issue a SERVICE ACTION IN (16) command, with the read capacity
7180 	 * serivce action set.
7181 	 */
7182 	if (lun->be_lun->maxlba > 0xfffffffe)
7183 		scsi_ulto4b(0xffffffff, data->addr);
7184 	else
7185 		scsi_ulto4b(lun->be_lun->maxlba, data->addr);
7186 
7187 	/*
7188 	 * XXX KDM this may not be 512 bytes...
7189 	 */
7190 	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7191 
7192 	ctsio->scsi_status = SCSI_STATUS_OK;
7193 
7194 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7195 	ctsio->be_move_done = ctl_config_move_done;
7196 	ctl_datamove((union ctl_io *)ctsio);
7197 
7198 	return (CTL_RETVAL_COMPLETE);
7199 }
7200 
7201 int
7202 ctl_read_capacity_16(struct ctl_scsiio *ctsio)
7203 {
7204 	struct scsi_read_capacity_16 *cdb;
7205 	struct scsi_read_capacity_data_long *data;
7206 	struct ctl_lun *lun;
7207 	uint64_t lba;
7208 	uint32_t alloc_len;
7209 
7210 	CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
7211 
7212 	cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
7213 
7214 	alloc_len = scsi_4btoul(cdb->alloc_len);
7215 	lba = scsi_8btou64(cdb->addr);
7216 
7217 	if ((cdb->reladr & SRC16_PMI)
7218 	 && (lba != 0)) {
7219 		ctl_set_invalid_field(/*ctsio*/ ctsio,
7220 				      /*sks_valid*/ 1,
7221 				      /*command*/ 1,
7222 				      /*field*/ 2,
7223 				      /*bit_valid*/ 0,
7224 				      /*bit*/ 0);
7225 		ctl_done((union ctl_io *)ctsio);
7226 		return (CTL_RETVAL_COMPLETE);
7227 	}
7228 
7229 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7230 
7231 	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7232 	data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
7233 
7234 	if (sizeof(*data) < alloc_len) {
7235 		ctsio->residual = alloc_len - sizeof(*data);
7236 		ctsio->kern_data_len = sizeof(*data);
7237 		ctsio->kern_total_len = sizeof(*data);
7238 	} else {
7239 		ctsio->residual = 0;
7240 		ctsio->kern_data_len = alloc_len;
7241 		ctsio->kern_total_len = alloc_len;
7242 	}
7243 	ctsio->kern_data_resid = 0;
7244 	ctsio->kern_rel_offset = 0;
7245 	ctsio->kern_sg_entries = 0;
7246 
7247 	scsi_u64to8b(lun->be_lun->maxlba, data->addr);
7248 	/* XXX KDM this may not be 512 bytes... */
7249 	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7250 	data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
7251 	scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
7252 	if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
7253 		data->lalba_lbp[0] |= SRC16_LBPME;
7254 
7255 	ctsio->scsi_status = SCSI_STATUS_OK;
7256 
7257 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7258 	ctsio->be_move_done = ctl_config_move_done;
7259 	ctl_datamove((union ctl_io *)ctsio);
7260 
7261 	return (CTL_RETVAL_COMPLETE);
7262 }
7263 
7264 int
7265 ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7266 {
7267 	struct scsi_maintenance_in *cdb;
7268 	int retval;
7269 	int alloc_len, ext, total_len = 0, g, p, pc, pg;
7270 	int num_target_port_groups, num_target_ports, single;
7271 	struct ctl_lun *lun;
7272 	struct ctl_softc *softc;
7273 	struct ctl_port *port;
7274 	struct scsi_target_group_data *rtg_ptr;
7275 	struct scsi_target_group_data_extended *rtg_ext_ptr;
7276 	struct scsi_target_port_group_descriptor *tpg_desc;
7277 
7278 	CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7279 
7280 	cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7281 	softc = control_softc;
7282 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7283 
7284 	retval = CTL_RETVAL_COMPLETE;
7285 
7286 	switch (cdb->byte2 & STG_PDF_MASK) {
7287 	case STG_PDF_LENGTH:
7288 		ext = 0;
7289 		break;
7290 	case STG_PDF_EXTENDED:
7291 		ext = 1;
7292 		break;
7293 	default:
7294 		ctl_set_invalid_field(/*ctsio*/ ctsio,
7295 				      /*sks_valid*/ 1,
7296 				      /*command*/ 1,
7297 				      /*field*/ 2,
7298 				      /*bit_valid*/ 1,
7299 				      /*bit*/ 5);
7300 		ctl_done((union ctl_io *)ctsio);
7301 		return(retval);
7302 	}
7303 
7304 	single = ctl_is_single;
7305 	if (single)
7306 		num_target_port_groups = 1;
7307 	else
7308 		num_target_port_groups = NUM_TARGET_PORT_GROUPS;
7309 	num_target_ports = 0;
7310 	mtx_lock(&softc->ctl_lock);
7311 	STAILQ_FOREACH(port, &softc->port_list, links) {
7312 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7313 			continue;
7314 		if (ctl_map_lun_back(port->targ_port, lun->lun) >= CTL_MAX_LUNS)
7315 			continue;
7316 		num_target_ports++;
7317 	}
7318 	mtx_unlock(&softc->ctl_lock);
7319 
7320 	if (ext)
7321 		total_len = sizeof(struct scsi_target_group_data_extended);
7322 	else
7323 		total_len = sizeof(struct scsi_target_group_data);
7324 	total_len += sizeof(struct scsi_target_port_group_descriptor) *
7325 		num_target_port_groups +
7326 	    sizeof(struct scsi_target_port_descriptor) *
7327 		num_target_ports * num_target_port_groups;
7328 
7329 	alloc_len = scsi_4btoul(cdb->length);
7330 
7331 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7332 
7333 	ctsio->kern_sg_entries = 0;
7334 
7335 	if (total_len < alloc_len) {
7336 		ctsio->residual = alloc_len - total_len;
7337 		ctsio->kern_data_len = total_len;
7338 		ctsio->kern_total_len = total_len;
7339 	} else {
7340 		ctsio->residual = 0;
7341 		ctsio->kern_data_len = alloc_len;
7342 		ctsio->kern_total_len = alloc_len;
7343 	}
7344 	ctsio->kern_data_resid = 0;
7345 	ctsio->kern_rel_offset = 0;
7346 
7347 	if (ext) {
7348 		rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7349 		    ctsio->kern_data_ptr;
7350 		scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7351 		rtg_ext_ptr->format_type = 0x10;
7352 		rtg_ext_ptr->implicit_transition_time = 0;
7353 		tpg_desc = &rtg_ext_ptr->groups[0];
7354 	} else {
7355 		rtg_ptr = (struct scsi_target_group_data *)
7356 		    ctsio->kern_data_ptr;
7357 		scsi_ulto4b(total_len - 4, rtg_ptr->length);
7358 		tpg_desc = &rtg_ptr->groups[0];
7359 	}
7360 
7361 	pg = ctsio->io_hdr.nexus.targ_port / CTL_MAX_PORTS;
7362 	mtx_lock(&softc->ctl_lock);
7363 	for (g = 0; g < num_target_port_groups; g++) {
7364 		if (g == pg)
7365 			tpg_desc->pref_state = TPG_PRIMARY |
7366 			    TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7367 		else
7368 			tpg_desc->pref_state =
7369 			    TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7370 		tpg_desc->support = TPG_AO_SUP;
7371 		if (!single)
7372 			tpg_desc->support |= TPG_AN_SUP;
7373 		scsi_ulto2b(g + 1, tpg_desc->target_port_group);
7374 		tpg_desc->status = TPG_IMPLICIT;
7375 		pc = 0;
7376 		STAILQ_FOREACH(port, &softc->port_list, links) {
7377 			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7378 				continue;
7379 			if (ctl_map_lun_back(port->targ_port, lun->lun) >=
7380 			    CTL_MAX_LUNS)
7381 				continue;
7382 			p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
7383 			scsi_ulto2b(p, tpg_desc->descriptors[pc].
7384 			    relative_target_port_identifier);
7385 			pc++;
7386 		}
7387 		tpg_desc->target_port_count = pc;
7388 		tpg_desc = (struct scsi_target_port_group_descriptor *)
7389 		    &tpg_desc->descriptors[pc];
7390 	}
7391 	mtx_unlock(&softc->ctl_lock);
7392 
7393 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7394 	ctsio->be_move_done = ctl_config_move_done;
7395 
7396 	CTL_DEBUG_PRINT(("buf = %x %x %x %x %x %x %x %x\n",
7397 			 ctsio->kern_data_ptr[0], ctsio->kern_data_ptr[1],
7398 			 ctsio->kern_data_ptr[2], ctsio->kern_data_ptr[3],
7399 			 ctsio->kern_data_ptr[4], ctsio->kern_data_ptr[5],
7400 			 ctsio->kern_data_ptr[6], ctsio->kern_data_ptr[7]));
7401 
7402 	ctl_datamove((union ctl_io *)ctsio);
7403 	return(retval);
7404 }
7405 
7406 int
7407 ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7408 {
7409 	struct ctl_lun *lun;
7410 	struct scsi_report_supported_opcodes *cdb;
7411 	const struct ctl_cmd_entry *entry, *sentry;
7412 	struct scsi_report_supported_opcodes_all *all;
7413 	struct scsi_report_supported_opcodes_descr *descr;
7414 	struct scsi_report_supported_opcodes_one *one;
7415 	int retval;
7416 	int alloc_len, total_len;
7417 	int opcode, service_action, i, j, num;
7418 
7419 	CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7420 
7421 	cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7422 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7423 
7424 	retval = CTL_RETVAL_COMPLETE;
7425 
7426 	opcode = cdb->requested_opcode;
7427 	service_action = scsi_2btoul(cdb->requested_service_action);
7428 	switch (cdb->options & RSO_OPTIONS_MASK) {
7429 	case RSO_OPTIONS_ALL:
7430 		num = 0;
7431 		for (i = 0; i < 256; i++) {
7432 			entry = &ctl_cmd_table[i];
7433 			if (entry->flags & CTL_CMD_FLAG_SA5) {
7434 				for (j = 0; j < 32; j++) {
7435 					sentry = &((const struct ctl_cmd_entry *)
7436 					    entry->execute)[j];
7437 					if (ctl_cmd_applicable(
7438 					    lun->be_lun->lun_type, sentry))
7439 						num++;
7440 				}
7441 			} else {
7442 				if (ctl_cmd_applicable(lun->be_lun->lun_type,
7443 				    entry))
7444 					num++;
7445 			}
7446 		}
7447 		total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7448 		    num * sizeof(struct scsi_report_supported_opcodes_descr);
7449 		break;
7450 	case RSO_OPTIONS_OC:
7451 		if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7452 			ctl_set_invalid_field(/*ctsio*/ ctsio,
7453 					      /*sks_valid*/ 1,
7454 					      /*command*/ 1,
7455 					      /*field*/ 2,
7456 					      /*bit_valid*/ 1,
7457 					      /*bit*/ 2);
7458 			ctl_done((union ctl_io *)ctsio);
7459 			return (CTL_RETVAL_COMPLETE);
7460 		}
7461 		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7462 		break;
7463 	case RSO_OPTIONS_OC_SA:
7464 		if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7465 		    service_action >= 32) {
7466 			ctl_set_invalid_field(/*ctsio*/ ctsio,
7467 					      /*sks_valid*/ 1,
7468 					      /*command*/ 1,
7469 					      /*field*/ 2,
7470 					      /*bit_valid*/ 1,
7471 					      /*bit*/ 2);
7472 			ctl_done((union ctl_io *)ctsio);
7473 			return (CTL_RETVAL_COMPLETE);
7474 		}
7475 		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7476 		break;
7477 	default:
7478 		ctl_set_invalid_field(/*ctsio*/ ctsio,
7479 				      /*sks_valid*/ 1,
7480 				      /*command*/ 1,
7481 				      /*field*/ 2,
7482 				      /*bit_valid*/ 1,
7483 				      /*bit*/ 2);
7484 		ctl_done((union ctl_io *)ctsio);
7485 		return (CTL_RETVAL_COMPLETE);
7486 	}
7487 
7488 	alloc_len = scsi_4btoul(cdb->length);
7489 
7490 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7491 
7492 	ctsio->kern_sg_entries = 0;
7493 
7494 	if (total_len < alloc_len) {
7495 		ctsio->residual = alloc_len - total_len;
7496 		ctsio->kern_data_len = total_len;
7497 		ctsio->kern_total_len = total_len;
7498 	} else {
7499 		ctsio->residual = 0;
7500 		ctsio->kern_data_len = alloc_len;
7501 		ctsio->kern_total_len = alloc_len;
7502 	}
7503 	ctsio->kern_data_resid = 0;
7504 	ctsio->kern_rel_offset = 0;
7505 
7506 	switch (cdb->options & RSO_OPTIONS_MASK) {
7507 	case RSO_OPTIONS_ALL:
7508 		all = (struct scsi_report_supported_opcodes_all *)
7509 		    ctsio->kern_data_ptr;
7510 		num = 0;
7511 		for (i = 0; i < 256; i++) {
7512 			entry = &ctl_cmd_table[i];
7513 			if (entry->flags & CTL_CMD_FLAG_SA5) {
7514 				for (j = 0; j < 32; j++) {
7515 					sentry = &((const struct ctl_cmd_entry *)
7516 					    entry->execute)[j];
7517 					if (!ctl_cmd_applicable(
7518 					    lun->be_lun->lun_type, sentry))
7519 						continue;
7520 					descr = &all->descr[num++];
7521 					descr->opcode = i;
7522 					scsi_ulto2b(j, descr->service_action);
7523 					descr->flags = RSO_SERVACTV;
7524 					scsi_ulto2b(sentry->length,
7525 					    descr->cdb_length);
7526 				}
7527 			} else {
7528 				if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7529 				    entry))
7530 					continue;
7531 				descr = &all->descr[num++];
7532 				descr->opcode = i;
7533 				scsi_ulto2b(0, descr->service_action);
7534 				descr->flags = 0;
7535 				scsi_ulto2b(entry->length, descr->cdb_length);
7536 			}
7537 		}
7538 		scsi_ulto4b(
7539 		    num * sizeof(struct scsi_report_supported_opcodes_descr),
7540 		    all->length);
7541 		break;
7542 	case RSO_OPTIONS_OC:
7543 		one = (struct scsi_report_supported_opcodes_one *)
7544 		    ctsio->kern_data_ptr;
7545 		entry = &ctl_cmd_table[opcode];
7546 		goto fill_one;
7547 	case RSO_OPTIONS_OC_SA:
7548 		one = (struct scsi_report_supported_opcodes_one *)
7549 		    ctsio->kern_data_ptr;
7550 		entry = &ctl_cmd_table[opcode];
7551 		entry = &((const struct ctl_cmd_entry *)
7552 		    entry->execute)[service_action];
7553 fill_one:
7554 		if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7555 			one->support = 3;
7556 			scsi_ulto2b(entry->length, one->cdb_length);
7557 			one->cdb_usage[0] = opcode;
7558 			memcpy(&one->cdb_usage[1], entry->usage,
7559 			    entry->length - 1);
7560 		} else
7561 			one->support = 1;
7562 		break;
7563 	}
7564 
7565 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7566 	ctsio->be_move_done = ctl_config_move_done;
7567 
7568 	ctl_datamove((union ctl_io *)ctsio);
7569 	return(retval);
7570 }
7571 
7572 int
7573 ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7574 {
7575 	struct ctl_lun *lun;
7576 	struct scsi_report_supported_tmf *cdb;
7577 	struct scsi_report_supported_tmf_data *data;
7578 	int retval;
7579 	int alloc_len, total_len;
7580 
7581 	CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7582 
7583 	cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7584 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7585 
7586 	retval = CTL_RETVAL_COMPLETE;
7587 
7588 	total_len = sizeof(struct scsi_report_supported_tmf_data);
7589 	alloc_len = scsi_4btoul(cdb->length);
7590 
7591 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7592 
7593 	ctsio->kern_sg_entries = 0;
7594 
7595 	if (total_len < alloc_len) {
7596 		ctsio->residual = alloc_len - total_len;
7597 		ctsio->kern_data_len = total_len;
7598 		ctsio->kern_total_len = total_len;
7599 	} else {
7600 		ctsio->residual = 0;
7601 		ctsio->kern_data_len = alloc_len;
7602 		ctsio->kern_total_len = alloc_len;
7603 	}
7604 	ctsio->kern_data_resid = 0;
7605 	ctsio->kern_rel_offset = 0;
7606 
7607 	data = (struct scsi_report_supported_tmf_data *)ctsio->kern_data_ptr;
7608 	data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_TRS;
7609 	data->byte2 |= RST_ITNRS;
7610 
7611 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7612 	ctsio->be_move_done = ctl_config_move_done;
7613 
7614 	ctl_datamove((union ctl_io *)ctsio);
7615 	return (retval);
7616 }
7617 
7618 int
7619 ctl_report_timestamp(struct ctl_scsiio *ctsio)
7620 {
7621 	struct ctl_lun *lun;
7622 	struct scsi_report_timestamp *cdb;
7623 	struct scsi_report_timestamp_data *data;
7624 	struct timeval tv;
7625 	int64_t timestamp;
7626 	int retval;
7627 	int alloc_len, total_len;
7628 
7629 	CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7630 
7631 	cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7632 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7633 
7634 	retval = CTL_RETVAL_COMPLETE;
7635 
7636 	total_len = sizeof(struct scsi_report_timestamp_data);
7637 	alloc_len = scsi_4btoul(cdb->length);
7638 
7639 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7640 
7641 	ctsio->kern_sg_entries = 0;
7642 
7643 	if (total_len < alloc_len) {
7644 		ctsio->residual = alloc_len - total_len;
7645 		ctsio->kern_data_len = total_len;
7646 		ctsio->kern_total_len = total_len;
7647 	} else {
7648 		ctsio->residual = 0;
7649 		ctsio->kern_data_len = alloc_len;
7650 		ctsio->kern_total_len = alloc_len;
7651 	}
7652 	ctsio->kern_data_resid = 0;
7653 	ctsio->kern_rel_offset = 0;
7654 
7655 	data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7656 	scsi_ulto2b(sizeof(*data) - 2, data->length);
7657 	data->origin = RTS_ORIG_OUTSIDE;
7658 	getmicrotime(&tv);
7659 	timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7660 	scsi_ulto4b(timestamp >> 16, data->timestamp);
7661 	scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7662 
7663 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7664 	ctsio->be_move_done = ctl_config_move_done;
7665 
7666 	ctl_datamove((union ctl_io *)ctsio);
7667 	return (retval);
7668 }
7669 
7670 int
7671 ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7672 {
7673 	struct scsi_per_res_in *cdb;
7674 	int alloc_len, total_len = 0;
7675 	/* struct scsi_per_res_in_rsrv in_data; */
7676 	struct ctl_lun *lun;
7677 	struct ctl_softc *softc;
7678 
7679 	CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7680 
7681 	softc = control_softc;
7682 
7683 	cdb = (struct scsi_per_res_in *)ctsio->cdb;
7684 
7685 	alloc_len = scsi_2btoul(cdb->length);
7686 
7687 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7688 
7689 retry:
7690 	mtx_lock(&lun->lun_lock);
7691 	switch (cdb->action) {
7692 	case SPRI_RK: /* read keys */
7693 		total_len = sizeof(struct scsi_per_res_in_keys) +
7694 			lun->pr_key_count *
7695 			sizeof(struct scsi_per_res_key);
7696 		break;
7697 	case SPRI_RR: /* read reservation */
7698 		if (lun->flags & CTL_LUN_PR_RESERVED)
7699 			total_len = sizeof(struct scsi_per_res_in_rsrv);
7700 		else
7701 			total_len = sizeof(struct scsi_per_res_in_header);
7702 		break;
7703 	case SPRI_RC: /* report capabilities */
7704 		total_len = sizeof(struct scsi_per_res_cap);
7705 		break;
7706 	case SPRI_RS: /* read full status */
7707 		total_len = sizeof(struct scsi_per_res_in_header) +
7708 		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7709 		    lun->pr_key_count;
7710 		break;
7711 	default:
7712 		panic("Invalid PR type %x", cdb->action);
7713 	}
7714 	mtx_unlock(&lun->lun_lock);
7715 
7716 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7717 
7718 	if (total_len < alloc_len) {
7719 		ctsio->residual = alloc_len - total_len;
7720 		ctsio->kern_data_len = total_len;
7721 		ctsio->kern_total_len = total_len;
7722 	} else {
7723 		ctsio->residual = 0;
7724 		ctsio->kern_data_len = alloc_len;
7725 		ctsio->kern_total_len = alloc_len;
7726 	}
7727 
7728 	ctsio->kern_data_resid = 0;
7729 	ctsio->kern_rel_offset = 0;
7730 	ctsio->kern_sg_entries = 0;
7731 
7732 	mtx_lock(&lun->lun_lock);
7733 	switch (cdb->action) {
7734 	case SPRI_RK: { // read keys
7735         struct scsi_per_res_in_keys *res_keys;
7736 		int i, key_count;
7737 
7738 		res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7739 
7740 		/*
7741 		 * We had to drop the lock to allocate our buffer, which
7742 		 * leaves time for someone to come in with another
7743 		 * persistent reservation.  (That is unlikely, though,
7744 		 * since this should be the only persistent reservation
7745 		 * command active right now.)
7746 		 */
7747 		if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7748 		    (lun->pr_key_count *
7749 		     sizeof(struct scsi_per_res_key)))){
7750 			mtx_unlock(&lun->lun_lock);
7751 			free(ctsio->kern_data_ptr, M_CTL);
7752 			printf("%s: reservation length changed, retrying\n",
7753 			       __func__);
7754 			goto retry;
7755 		}
7756 
7757 		scsi_ulto4b(lun->PRGeneration, res_keys->header.generation);
7758 
7759 		scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7760 			     lun->pr_key_count, res_keys->header.length);
7761 
7762 		for (i = 0, key_count = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7763 			if (!lun->per_res[i].registered)
7764 				continue;
7765 
7766 			/*
7767 			 * We used lun->pr_key_count to calculate the
7768 			 * size to allocate.  If it turns out the number of
7769 			 * initiators with the registered flag set is
7770 			 * larger than that (i.e. they haven't been kept in
7771 			 * sync), we've got a problem.
7772 			 */
7773 			if (key_count >= lun->pr_key_count) {
7774 #ifdef NEEDTOPORT
7775 				csevent_log(CSC_CTL | CSC_SHELF_SW |
7776 					    CTL_PR_ERROR,
7777 					    csevent_LogType_Fault,
7778 					    csevent_AlertLevel_Yellow,
7779 					    csevent_FRU_ShelfController,
7780 					    csevent_FRU_Firmware,
7781 				        csevent_FRU_Unknown,
7782 					    "registered keys %d >= key "
7783 					    "count %d", key_count,
7784 					    lun->pr_key_count);
7785 #endif
7786 				key_count++;
7787 				continue;
7788 			}
7789 			memcpy(res_keys->keys[key_count].key,
7790 			       lun->per_res[i].res_key.key,
7791 			       ctl_min(sizeof(res_keys->keys[key_count].key),
7792 			       sizeof(lun->per_res[i].res_key)));
7793 			key_count++;
7794 		}
7795 		break;
7796 	}
7797 	case SPRI_RR: { // read reservation
7798 		struct scsi_per_res_in_rsrv *res;
7799 		int tmp_len, header_only;
7800 
7801 		res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7802 
7803 		scsi_ulto4b(lun->PRGeneration, res->header.generation);
7804 
7805 		if (lun->flags & CTL_LUN_PR_RESERVED)
7806 		{
7807 			tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7808 			scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7809 				    res->header.length);
7810 			header_only = 0;
7811 		} else {
7812 			tmp_len = sizeof(struct scsi_per_res_in_header);
7813 			scsi_ulto4b(0, res->header.length);
7814 			header_only = 1;
7815 		}
7816 
7817 		/*
7818 		 * We had to drop the lock to allocate our buffer, which
7819 		 * leaves time for someone to come in with another
7820 		 * persistent reservation.  (That is unlikely, though,
7821 		 * since this should be the only persistent reservation
7822 		 * command active right now.)
7823 		 */
7824 		if (tmp_len != total_len) {
7825 			mtx_unlock(&lun->lun_lock);
7826 			free(ctsio->kern_data_ptr, M_CTL);
7827 			printf("%s: reservation status changed, retrying\n",
7828 			       __func__);
7829 			goto retry;
7830 		}
7831 
7832 		/*
7833 		 * No reservation held, so we're done.
7834 		 */
7835 		if (header_only != 0)
7836 			break;
7837 
7838 		/*
7839 		 * If the registration is an All Registrants type, the key
7840 		 * is 0, since it doesn't really matter.
7841 		 */
7842 		if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7843 			memcpy(res->data.reservation,
7844 			       &lun->per_res[lun->pr_res_idx].res_key,
7845 			       sizeof(struct scsi_per_res_key));
7846 		}
7847 		res->data.scopetype = lun->res_type;
7848 		break;
7849 	}
7850 	case SPRI_RC:     //report capabilities
7851 	{
7852 		struct scsi_per_res_cap *res_cap;
7853 		uint16_t type_mask;
7854 
7855 		res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7856 		scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7857 		res_cap->flags2 |= SPRI_TMV | SPRI_ALLOW_3;
7858 		type_mask = SPRI_TM_WR_EX_AR |
7859 			    SPRI_TM_EX_AC_RO |
7860 			    SPRI_TM_WR_EX_RO |
7861 			    SPRI_TM_EX_AC |
7862 			    SPRI_TM_WR_EX |
7863 			    SPRI_TM_EX_AC_AR;
7864 		scsi_ulto2b(type_mask, res_cap->type_mask);
7865 		break;
7866 	}
7867 	case SPRI_RS: { // read full status
7868 		struct scsi_per_res_in_full *res_status;
7869 		struct scsi_per_res_in_full_desc *res_desc;
7870 		struct ctl_port *port;
7871 		int i, len;
7872 
7873 		res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7874 
7875 		/*
7876 		 * We had to drop the lock to allocate our buffer, which
7877 		 * leaves time for someone to come in with another
7878 		 * persistent reservation.  (That is unlikely, though,
7879 		 * since this should be the only persistent reservation
7880 		 * command active right now.)
7881 		 */
7882 		if (total_len < (sizeof(struct scsi_per_res_in_header) +
7883 		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7884 		     lun->pr_key_count)){
7885 			mtx_unlock(&lun->lun_lock);
7886 			free(ctsio->kern_data_ptr, M_CTL);
7887 			printf("%s: reservation length changed, retrying\n",
7888 			       __func__);
7889 			goto retry;
7890 		}
7891 
7892 		scsi_ulto4b(lun->PRGeneration, res_status->header.generation);
7893 
7894 		res_desc = &res_status->desc[0];
7895 		for (i = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7896 			if (!lun->per_res[i].registered)
7897 				continue;
7898 
7899 			memcpy(&res_desc->res_key, &lun->per_res[i].res_key.key,
7900 			    sizeof(res_desc->res_key));
7901 			if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7902 			    (lun->pr_res_idx == i ||
7903 			     lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7904 				res_desc->flags = SPRI_FULL_R_HOLDER;
7905 				res_desc->scopetype = lun->res_type;
7906 			}
7907 			scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7908 			    res_desc->rel_trgt_port_id);
7909 			len = 0;
7910 			port = softc->ctl_ports[i / CTL_MAX_INIT_PER_PORT];
7911 			if (port != NULL)
7912 				len = ctl_create_iid(port,
7913 				    i % CTL_MAX_INIT_PER_PORT,
7914 				    res_desc->transport_id);
7915 			scsi_ulto4b(len, res_desc->additional_length);
7916 			res_desc = (struct scsi_per_res_in_full_desc *)
7917 			    &res_desc->transport_id[len];
7918 		}
7919 		scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7920 		    res_status->header.length);
7921 		break;
7922 	}
7923 	default:
7924 		/*
7925 		 * This is a bug, because we just checked for this above,
7926 		 * and should have returned an error.
7927 		 */
7928 		panic("Invalid PR type %x", cdb->action);
7929 		break; /* NOTREACHED */
7930 	}
7931 	mtx_unlock(&lun->lun_lock);
7932 
7933 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7934 	ctsio->be_move_done = ctl_config_move_done;
7935 
7936 	CTL_DEBUG_PRINT(("buf = %x %x %x %x %x %x %x %x\n",
7937 			 ctsio->kern_data_ptr[0], ctsio->kern_data_ptr[1],
7938 			 ctsio->kern_data_ptr[2], ctsio->kern_data_ptr[3],
7939 			 ctsio->kern_data_ptr[4], ctsio->kern_data_ptr[5],
7940 			 ctsio->kern_data_ptr[6], ctsio->kern_data_ptr[7]));
7941 
7942 	ctl_datamove((union ctl_io *)ctsio);
7943 
7944 	return (CTL_RETVAL_COMPLETE);
7945 }
7946 
7947 /*
7948  * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
7949  * it should return.
7950  */
7951 static int
7952 ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
7953 		uint64_t sa_res_key, uint8_t type, uint32_t residx,
7954 		struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
7955 		struct scsi_per_res_out_parms* param)
7956 {
7957 	union ctl_ha_msg persis_io;
7958 	int retval, i;
7959 	int isc_retval;
7960 
7961 	retval = 0;
7962 
7963 	mtx_lock(&lun->lun_lock);
7964 	if (sa_res_key == 0) {
7965 		if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
7966 			/* validate scope and type */
7967 			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7968 			     SPR_LU_SCOPE) {
7969 				mtx_unlock(&lun->lun_lock);
7970 				ctl_set_invalid_field(/*ctsio*/ ctsio,
7971 						      /*sks_valid*/ 1,
7972 						      /*command*/ 1,
7973 						      /*field*/ 2,
7974 						      /*bit_valid*/ 1,
7975 						      /*bit*/ 4);
7976 				ctl_done((union ctl_io *)ctsio);
7977 				return (1);
7978 			}
7979 
7980 		        if (type>8 || type==2 || type==4 || type==0) {
7981 				mtx_unlock(&lun->lun_lock);
7982 				ctl_set_invalid_field(/*ctsio*/ ctsio,
7983        	           				      /*sks_valid*/ 1,
7984 						      /*command*/ 1,
7985 						      /*field*/ 2,
7986 						      /*bit_valid*/ 1,
7987 						      /*bit*/ 0);
7988 				ctl_done((union ctl_io *)ctsio);
7989 				return (1);
7990 		        }
7991 
7992 			/* temporarily unregister this nexus */
7993 			lun->per_res[residx].registered = 0;
7994 
7995 			/*
7996 			 * Unregister everybody else and build UA for
7997 			 * them
7998 			 */
7999 			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8000 				if (lun->per_res[i].registered == 0)
8001 					continue;
8002 
8003 				if (!persis_offset
8004 				 && i <CTL_MAX_INITIATORS)
8005 					lun->pending_ua[i] |=
8006 						CTL_UA_REG_PREEMPT;
8007 				else if (persis_offset
8008 				      && i >= persis_offset)
8009 					lun->pending_ua[i-persis_offset] |=
8010 						CTL_UA_REG_PREEMPT;
8011 				lun->per_res[i].registered = 0;
8012 				memset(&lun->per_res[i].res_key, 0,
8013 				       sizeof(struct scsi_per_res_key));
8014 			}
8015 			lun->per_res[residx].registered = 1;
8016 			lun->pr_key_count = 1;
8017 			lun->res_type = type;
8018 			if (lun->res_type != SPR_TYPE_WR_EX_AR
8019 			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8020 				lun->pr_res_idx = residx;
8021 
8022 			/* send msg to other side */
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_PREEMPT;
8026 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8027 			persis_io.pr.pr_info.res_type = type;
8028 			memcpy(persis_io.pr.pr_info.sa_res_key,
8029 			       param->serv_act_res_key,
8030 			       sizeof(param->serv_act_res_key));
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 "
8035 				       "from ctl_ha_msg_send %d\n",
8036 				       isc_retval);
8037 			}
8038 		} else {
8039 			/* not all registrants */
8040 			mtx_unlock(&lun->lun_lock);
8041 			free(ctsio->kern_data_ptr, M_CTL);
8042 			ctl_set_invalid_field(ctsio,
8043 					      /*sks_valid*/ 1,
8044 					      /*command*/ 0,
8045 					      /*field*/ 8,
8046 					      /*bit_valid*/ 0,
8047 					      /*bit*/ 0);
8048 			ctl_done((union ctl_io *)ctsio);
8049 			return (1);
8050 		}
8051 	} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8052 		|| !(lun->flags & CTL_LUN_PR_RESERVED)) {
8053 		int found = 0;
8054 
8055 		if (res_key == sa_res_key) {
8056 			/* special case */
8057 			/*
8058 			 * The spec implies this is not good but doesn't
8059 			 * say what to do. There are two choices either
8060 			 * generate a res conflict or check condition
8061 			 * with illegal field in parameter data. Since
8062 			 * that is what is done when the sa_res_key is
8063 			 * zero I'll take that approach since this has
8064 			 * to do with the sa_res_key.
8065 			 */
8066 			mtx_unlock(&lun->lun_lock);
8067 			free(ctsio->kern_data_ptr, M_CTL);
8068 			ctl_set_invalid_field(ctsio,
8069 					      /*sks_valid*/ 1,
8070 					      /*command*/ 0,
8071 					      /*field*/ 8,
8072 					      /*bit_valid*/ 0,
8073 					      /*bit*/ 0);
8074 			ctl_done((union ctl_io *)ctsio);
8075 			return (1);
8076 		}
8077 
8078 		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8079 			if (lun->per_res[i].registered
8080 			 && memcmp(param->serv_act_res_key,
8081 			    lun->per_res[i].res_key.key,
8082 			    sizeof(struct scsi_per_res_key)) != 0)
8083 				continue;
8084 
8085 			found = 1;
8086 			lun->per_res[i].registered = 0;
8087 			memset(&lun->per_res[i].res_key, 0,
8088 			       sizeof(struct scsi_per_res_key));
8089 			lun->pr_key_count--;
8090 
8091 			if (!persis_offset && i < CTL_MAX_INITIATORS)
8092 				lun->pending_ua[i] |= CTL_UA_REG_PREEMPT;
8093 			else if (persis_offset && i >= persis_offset)
8094 				lun->pending_ua[i-persis_offset] |=
8095 					CTL_UA_REG_PREEMPT;
8096 		}
8097 		if (!found) {
8098 			mtx_unlock(&lun->lun_lock);
8099 			free(ctsio->kern_data_ptr, M_CTL);
8100 			ctl_set_reservation_conflict(ctsio);
8101 			ctl_done((union ctl_io *)ctsio);
8102 			return (CTL_RETVAL_COMPLETE);
8103 		}
8104 		/* send msg to other side */
8105 		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8106 		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8107 		persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8108 		persis_io.pr.pr_info.residx = lun->pr_res_idx;
8109 		persis_io.pr.pr_info.res_type = type;
8110 		memcpy(persis_io.pr.pr_info.sa_res_key,
8111 		       param->serv_act_res_key,
8112 		       sizeof(param->serv_act_res_key));
8113 		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8114 		     &persis_io, sizeof(persis_io), 0)) >
8115 		     CTL_HA_STATUS_SUCCESS) {
8116 			printf("CTL:Persis Out error returned from "
8117 			       "ctl_ha_msg_send %d\n", isc_retval);
8118 		}
8119 	} else {
8120 		/* Reserved but not all registrants */
8121 		/* sa_res_key is res holder */
8122 		if (memcmp(param->serv_act_res_key,
8123                    lun->per_res[lun->pr_res_idx].res_key.key,
8124                    sizeof(struct scsi_per_res_key)) == 0) {
8125 			/* validate scope and type */
8126 			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8127 			     SPR_LU_SCOPE) {
8128 				mtx_unlock(&lun->lun_lock);
8129 				ctl_set_invalid_field(/*ctsio*/ ctsio,
8130 						      /*sks_valid*/ 1,
8131 						      /*command*/ 1,
8132 						      /*field*/ 2,
8133 						      /*bit_valid*/ 1,
8134 						      /*bit*/ 4);
8135 				ctl_done((union ctl_io *)ctsio);
8136 				return (1);
8137 			}
8138 
8139 			if (type>8 || type==2 || type==4 || type==0) {
8140 				mtx_unlock(&lun->lun_lock);
8141 				ctl_set_invalid_field(/*ctsio*/ ctsio,
8142 						      /*sks_valid*/ 1,
8143 						      /*command*/ 1,
8144 						      /*field*/ 2,
8145 						      /*bit_valid*/ 1,
8146 						      /*bit*/ 0);
8147 				ctl_done((union ctl_io *)ctsio);
8148 				return (1);
8149 			}
8150 
8151 			/*
8152 			 * Do the following:
8153 			 * if sa_res_key != res_key remove all
8154 			 * registrants w/sa_res_key and generate UA
8155 			 * for these registrants(Registrations
8156 			 * Preempted) if it wasn't an exclusive
8157 			 * reservation generate UA(Reservations
8158 			 * Preempted) for all other registered nexuses
8159 			 * if the type has changed. Establish the new
8160 			 * reservation and holder. If res_key and
8161 			 * sa_res_key are the same do the above
8162 			 * except don't unregister the res holder.
8163 			 */
8164 
8165 			/*
8166 			 * Temporarily unregister so it won't get
8167 			 * removed or UA generated
8168 			 */
8169 			lun->per_res[residx].registered = 0;
8170 			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8171 				if (lun->per_res[i].registered == 0)
8172 					continue;
8173 
8174 				if (memcmp(param->serv_act_res_key,
8175 				    lun->per_res[i].res_key.key,
8176 				    sizeof(struct scsi_per_res_key)) == 0) {
8177 					lun->per_res[i].registered = 0;
8178 					memset(&lun->per_res[i].res_key,
8179 					       0,
8180 					       sizeof(struct scsi_per_res_key));
8181 					lun->pr_key_count--;
8182 
8183 					if (!persis_offset
8184 					 && i < CTL_MAX_INITIATORS)
8185 						lun->pending_ua[i] |=
8186 							CTL_UA_REG_PREEMPT;
8187 					else if (persis_offset
8188 					      && i >= persis_offset)
8189 						lun->pending_ua[i-persis_offset] |=
8190 						  CTL_UA_REG_PREEMPT;
8191 				} else if (type != lun->res_type
8192 					&& (lun->res_type == SPR_TYPE_WR_EX_RO
8193 					 || lun->res_type ==SPR_TYPE_EX_AC_RO)){
8194 						if (!persis_offset
8195 						 && i < CTL_MAX_INITIATORS)
8196 							lun->pending_ua[i] |=
8197 							CTL_UA_RES_RELEASE;
8198 						else if (persis_offset
8199 						      && i >= persis_offset)
8200 							lun->pending_ua[
8201 							i-persis_offset] |=
8202 							CTL_UA_RES_RELEASE;
8203 				}
8204 			}
8205 			lun->per_res[residx].registered = 1;
8206 			lun->res_type = type;
8207 			if (lun->res_type != SPR_TYPE_WR_EX_AR
8208 			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8209 				lun->pr_res_idx = residx;
8210 			else
8211 				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8212 
8213 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8214 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8215 			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8216 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8217 			persis_io.pr.pr_info.res_type = type;
8218 			memcpy(persis_io.pr.pr_info.sa_res_key,
8219 			       param->serv_act_res_key,
8220 			       sizeof(param->serv_act_res_key));
8221 			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8222 			     &persis_io, sizeof(persis_io), 0)) >
8223 			     CTL_HA_STATUS_SUCCESS) {
8224 				printf("CTL:Persis Out error returned "
8225 				       "from ctl_ha_msg_send %d\n",
8226 				       isc_retval);
8227 			}
8228 		} else {
8229 			/*
8230 			 * sa_res_key is not the res holder just
8231 			 * remove registrants
8232 			 */
8233 			int found=0;
8234 
8235 			for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8236 				if (memcmp(param->serv_act_res_key,
8237 				    lun->per_res[i].res_key.key,
8238 				    sizeof(struct scsi_per_res_key)) != 0)
8239 					continue;
8240 
8241 				found = 1;
8242 				lun->per_res[i].registered = 0;
8243 				memset(&lun->per_res[i].res_key, 0,
8244 				       sizeof(struct scsi_per_res_key));
8245 				lun->pr_key_count--;
8246 
8247 				if (!persis_offset
8248 				 && i < CTL_MAX_INITIATORS)
8249 					lun->pending_ua[i] |=
8250 						CTL_UA_REG_PREEMPT;
8251 				else if (persis_offset
8252 				      && i >= persis_offset)
8253 					lun->pending_ua[i-persis_offset] |=
8254 						CTL_UA_REG_PREEMPT;
8255 			}
8256 
8257 			if (!found) {
8258 				mtx_unlock(&lun->lun_lock);
8259 				free(ctsio->kern_data_ptr, M_CTL);
8260 				ctl_set_reservation_conflict(ctsio);
8261 				ctl_done((union ctl_io *)ctsio);
8262 		        	return (1);
8263 			}
8264 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8265 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8266 			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8267 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8268 			persis_io.pr.pr_info.res_type = type;
8269 			memcpy(persis_io.pr.pr_info.sa_res_key,
8270 			       param->serv_act_res_key,
8271 			       sizeof(param->serv_act_res_key));
8272 			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8273 			     &persis_io, sizeof(persis_io), 0)) >
8274 			     CTL_HA_STATUS_SUCCESS) {
8275 				printf("CTL:Persis Out error returned "
8276 				       "from ctl_ha_msg_send %d\n",
8277 				isc_retval);
8278 			}
8279 		}
8280 	}
8281 
8282 	lun->PRGeneration++;
8283 	mtx_unlock(&lun->lun_lock);
8284 
8285 	return (retval);
8286 }
8287 
8288 static void
8289 ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8290 {
8291 	int i;
8292 
8293 	if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8294 	 || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8295 	 || memcmp(&lun->per_res[lun->pr_res_idx].res_key,
8296 		   msg->pr.pr_info.sa_res_key,
8297 		   sizeof(struct scsi_per_res_key)) != 0) {
8298 		uint64_t sa_res_key;
8299 		sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8300 
8301 		if (sa_res_key == 0) {
8302 			/* temporarily unregister this nexus */
8303 			lun->per_res[msg->pr.pr_info.residx].registered = 0;
8304 
8305 			/*
8306 			 * Unregister everybody else and build UA for
8307 			 * them
8308 			 */
8309 			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8310 				if (lun->per_res[i].registered == 0)
8311 					continue;
8312 
8313 				if (!persis_offset
8314 				 && i < CTL_MAX_INITIATORS)
8315 					lun->pending_ua[i] |=
8316 						CTL_UA_REG_PREEMPT;
8317 				else if (persis_offset && i >= persis_offset)
8318 					lun->pending_ua[i - persis_offset] |=
8319 						CTL_UA_REG_PREEMPT;
8320 				lun->per_res[i].registered = 0;
8321 				memset(&lun->per_res[i].res_key, 0,
8322 				       sizeof(struct scsi_per_res_key));
8323 			}
8324 
8325 			lun->per_res[msg->pr.pr_info.residx].registered = 1;
8326 			lun->pr_key_count = 1;
8327 			lun->res_type = msg->pr.pr_info.res_type;
8328 			if (lun->res_type != SPR_TYPE_WR_EX_AR
8329 			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8330 				lun->pr_res_idx = msg->pr.pr_info.residx;
8331 		} else {
8332 		        for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8333 				if (memcmp(msg->pr.pr_info.sa_res_key,
8334 		                   lun->per_res[i].res_key.key,
8335 		                   sizeof(struct scsi_per_res_key)) != 0)
8336 					continue;
8337 
8338 				lun->per_res[i].registered = 0;
8339 				memset(&lun->per_res[i].res_key, 0,
8340 				       sizeof(struct scsi_per_res_key));
8341 				lun->pr_key_count--;
8342 
8343 				if (!persis_offset
8344 				 && i < persis_offset)
8345 					lun->pending_ua[i] |=
8346 						CTL_UA_REG_PREEMPT;
8347 				else if (persis_offset
8348 				      && i >= persis_offset)
8349 					lun->pending_ua[i - persis_offset] |=
8350 						CTL_UA_REG_PREEMPT;
8351 			}
8352 		}
8353 	} else {
8354 		/*
8355 		 * Temporarily unregister so it won't get removed
8356 		 * or UA generated
8357 		 */
8358 		lun->per_res[msg->pr.pr_info.residx].registered = 0;
8359 		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8360 			if (lun->per_res[i].registered == 0)
8361 				continue;
8362 
8363 			if (memcmp(msg->pr.pr_info.sa_res_key,
8364 	                   lun->per_res[i].res_key.key,
8365 	                   sizeof(struct scsi_per_res_key)) == 0) {
8366 				lun->per_res[i].registered = 0;
8367 				memset(&lun->per_res[i].res_key, 0,
8368 				       sizeof(struct scsi_per_res_key));
8369 				lun->pr_key_count--;
8370 				if (!persis_offset
8371 				 && i < CTL_MAX_INITIATORS)
8372 					lun->pending_ua[i] |=
8373 						CTL_UA_REG_PREEMPT;
8374 				else if (persis_offset
8375 				      && i >= persis_offset)
8376 					lun->pending_ua[i - persis_offset] |=
8377 						CTL_UA_REG_PREEMPT;
8378 			} else if (msg->pr.pr_info.res_type != lun->res_type
8379 				&& (lun->res_type == SPR_TYPE_WR_EX_RO
8380 				 || lun->res_type == SPR_TYPE_EX_AC_RO)) {
8381 					if (!persis_offset
8382 					 && i < persis_offset)
8383 						lun->pending_ua[i] |=
8384 							CTL_UA_RES_RELEASE;
8385 					else if (persis_offset
8386 					      && i >= persis_offset)
8387 					lun->pending_ua[i - persis_offset] |=
8388 						CTL_UA_RES_RELEASE;
8389 			}
8390 		}
8391 		lun->per_res[msg->pr.pr_info.residx].registered = 1;
8392 		lun->res_type = msg->pr.pr_info.res_type;
8393 		if (lun->res_type != SPR_TYPE_WR_EX_AR
8394 		 && lun->res_type != SPR_TYPE_EX_AC_AR)
8395 			lun->pr_res_idx = msg->pr.pr_info.residx;
8396 		else
8397 			lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8398 	}
8399 	lun->PRGeneration++;
8400 
8401 }
8402 
8403 
8404 int
8405 ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8406 {
8407 	int retval;
8408 	int isc_retval;
8409 	u_int32_t param_len;
8410 	struct scsi_per_res_out *cdb;
8411 	struct ctl_lun *lun;
8412 	struct scsi_per_res_out_parms* param;
8413 	struct ctl_softc *softc;
8414 	uint32_t residx;
8415 	uint64_t res_key, sa_res_key;
8416 	uint8_t type;
8417 	union ctl_ha_msg persis_io;
8418 	int    i;
8419 
8420 	CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8421 
8422 	retval = CTL_RETVAL_COMPLETE;
8423 
8424 	softc = control_softc;
8425 
8426 	cdb = (struct scsi_per_res_out *)ctsio->cdb;
8427 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8428 
8429 	/*
8430 	 * We only support whole-LUN scope.  The scope & type are ignored for
8431 	 * register, register and ignore existing key and clear.
8432 	 * We sometimes ignore scope and type on preempts too!!
8433 	 * Verify reservation type here as well.
8434 	 */
8435 	type = cdb->scope_type & SPR_TYPE_MASK;
8436 	if ((cdb->action == SPRO_RESERVE)
8437 	 || (cdb->action == SPRO_RELEASE)) {
8438 		if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8439 			ctl_set_invalid_field(/*ctsio*/ ctsio,
8440 					      /*sks_valid*/ 1,
8441 					      /*command*/ 1,
8442 					      /*field*/ 2,
8443 					      /*bit_valid*/ 1,
8444 					      /*bit*/ 4);
8445 			ctl_done((union ctl_io *)ctsio);
8446 			return (CTL_RETVAL_COMPLETE);
8447 		}
8448 
8449 		if (type>8 || type==2 || type==4 || type==0) {
8450 			ctl_set_invalid_field(/*ctsio*/ ctsio,
8451 					      /*sks_valid*/ 1,
8452 					      /*command*/ 1,
8453 					      /*field*/ 2,
8454 					      /*bit_valid*/ 1,
8455 					      /*bit*/ 0);
8456 			ctl_done((union ctl_io *)ctsio);
8457 			return (CTL_RETVAL_COMPLETE);
8458 		}
8459 	}
8460 
8461 	param_len = scsi_4btoul(cdb->length);
8462 
8463 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8464 		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8465 		ctsio->kern_data_len = param_len;
8466 		ctsio->kern_total_len = param_len;
8467 		ctsio->kern_data_resid = 0;
8468 		ctsio->kern_rel_offset = 0;
8469 		ctsio->kern_sg_entries = 0;
8470 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8471 		ctsio->be_move_done = ctl_config_move_done;
8472 		ctl_datamove((union ctl_io *)ctsio);
8473 
8474 		return (CTL_RETVAL_COMPLETE);
8475 	}
8476 
8477 	param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8478 
8479 	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
8480 	res_key = scsi_8btou64(param->res_key.key);
8481 	sa_res_key = scsi_8btou64(param->serv_act_res_key);
8482 
8483 	/*
8484 	 * Validate the reservation key here except for SPRO_REG_IGNO
8485 	 * This must be done for all other service actions
8486 	 */
8487 	if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8488 		mtx_lock(&lun->lun_lock);
8489 		if (lun->per_res[residx].registered) {
8490 		    if (memcmp(param->res_key.key,
8491 			       lun->per_res[residx].res_key.key,
8492 			       ctl_min(sizeof(param->res_key),
8493 			       sizeof(lun->per_res[residx].res_key))) != 0) {
8494 				/*
8495 				 * The current key passed in doesn't match
8496 				 * the one the initiator previously
8497 				 * registered.
8498 				 */
8499 				mtx_unlock(&lun->lun_lock);
8500 				free(ctsio->kern_data_ptr, M_CTL);
8501 				ctl_set_reservation_conflict(ctsio);
8502 				ctl_done((union ctl_io *)ctsio);
8503 				return (CTL_RETVAL_COMPLETE);
8504 			}
8505 		} else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8506 			/*
8507 			 * We are not registered
8508 			 */
8509 			mtx_unlock(&lun->lun_lock);
8510 			free(ctsio->kern_data_ptr, M_CTL);
8511 			ctl_set_reservation_conflict(ctsio);
8512 			ctl_done((union ctl_io *)ctsio);
8513 			return (CTL_RETVAL_COMPLETE);
8514 		} else if (res_key != 0) {
8515 			/*
8516 			 * We are not registered and trying to register but
8517 			 * the register key isn't zero.
8518 			 */
8519 			mtx_unlock(&lun->lun_lock);
8520 			free(ctsio->kern_data_ptr, M_CTL);
8521 			ctl_set_reservation_conflict(ctsio);
8522 			ctl_done((union ctl_io *)ctsio);
8523 			return (CTL_RETVAL_COMPLETE);
8524 		}
8525 		mtx_unlock(&lun->lun_lock);
8526 	}
8527 
8528 	switch (cdb->action & SPRO_ACTION_MASK) {
8529 	case SPRO_REGISTER:
8530 	case SPRO_REG_IGNO: {
8531 
8532 #if 0
8533 		printf("Registration received\n");
8534 #endif
8535 
8536 		/*
8537 		 * We don't support any of these options, as we report in
8538 		 * the read capabilities request (see
8539 		 * ctl_persistent_reserve_in(), above).
8540 		 */
8541 		if ((param->flags & SPR_SPEC_I_PT)
8542 		 || (param->flags & SPR_ALL_TG_PT)
8543 		 || (param->flags & SPR_APTPL)) {
8544 			int bit_ptr;
8545 
8546 			if (param->flags & SPR_APTPL)
8547 				bit_ptr = 0;
8548 			else if (param->flags & SPR_ALL_TG_PT)
8549 				bit_ptr = 2;
8550 			else /* SPR_SPEC_I_PT */
8551 				bit_ptr = 3;
8552 
8553 			free(ctsio->kern_data_ptr, M_CTL);
8554 			ctl_set_invalid_field(ctsio,
8555 					      /*sks_valid*/ 1,
8556 					      /*command*/ 0,
8557 					      /*field*/ 20,
8558 					      /*bit_valid*/ 1,
8559 					      /*bit*/ bit_ptr);
8560 			ctl_done((union ctl_io *)ctsio);
8561 			return (CTL_RETVAL_COMPLETE);
8562 		}
8563 
8564 		mtx_lock(&lun->lun_lock);
8565 
8566 		/*
8567 		 * The initiator wants to clear the
8568 		 * key/unregister.
8569 		 */
8570 		if (sa_res_key == 0) {
8571 			if ((res_key == 0
8572 			  && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8573 			 || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8574 			  && !lun->per_res[residx].registered)) {
8575 				mtx_unlock(&lun->lun_lock);
8576 				goto done;
8577 			}
8578 
8579 			lun->per_res[residx].registered = 0;
8580 			memset(&lun->per_res[residx].res_key,
8581 			       0, sizeof(lun->per_res[residx].res_key));
8582 			lun->pr_key_count--;
8583 
8584 			if (residx == lun->pr_res_idx) {
8585 				lun->flags &= ~CTL_LUN_PR_RESERVED;
8586 				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8587 
8588 				if ((lun->res_type == SPR_TYPE_WR_EX_RO
8589 				  || lun->res_type == SPR_TYPE_EX_AC_RO)
8590 				 && lun->pr_key_count) {
8591 					/*
8592 					 * If the reservation is a registrants
8593 					 * only type we need to generate a UA
8594 					 * for other registered inits.  The
8595 					 * sense code should be RESERVATIONS
8596 					 * RELEASED
8597 					 */
8598 
8599 					for (i = 0; i < CTL_MAX_INITIATORS;i++){
8600 						if (lun->per_res[
8601 						    i+persis_offset].registered
8602 						    == 0)
8603 							continue;
8604 						lun->pending_ua[i] |=
8605 							CTL_UA_RES_RELEASE;
8606 					}
8607 				}
8608 				lun->res_type = 0;
8609 			} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8610 				if (lun->pr_key_count==0) {
8611 					lun->flags &= ~CTL_LUN_PR_RESERVED;
8612 					lun->res_type = 0;
8613 					lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8614 				}
8615 			}
8616 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8617 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8618 			persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8619 			persis_io.pr.pr_info.residx = residx;
8620 			if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8621 			     &persis_io, sizeof(persis_io), 0 )) >
8622 			     CTL_HA_STATUS_SUCCESS) {
8623 				printf("CTL:Persis Out error returned from "
8624 				       "ctl_ha_msg_send %d\n", isc_retval);
8625 			}
8626 		} else /* sa_res_key != 0 */ {
8627 
8628 			/*
8629 			 * If we aren't registered currently then increment
8630 			 * the key count and set the registered flag.
8631 			 */
8632 			if (!lun->per_res[residx].registered) {
8633 				lun->pr_key_count++;
8634 				lun->per_res[residx].registered = 1;
8635 			}
8636 
8637 			memcpy(&lun->per_res[residx].res_key,
8638 			       param->serv_act_res_key,
8639 			       ctl_min(sizeof(param->serv_act_res_key),
8640 			       sizeof(lun->per_res[residx].res_key)));
8641 
8642 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8643 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8644 			persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8645 			persis_io.pr.pr_info.residx = residx;
8646 			memcpy(persis_io.pr.pr_info.sa_res_key,
8647 			       param->serv_act_res_key,
8648 			       sizeof(param->serv_act_res_key));
8649 			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8650 			     &persis_io, sizeof(persis_io), 0)) >
8651 			     CTL_HA_STATUS_SUCCESS) {
8652 				printf("CTL:Persis Out error returned from "
8653 				       "ctl_ha_msg_send %d\n", isc_retval);
8654 			}
8655 		}
8656 		lun->PRGeneration++;
8657 		mtx_unlock(&lun->lun_lock);
8658 
8659 		break;
8660 	}
8661 	case SPRO_RESERVE:
8662 #if 0
8663                 printf("Reserve executed type %d\n", type);
8664 #endif
8665 		mtx_lock(&lun->lun_lock);
8666 		if (lun->flags & CTL_LUN_PR_RESERVED) {
8667 			/*
8668 			 * if this isn't the reservation holder and it's
8669 			 * not a "all registrants" type or if the type is
8670 			 * different then we have a conflict
8671 			 */
8672 			if ((lun->pr_res_idx != residx
8673 			  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8674 			 || lun->res_type != type) {
8675 				mtx_unlock(&lun->lun_lock);
8676 				free(ctsio->kern_data_ptr, M_CTL);
8677 				ctl_set_reservation_conflict(ctsio);
8678 				ctl_done((union ctl_io *)ctsio);
8679 				return (CTL_RETVAL_COMPLETE);
8680 			}
8681 			mtx_unlock(&lun->lun_lock);
8682 		} else /* create a reservation */ {
8683 			/*
8684 			 * If it's not an "all registrants" type record
8685 			 * reservation holder
8686 			 */
8687 			if (type != SPR_TYPE_WR_EX_AR
8688 			 && type != SPR_TYPE_EX_AC_AR)
8689 				lun->pr_res_idx = residx; /* Res holder */
8690 			else
8691 				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8692 
8693 			lun->flags |= CTL_LUN_PR_RESERVED;
8694 			lun->res_type = type;
8695 
8696 			mtx_unlock(&lun->lun_lock);
8697 
8698 			/* send msg to other side */
8699 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8700 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8701 			persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8702 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8703 			persis_io.pr.pr_info.res_type = type;
8704 			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8705 			     &persis_io, sizeof(persis_io), 0)) >
8706 			     CTL_HA_STATUS_SUCCESS) {
8707 				printf("CTL:Persis Out error returned from "
8708 				       "ctl_ha_msg_send %d\n", isc_retval);
8709 			}
8710 		}
8711 		break;
8712 
8713 	case SPRO_RELEASE:
8714 		mtx_lock(&lun->lun_lock);
8715 		if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8716 			/* No reservation exists return good status */
8717 			mtx_unlock(&lun->lun_lock);
8718 			goto done;
8719 		}
8720 		/*
8721 		 * Is this nexus a reservation holder?
8722 		 */
8723 		if (lun->pr_res_idx != residx
8724 		 && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8725 			/*
8726 			 * not a res holder return good status but
8727 			 * do nothing
8728 			 */
8729 			mtx_unlock(&lun->lun_lock);
8730 			goto done;
8731 		}
8732 
8733 		if (lun->res_type != type) {
8734 			mtx_unlock(&lun->lun_lock);
8735 			free(ctsio->kern_data_ptr, M_CTL);
8736 			ctl_set_illegal_pr_release(ctsio);
8737 			ctl_done((union ctl_io *)ctsio);
8738 			return (CTL_RETVAL_COMPLETE);
8739 		}
8740 
8741 		/* okay to release */
8742 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8743 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8744 		lun->res_type = 0;
8745 
8746 		/*
8747 		 * if this isn't an exclusive access
8748 		 * res generate UA for all other
8749 		 * registrants.
8750 		 */
8751 		if (type != SPR_TYPE_EX_AC
8752 		 && type != SPR_TYPE_WR_EX) {
8753 			/*
8754 			 * temporarily unregister so we don't generate UA
8755 			 */
8756 			lun->per_res[residx].registered = 0;
8757 
8758 			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8759 				if (lun->per_res[i+persis_offset].registered
8760 				    == 0)
8761 					continue;
8762 				lun->pending_ua[i] |=
8763 					CTL_UA_RES_RELEASE;
8764 			}
8765 
8766 			lun->per_res[residx].registered = 1;
8767 		}
8768 		mtx_unlock(&lun->lun_lock);
8769 		/* Send msg to other side */
8770 		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8771 		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8772 		persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8773 		if ((isc_retval=ctl_ha_msg_send( CTL_HA_CHAN_CTL, &persis_io,
8774 		     sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8775 			printf("CTL:Persis Out error returned from "
8776 			       "ctl_ha_msg_send %d\n", isc_retval);
8777 		}
8778 		break;
8779 
8780 	case SPRO_CLEAR:
8781 		/* send msg to other side */
8782 
8783 		mtx_lock(&lun->lun_lock);
8784 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8785 		lun->res_type = 0;
8786 		lun->pr_key_count = 0;
8787 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8788 
8789 
8790 		memset(&lun->per_res[residx].res_key,
8791 		       0, sizeof(lun->per_res[residx].res_key));
8792 		lun->per_res[residx].registered = 0;
8793 
8794 		for (i=0; i < 2*CTL_MAX_INITIATORS; i++)
8795 			if (lun->per_res[i].registered) {
8796 				if (!persis_offset && i < CTL_MAX_INITIATORS)
8797 					lun->pending_ua[i] |=
8798 						CTL_UA_RES_PREEMPT;
8799 				else if (persis_offset && i >= persis_offset)
8800 					lun->pending_ua[i-persis_offset] |=
8801 					    CTL_UA_RES_PREEMPT;
8802 
8803 				memset(&lun->per_res[i].res_key,
8804 				       0, sizeof(struct scsi_per_res_key));
8805 				lun->per_res[i].registered = 0;
8806 			}
8807 		lun->PRGeneration++;
8808 		mtx_unlock(&lun->lun_lock);
8809 		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8810 		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8811 		persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8812 		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8813 		     sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8814 			printf("CTL:Persis Out error returned from "
8815 			       "ctl_ha_msg_send %d\n", isc_retval);
8816 		}
8817 		break;
8818 
8819 	case SPRO_PREEMPT: {
8820 		int nretval;
8821 
8822 		nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8823 					  residx, ctsio, cdb, param);
8824 		if (nretval != 0)
8825 			return (CTL_RETVAL_COMPLETE);
8826 		break;
8827 	}
8828 	default:
8829 		panic("Invalid PR type %x", cdb->action);
8830 	}
8831 
8832 done:
8833 	free(ctsio->kern_data_ptr, M_CTL);
8834 	ctl_set_success(ctsio);
8835 	ctl_done((union ctl_io *)ctsio);
8836 
8837 	return (retval);
8838 }
8839 
8840 /*
8841  * This routine is for handling a message from the other SC pertaining to
8842  * persistent reserve out. All the error checking will have been done
8843  * so only perorming the action need be done here to keep the two
8844  * in sync.
8845  */
8846 static void
8847 ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg)
8848 {
8849 	struct ctl_lun *lun;
8850 	struct ctl_softc *softc;
8851 	int i;
8852 	uint32_t targ_lun;
8853 
8854 	softc = control_softc;
8855 
8856 	targ_lun = msg->hdr.nexus.targ_mapped_lun;
8857 	lun = softc->ctl_luns[targ_lun];
8858 	mtx_lock(&lun->lun_lock);
8859 	switch(msg->pr.pr_info.action) {
8860 	case CTL_PR_REG_KEY:
8861 		if (!lun->per_res[msg->pr.pr_info.residx].registered) {
8862 			lun->per_res[msg->pr.pr_info.residx].registered = 1;
8863 			lun->pr_key_count++;
8864 		}
8865 		lun->PRGeneration++;
8866 		memcpy(&lun->per_res[msg->pr.pr_info.residx].res_key,
8867 		       msg->pr.pr_info.sa_res_key,
8868 		       sizeof(struct scsi_per_res_key));
8869 		break;
8870 
8871 	case CTL_PR_UNREG_KEY:
8872 		lun->per_res[msg->pr.pr_info.residx].registered = 0;
8873 		memset(&lun->per_res[msg->pr.pr_info.residx].res_key,
8874 		       0, sizeof(struct scsi_per_res_key));
8875 		lun->pr_key_count--;
8876 
8877 		/* XXX Need to see if the reservation has been released */
8878 		/* if so do we need to generate UA? */
8879 		if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8880 			lun->flags &= ~CTL_LUN_PR_RESERVED;
8881 			lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8882 
8883 			if ((lun->res_type == SPR_TYPE_WR_EX_RO
8884 			  || lun->res_type == SPR_TYPE_EX_AC_RO)
8885 			 && lun->pr_key_count) {
8886 				/*
8887 				 * If the reservation is a registrants
8888 				 * only type we need to generate a UA
8889 				 * for other registered inits.  The
8890 				 * sense code should be RESERVATIONS
8891 				 * RELEASED
8892 				 */
8893 
8894 				for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8895 					if (lun->per_res[i+
8896 					    persis_offset].registered == 0)
8897 						continue;
8898 
8899 					lun->pending_ua[i] |=
8900 						CTL_UA_RES_RELEASE;
8901 				}
8902 			}
8903 			lun->res_type = 0;
8904 		} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8905 			if (lun->pr_key_count==0) {
8906 				lun->flags &= ~CTL_LUN_PR_RESERVED;
8907 				lun->res_type = 0;
8908 				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8909 			}
8910 		}
8911 		lun->PRGeneration++;
8912 		break;
8913 
8914 	case CTL_PR_RESERVE:
8915 		lun->flags |= CTL_LUN_PR_RESERVED;
8916 		lun->res_type = msg->pr.pr_info.res_type;
8917 		lun->pr_res_idx = msg->pr.pr_info.residx;
8918 
8919 		break;
8920 
8921 	case CTL_PR_RELEASE:
8922 		/*
8923 		 * if this isn't an exclusive access res generate UA for all
8924 		 * other registrants.
8925 		 */
8926 		if (lun->res_type != SPR_TYPE_EX_AC
8927 		 && lun->res_type != SPR_TYPE_WR_EX) {
8928 			for (i = 0; i < CTL_MAX_INITIATORS; i++)
8929 				if (lun->per_res[i+persis_offset].registered)
8930 					lun->pending_ua[i] |=
8931 						CTL_UA_RES_RELEASE;
8932 		}
8933 
8934 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8935 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8936 		lun->res_type = 0;
8937 		break;
8938 
8939 	case CTL_PR_PREEMPT:
8940 		ctl_pro_preempt_other(lun, msg);
8941 		break;
8942 	case CTL_PR_CLEAR:
8943 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8944 		lun->res_type = 0;
8945 		lun->pr_key_count = 0;
8946 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8947 
8948 		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8949 			if (lun->per_res[i].registered == 0)
8950 				continue;
8951 			if (!persis_offset
8952 			 && i < CTL_MAX_INITIATORS)
8953 				lun->pending_ua[i] |= CTL_UA_RES_PREEMPT;
8954 			else if (persis_offset
8955 			      && i >= persis_offset)
8956 				lun->pending_ua[i-persis_offset] |=
8957 					CTL_UA_RES_PREEMPT;
8958 			memset(&lun->per_res[i].res_key, 0,
8959 			       sizeof(struct scsi_per_res_key));
8960 			lun->per_res[i].registered = 0;
8961 		}
8962 		lun->PRGeneration++;
8963 		break;
8964 	}
8965 
8966 	mtx_unlock(&lun->lun_lock);
8967 }
8968 
8969 int
8970 ctl_read_write(struct ctl_scsiio *ctsio)
8971 {
8972 	struct ctl_lun *lun;
8973 	struct ctl_lba_len_flags *lbalen;
8974 	uint64_t lba;
8975 	uint32_t num_blocks;
8976 	int fua, dpo;
8977 	int retval;
8978 	int isread;
8979 
8980 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8981 
8982 	CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8983 
8984 	fua = 0;
8985 	dpo = 0;
8986 
8987 	retval = CTL_RETVAL_COMPLETE;
8988 
8989 	isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8990 	      || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8991 	if (lun->flags & CTL_LUN_PR_RESERVED && isread) {
8992 		uint32_t residx;
8993 
8994 		/*
8995 		 * XXX KDM need a lock here.
8996 		 */
8997 		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
8998 		if ((lun->res_type == SPR_TYPE_EX_AC
8999 		  && residx != lun->pr_res_idx)
9000 		 || ((lun->res_type == SPR_TYPE_EX_AC_RO
9001 		   || lun->res_type == SPR_TYPE_EX_AC_AR)
9002 		  && !lun->per_res[residx].registered)) {
9003 			ctl_set_reservation_conflict(ctsio);
9004 			ctl_done((union ctl_io *)ctsio);
9005 			return (CTL_RETVAL_COMPLETE);
9006 	        }
9007 	}
9008 
9009 	switch (ctsio->cdb[0]) {
9010 	case READ_6:
9011 	case WRITE_6: {
9012 		struct scsi_rw_6 *cdb;
9013 
9014 		cdb = (struct scsi_rw_6 *)ctsio->cdb;
9015 
9016 		lba = scsi_3btoul(cdb->addr);
9017 		/* only 5 bits are valid in the most significant address byte */
9018 		lba &= 0x1fffff;
9019 		num_blocks = cdb->length;
9020 		/*
9021 		 * This is correct according to SBC-2.
9022 		 */
9023 		if (num_blocks == 0)
9024 			num_blocks = 256;
9025 		break;
9026 	}
9027 	case READ_10:
9028 	case WRITE_10: {
9029 		struct scsi_rw_10 *cdb;
9030 
9031 		cdb = (struct scsi_rw_10 *)ctsio->cdb;
9032 
9033 		if (cdb->byte2 & SRW10_FUA)
9034 			fua = 1;
9035 		if (cdb->byte2 & SRW10_DPO)
9036 			dpo = 1;
9037 
9038 		lba = scsi_4btoul(cdb->addr);
9039 		num_blocks = scsi_2btoul(cdb->length);
9040 		break;
9041 	}
9042 	case WRITE_VERIFY_10: {
9043 		struct scsi_write_verify_10 *cdb;
9044 
9045 		cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
9046 
9047 		/*
9048 		 * XXX KDM we should do actual write verify support at some
9049 		 * point.  This is obviously fake, we're just translating
9050 		 * things to a write.  So we don't even bother checking the
9051 		 * BYTCHK field, since we don't do any verification.  If
9052 		 * the user asks for it, we'll just pretend we did it.
9053 		 */
9054 		if (cdb->byte2 & SWV_DPO)
9055 			dpo = 1;
9056 
9057 		lba = scsi_4btoul(cdb->addr);
9058 		num_blocks = scsi_2btoul(cdb->length);
9059 		break;
9060 	}
9061 	case READ_12:
9062 	case WRITE_12: {
9063 		struct scsi_rw_12 *cdb;
9064 
9065 		cdb = (struct scsi_rw_12 *)ctsio->cdb;
9066 
9067 		if (cdb->byte2 & SRW12_FUA)
9068 			fua = 1;
9069 		if (cdb->byte2 & SRW12_DPO)
9070 			dpo = 1;
9071 		lba = scsi_4btoul(cdb->addr);
9072 		num_blocks = scsi_4btoul(cdb->length);
9073 		break;
9074 	}
9075 	case WRITE_VERIFY_12: {
9076 		struct scsi_write_verify_12 *cdb;
9077 
9078 		cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
9079 
9080 		if (cdb->byte2 & SWV_DPO)
9081 			dpo = 1;
9082 
9083 		lba = scsi_4btoul(cdb->addr);
9084 		num_blocks = scsi_4btoul(cdb->length);
9085 
9086 		break;
9087 	}
9088 	case READ_16:
9089 	case WRITE_16: {
9090 		struct scsi_rw_16 *cdb;
9091 
9092 		cdb = (struct scsi_rw_16 *)ctsio->cdb;
9093 
9094 		if (cdb->byte2 & SRW12_FUA)
9095 			fua = 1;
9096 		if (cdb->byte2 & SRW12_DPO)
9097 			dpo = 1;
9098 
9099 		lba = scsi_8btou64(cdb->addr);
9100 		num_blocks = scsi_4btoul(cdb->length);
9101 		break;
9102 	}
9103 	case WRITE_VERIFY_16: {
9104 		struct scsi_write_verify_16 *cdb;
9105 
9106 		cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
9107 
9108 		if (cdb->byte2 & SWV_DPO)
9109 			dpo = 1;
9110 
9111 		lba = scsi_8btou64(cdb->addr);
9112 		num_blocks = scsi_4btoul(cdb->length);
9113 		break;
9114 	}
9115 	default:
9116 		/*
9117 		 * We got a command we don't support.  This shouldn't
9118 		 * happen, commands should be filtered out above us.
9119 		 */
9120 		ctl_set_invalid_opcode(ctsio);
9121 		ctl_done((union ctl_io *)ctsio);
9122 
9123 		return (CTL_RETVAL_COMPLETE);
9124 		break; /* NOTREACHED */
9125 	}
9126 
9127 	/*
9128 	 * XXX KDM what do we do with the DPO and FUA bits?  FUA might be
9129 	 * interesting for us, but if RAIDCore is in write-back mode,
9130 	 * getting it to do write-through for a particular transaction may
9131 	 * not be possible.
9132 	 */
9133 
9134 	/*
9135 	 * The first check is to make sure we're in bounds, the second
9136 	 * check is to catch wrap-around problems.  If the lba + num blocks
9137 	 * is less than the lba, then we've wrapped around and the block
9138 	 * range is invalid anyway.
9139 	 */
9140 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9141 	 || ((lba + num_blocks) < lba)) {
9142 		ctl_set_lba_out_of_range(ctsio);
9143 		ctl_done((union ctl_io *)ctsio);
9144 		return (CTL_RETVAL_COMPLETE);
9145 	}
9146 
9147 	/*
9148 	 * According to SBC-3, a transfer length of 0 is not an error.
9149 	 * Note that this cannot happen with WRITE(6) or READ(6), since 0
9150 	 * translates to 256 blocks for those commands.
9151 	 */
9152 	if (num_blocks == 0) {
9153 		ctl_set_success(ctsio);
9154 		ctl_done((union ctl_io *)ctsio);
9155 		return (CTL_RETVAL_COMPLETE);
9156 	}
9157 
9158 	lbalen = (struct ctl_lba_len_flags *)
9159 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9160 	lbalen->lba = lba;
9161 	lbalen->len = num_blocks;
9162 	lbalen->flags = isread ? CTL_LLF_READ : CTL_LLF_WRITE;
9163 
9164 	ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9165 	ctsio->kern_rel_offset = 0;
9166 
9167 	CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
9168 
9169 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9170 
9171 	return (retval);
9172 }
9173 
9174 static int
9175 ctl_cnw_cont(union ctl_io *io)
9176 {
9177 	struct ctl_scsiio *ctsio;
9178 	struct ctl_lun *lun;
9179 	struct ctl_lba_len_flags *lbalen;
9180 	int retval;
9181 
9182 	ctsio = &io->scsiio;
9183 	ctsio->io_hdr.status = CTL_STATUS_NONE;
9184 	ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
9185 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9186 	lbalen = (struct ctl_lba_len_flags *)
9187 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9188 	lbalen->flags = CTL_LLF_WRITE;
9189 
9190 	CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
9191 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9192 	return (retval);
9193 }
9194 
9195 int
9196 ctl_cnw(struct ctl_scsiio *ctsio)
9197 {
9198 	struct ctl_lun *lun;
9199 	struct ctl_lba_len_flags *lbalen;
9200 	uint64_t lba;
9201 	uint32_t num_blocks;
9202 	int fua, dpo;
9203 	int retval;
9204 
9205 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9206 
9207 	CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
9208 
9209 	fua = 0;
9210 	dpo = 0;
9211 
9212 	retval = CTL_RETVAL_COMPLETE;
9213 
9214 	switch (ctsio->cdb[0]) {
9215 	case COMPARE_AND_WRITE: {
9216 		struct scsi_compare_and_write *cdb;
9217 
9218 		cdb = (struct scsi_compare_and_write *)ctsio->cdb;
9219 
9220 		if (cdb->byte2 & SRW10_FUA)
9221 			fua = 1;
9222 		if (cdb->byte2 & SRW10_DPO)
9223 			dpo = 1;
9224 		lba = scsi_8btou64(cdb->addr);
9225 		num_blocks = cdb->length;
9226 		break;
9227 	}
9228 	default:
9229 		/*
9230 		 * We got a command we don't support.  This shouldn't
9231 		 * happen, commands should be filtered out above us.
9232 		 */
9233 		ctl_set_invalid_opcode(ctsio);
9234 		ctl_done((union ctl_io *)ctsio);
9235 
9236 		return (CTL_RETVAL_COMPLETE);
9237 		break; /* NOTREACHED */
9238 	}
9239 
9240 	/*
9241 	 * XXX KDM what do we do with the DPO and FUA bits?  FUA might be
9242 	 * interesting for us, but if RAIDCore is in write-back mode,
9243 	 * getting it to do write-through for a particular transaction may
9244 	 * not be possible.
9245 	 */
9246 
9247 	/*
9248 	 * The first check is to make sure we're in bounds, the second
9249 	 * check is to catch wrap-around problems.  If the lba + num blocks
9250 	 * is less than the lba, then we've wrapped around and the block
9251 	 * range is invalid anyway.
9252 	 */
9253 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9254 	 || ((lba + num_blocks) < lba)) {
9255 		ctl_set_lba_out_of_range(ctsio);
9256 		ctl_done((union ctl_io *)ctsio);
9257 		return (CTL_RETVAL_COMPLETE);
9258 	}
9259 
9260 	/*
9261 	 * According to SBC-3, a transfer length of 0 is not an error.
9262 	 */
9263 	if (num_blocks == 0) {
9264 		ctl_set_success(ctsio);
9265 		ctl_done((union ctl_io *)ctsio);
9266 		return (CTL_RETVAL_COMPLETE);
9267 	}
9268 
9269 	ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
9270 	ctsio->kern_rel_offset = 0;
9271 
9272 	/*
9273 	 * Set the IO_CONT flag, so that if this I/O gets passed to
9274 	 * ctl_data_submit_done(), it'll get passed back to
9275 	 * ctl_ctl_cnw_cont() for further processing.
9276 	 */
9277 	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
9278 	ctsio->io_cont = ctl_cnw_cont;
9279 
9280 	lbalen = (struct ctl_lba_len_flags *)
9281 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9282 	lbalen->lba = lba;
9283 	lbalen->len = num_blocks;
9284 	lbalen->flags = CTL_LLF_COMPARE;
9285 
9286 	CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
9287 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9288 	return (retval);
9289 }
9290 
9291 int
9292 ctl_verify(struct ctl_scsiio *ctsio)
9293 {
9294 	struct ctl_lun *lun;
9295 	struct ctl_lba_len_flags *lbalen;
9296 	uint64_t lba;
9297 	uint32_t num_blocks;
9298 	int bytchk, dpo;
9299 	int retval;
9300 
9301 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9302 
9303 	CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
9304 
9305 	bytchk = 0;
9306 	dpo = 0;
9307 	retval = CTL_RETVAL_COMPLETE;
9308 
9309 	switch (ctsio->cdb[0]) {
9310 	case VERIFY_10: {
9311 		struct scsi_verify_10 *cdb;
9312 
9313 		cdb = (struct scsi_verify_10 *)ctsio->cdb;
9314 		if (cdb->byte2 & SVFY_BYTCHK)
9315 			bytchk = 1;
9316 		if (cdb->byte2 & SVFY_DPO)
9317 			dpo = 1;
9318 		lba = scsi_4btoul(cdb->addr);
9319 		num_blocks = scsi_2btoul(cdb->length);
9320 		break;
9321 	}
9322 	case VERIFY_12: {
9323 		struct scsi_verify_12 *cdb;
9324 
9325 		cdb = (struct scsi_verify_12 *)ctsio->cdb;
9326 		if (cdb->byte2 & SVFY_BYTCHK)
9327 			bytchk = 1;
9328 		if (cdb->byte2 & SVFY_DPO)
9329 			dpo = 1;
9330 		lba = scsi_4btoul(cdb->addr);
9331 		num_blocks = scsi_4btoul(cdb->length);
9332 		break;
9333 	}
9334 	case VERIFY_16: {
9335 		struct scsi_rw_16 *cdb;
9336 
9337 		cdb = (struct scsi_rw_16 *)ctsio->cdb;
9338 		if (cdb->byte2 & SVFY_BYTCHK)
9339 			bytchk = 1;
9340 		if (cdb->byte2 & SVFY_DPO)
9341 			dpo = 1;
9342 		lba = scsi_8btou64(cdb->addr);
9343 		num_blocks = scsi_4btoul(cdb->length);
9344 		break;
9345 	}
9346 	default:
9347 		/*
9348 		 * We got a command we don't support.  This shouldn't
9349 		 * happen, commands should be filtered out above us.
9350 		 */
9351 		ctl_set_invalid_opcode(ctsio);
9352 		ctl_done((union ctl_io *)ctsio);
9353 		return (CTL_RETVAL_COMPLETE);
9354 	}
9355 
9356 	/*
9357 	 * The first check is to make sure we're in bounds, the second
9358 	 * check is to catch wrap-around problems.  If the lba + num blocks
9359 	 * is less than the lba, then we've wrapped around and the block
9360 	 * range is invalid anyway.
9361 	 */
9362 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9363 	 || ((lba + num_blocks) < lba)) {
9364 		ctl_set_lba_out_of_range(ctsio);
9365 		ctl_done((union ctl_io *)ctsio);
9366 		return (CTL_RETVAL_COMPLETE);
9367 	}
9368 
9369 	/*
9370 	 * According to SBC-3, a transfer length of 0 is not an error.
9371 	 */
9372 	if (num_blocks == 0) {
9373 		ctl_set_success(ctsio);
9374 		ctl_done((union ctl_io *)ctsio);
9375 		return (CTL_RETVAL_COMPLETE);
9376 	}
9377 
9378 	lbalen = (struct ctl_lba_len_flags *)
9379 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9380 	lbalen->lba = lba;
9381 	lbalen->len = num_blocks;
9382 	if (bytchk) {
9383 		lbalen->flags = CTL_LLF_COMPARE;
9384 		ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9385 	} else {
9386 		lbalen->flags = CTL_LLF_VERIFY;
9387 		ctsio->kern_total_len = 0;
9388 	}
9389 	ctsio->kern_rel_offset = 0;
9390 
9391 	CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9392 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9393 	return (retval);
9394 }
9395 
9396 int
9397 ctl_report_luns(struct ctl_scsiio *ctsio)
9398 {
9399 	struct scsi_report_luns *cdb;
9400 	struct scsi_report_luns_data *lun_data;
9401 	struct ctl_lun *lun, *request_lun;
9402 	int num_luns, retval;
9403 	uint32_t alloc_len, lun_datalen;
9404 	int num_filled, well_known;
9405 	uint32_t initidx, targ_lun_id, lun_id;
9406 
9407 	retval = CTL_RETVAL_COMPLETE;
9408 	well_known = 0;
9409 
9410 	cdb = (struct scsi_report_luns *)ctsio->cdb;
9411 
9412 	CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9413 
9414 	mtx_lock(&control_softc->ctl_lock);
9415 	num_luns = control_softc->num_luns;
9416 	mtx_unlock(&control_softc->ctl_lock);
9417 
9418 	switch (cdb->select_report) {
9419 	case RPL_REPORT_DEFAULT:
9420 	case RPL_REPORT_ALL:
9421 		break;
9422 	case RPL_REPORT_WELLKNOWN:
9423 		well_known = 1;
9424 		num_luns = 0;
9425 		break;
9426 	default:
9427 		ctl_set_invalid_field(ctsio,
9428 				      /*sks_valid*/ 1,
9429 				      /*command*/ 1,
9430 				      /*field*/ 2,
9431 				      /*bit_valid*/ 0,
9432 				      /*bit*/ 0);
9433 		ctl_done((union ctl_io *)ctsio);
9434 		return (retval);
9435 		break; /* NOTREACHED */
9436 	}
9437 
9438 	alloc_len = scsi_4btoul(cdb->length);
9439 	/*
9440 	 * The initiator has to allocate at least 16 bytes for this request,
9441 	 * so he can at least get the header and the first LUN.  Otherwise
9442 	 * we reject the request (per SPC-3 rev 14, section 6.21).
9443 	 */
9444 	if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9445 	    sizeof(struct scsi_report_luns_lundata))) {
9446 		ctl_set_invalid_field(ctsio,
9447 				      /*sks_valid*/ 1,
9448 				      /*command*/ 1,
9449 				      /*field*/ 6,
9450 				      /*bit_valid*/ 0,
9451 				      /*bit*/ 0);
9452 		ctl_done((union ctl_io *)ctsio);
9453 		return (retval);
9454 	}
9455 
9456 	request_lun = (struct ctl_lun *)
9457 		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9458 
9459 	lun_datalen = sizeof(*lun_data) +
9460 		(num_luns * sizeof(struct scsi_report_luns_lundata));
9461 
9462 	ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9463 	lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9464 	ctsio->kern_sg_entries = 0;
9465 
9466 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9467 
9468 	mtx_lock(&control_softc->ctl_lock);
9469 	for (targ_lun_id = 0, num_filled = 0; targ_lun_id < CTL_MAX_LUNS && num_filled < num_luns; targ_lun_id++) {
9470 		lun_id = ctl_map_lun(ctsio->io_hdr.nexus.targ_port, targ_lun_id);
9471 		if (lun_id >= CTL_MAX_LUNS)
9472 			continue;
9473 		lun = control_softc->ctl_luns[lun_id];
9474 		if (lun == NULL)
9475 			continue;
9476 
9477 		if (targ_lun_id <= 0xff) {
9478 			/*
9479 			 * Peripheral addressing method, bus number 0.
9480 			 */
9481 			lun_data->luns[num_filled].lundata[0] =
9482 				RPL_LUNDATA_ATYP_PERIPH;
9483 			lun_data->luns[num_filled].lundata[1] = targ_lun_id;
9484 			num_filled++;
9485 		} else if (targ_lun_id <= 0x3fff) {
9486 			/*
9487 			 * Flat addressing method.
9488 			 */
9489 			lun_data->luns[num_filled].lundata[0] =
9490 				RPL_LUNDATA_ATYP_FLAT |
9491 				(targ_lun_id & RPL_LUNDATA_FLAT_LUN_MASK);
9492 #ifdef OLDCTLHEADERS
9493 				(SRLD_ADDR_FLAT << SRLD_ADDR_SHIFT) |
9494 				(targ_lun_id & SRLD_BUS_LUN_MASK);
9495 #endif
9496 			lun_data->luns[num_filled].lundata[1] =
9497 #ifdef OLDCTLHEADERS
9498 				targ_lun_id >> SRLD_BUS_LUN_BITS;
9499 #endif
9500 				targ_lun_id >> RPL_LUNDATA_FLAT_LUN_BITS;
9501 			num_filled++;
9502 		} else {
9503 			printf("ctl_report_luns: bogus LUN number %jd, "
9504 			       "skipping\n", (intmax_t)targ_lun_id);
9505 		}
9506 		/*
9507 		 * According to SPC-3, rev 14 section 6.21:
9508 		 *
9509 		 * "The execution of a REPORT LUNS command to any valid and
9510 		 * installed logical unit shall clear the REPORTED LUNS DATA
9511 		 * HAS CHANGED unit attention condition for all logical
9512 		 * units of that target with respect to the requesting
9513 		 * initiator. A valid and installed logical unit is one
9514 		 * having a PERIPHERAL QUALIFIER of 000b in the standard
9515 		 * INQUIRY data (see 6.4.2)."
9516 		 *
9517 		 * If request_lun is NULL, the LUN this report luns command
9518 		 * was issued to is either disabled or doesn't exist. In that
9519 		 * case, we shouldn't clear any pending lun change unit
9520 		 * attention.
9521 		 */
9522 		if (request_lun != NULL) {
9523 			mtx_lock(&lun->lun_lock);
9524 			lun->pending_ua[initidx] &= ~CTL_UA_LUN_CHANGE;
9525 			mtx_unlock(&lun->lun_lock);
9526 		}
9527 	}
9528 	mtx_unlock(&control_softc->ctl_lock);
9529 
9530 	/*
9531 	 * It's quite possible that we've returned fewer LUNs than we allocated
9532 	 * space for.  Trim it.
9533 	 */
9534 	lun_datalen = sizeof(*lun_data) +
9535 		(num_filled * sizeof(struct scsi_report_luns_lundata));
9536 
9537 	if (lun_datalen < alloc_len) {
9538 		ctsio->residual = alloc_len - lun_datalen;
9539 		ctsio->kern_data_len = lun_datalen;
9540 		ctsio->kern_total_len = lun_datalen;
9541 	} else {
9542 		ctsio->residual = 0;
9543 		ctsio->kern_data_len = alloc_len;
9544 		ctsio->kern_total_len = alloc_len;
9545 	}
9546 	ctsio->kern_data_resid = 0;
9547 	ctsio->kern_rel_offset = 0;
9548 	ctsio->kern_sg_entries = 0;
9549 
9550 	/*
9551 	 * We set this to the actual data length, regardless of how much
9552 	 * space we actually have to return results.  If the user looks at
9553 	 * this value, he'll know whether or not he allocated enough space
9554 	 * and reissue the command if necessary.  We don't support well
9555 	 * known logical units, so if the user asks for that, return none.
9556 	 */
9557 	scsi_ulto4b(lun_datalen - 8, lun_data->length);
9558 
9559 	/*
9560 	 * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9561 	 * this request.
9562 	 */
9563 	ctsio->scsi_status = SCSI_STATUS_OK;
9564 
9565 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9566 	ctsio->be_move_done = ctl_config_move_done;
9567 	ctl_datamove((union ctl_io *)ctsio);
9568 
9569 	return (retval);
9570 }
9571 
9572 int
9573 ctl_request_sense(struct ctl_scsiio *ctsio)
9574 {
9575 	struct scsi_request_sense *cdb;
9576 	struct scsi_sense_data *sense_ptr;
9577 	struct ctl_lun *lun;
9578 	uint32_t initidx;
9579 	int have_error;
9580 	scsi_sense_data_type sense_format;
9581 
9582 	cdb = (struct scsi_request_sense *)ctsio->cdb;
9583 
9584 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9585 
9586 	CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9587 
9588 	/*
9589 	 * Determine which sense format the user wants.
9590 	 */
9591 	if (cdb->byte2 & SRS_DESC)
9592 		sense_format = SSD_TYPE_DESC;
9593 	else
9594 		sense_format = SSD_TYPE_FIXED;
9595 
9596 	ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9597 	sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9598 	ctsio->kern_sg_entries = 0;
9599 
9600 	/*
9601 	 * struct scsi_sense_data, which is currently set to 256 bytes, is
9602 	 * larger than the largest allowed value for the length field in the
9603 	 * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9604 	 */
9605 	ctsio->residual = 0;
9606 	ctsio->kern_data_len = cdb->length;
9607 	ctsio->kern_total_len = cdb->length;
9608 
9609 	ctsio->kern_data_resid = 0;
9610 	ctsio->kern_rel_offset = 0;
9611 	ctsio->kern_sg_entries = 0;
9612 
9613 	/*
9614 	 * If we don't have a LUN, we don't have any pending sense.
9615 	 */
9616 	if (lun == NULL)
9617 		goto no_sense;
9618 
9619 	have_error = 0;
9620 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9621 	/*
9622 	 * Check for pending sense, and then for pending unit attentions.
9623 	 * Pending sense gets returned first, then pending unit attentions.
9624 	 */
9625 	mtx_lock(&lun->lun_lock);
9626 #ifdef CTL_WITH_CA
9627 	if (ctl_is_set(lun->have_ca, initidx)) {
9628 		scsi_sense_data_type stored_format;
9629 
9630 		/*
9631 		 * Check to see which sense format was used for the stored
9632 		 * sense data.
9633 		 */
9634 		stored_format = scsi_sense_type(&lun->pending_sense[initidx]);
9635 
9636 		/*
9637 		 * If the user requested a different sense format than the
9638 		 * one we stored, then we need to convert it to the other
9639 		 * format.  If we're going from descriptor to fixed format
9640 		 * sense data, we may lose things in translation, depending
9641 		 * on what options were used.
9642 		 *
9643 		 * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9644 		 * for some reason we'll just copy it out as-is.
9645 		 */
9646 		if ((stored_format == SSD_TYPE_FIXED)
9647 		 && (sense_format == SSD_TYPE_DESC))
9648 			ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9649 			    &lun->pending_sense[initidx],
9650 			    (struct scsi_sense_data_desc *)sense_ptr);
9651 		else if ((stored_format == SSD_TYPE_DESC)
9652 		      && (sense_format == SSD_TYPE_FIXED))
9653 			ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9654 			    &lun->pending_sense[initidx],
9655 			    (struct scsi_sense_data_fixed *)sense_ptr);
9656 		else
9657 			memcpy(sense_ptr, &lun->pending_sense[initidx],
9658 			       ctl_min(sizeof(*sense_ptr),
9659 			       sizeof(lun->pending_sense[initidx])));
9660 
9661 		ctl_clear_mask(lun->have_ca, initidx);
9662 		have_error = 1;
9663 	} else
9664 #endif
9665 	if (lun->pending_ua[initidx] != CTL_UA_NONE) {
9666 		ctl_ua_type ua_type;
9667 
9668 		ua_type = ctl_build_ua(lun->pending_ua[initidx],
9669 				       sense_ptr, sense_format);
9670 		if (ua_type != CTL_UA_NONE) {
9671 			have_error = 1;
9672 			/* We're reporting this UA, so clear it */
9673 			lun->pending_ua[initidx] &= ~ua_type;
9674 		}
9675 	}
9676 	mtx_unlock(&lun->lun_lock);
9677 
9678 	/*
9679 	 * We already have a pending error, return it.
9680 	 */
9681 	if (have_error != 0) {
9682 		/*
9683 		 * We report the SCSI status as OK, since the status of the
9684 		 * request sense command itself is OK.
9685 		 */
9686 		ctsio->scsi_status = SCSI_STATUS_OK;
9687 
9688 		/*
9689 		 * We report 0 for the sense length, because we aren't doing
9690 		 * autosense in this case.  We're reporting sense as
9691 		 * parameter data.
9692 		 */
9693 		ctsio->sense_len = 0;
9694 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9695 		ctsio->be_move_done = ctl_config_move_done;
9696 		ctl_datamove((union ctl_io *)ctsio);
9697 
9698 		return (CTL_RETVAL_COMPLETE);
9699 	}
9700 
9701 no_sense:
9702 
9703 	/*
9704 	 * No sense information to report, so we report that everything is
9705 	 * okay.
9706 	 */
9707 	ctl_set_sense_data(sense_ptr,
9708 			   lun,
9709 			   sense_format,
9710 			   /*current_error*/ 1,
9711 			   /*sense_key*/ SSD_KEY_NO_SENSE,
9712 			   /*asc*/ 0x00,
9713 			   /*ascq*/ 0x00,
9714 			   SSD_ELEM_NONE);
9715 
9716 	ctsio->scsi_status = SCSI_STATUS_OK;
9717 
9718 	/*
9719 	 * We report 0 for the sense length, because we aren't doing
9720 	 * autosense in this case.  We're reporting sense as parameter data.
9721 	 */
9722 	ctsio->sense_len = 0;
9723 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9724 	ctsio->be_move_done = ctl_config_move_done;
9725 	ctl_datamove((union ctl_io *)ctsio);
9726 
9727 	return (CTL_RETVAL_COMPLETE);
9728 }
9729 
9730 int
9731 ctl_tur(struct ctl_scsiio *ctsio)
9732 {
9733 	struct ctl_lun *lun;
9734 
9735 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9736 
9737 	CTL_DEBUG_PRINT(("ctl_tur\n"));
9738 
9739 	if (lun == NULL)
9740 		return (EINVAL);
9741 
9742 	ctsio->scsi_status = SCSI_STATUS_OK;
9743 	ctsio->io_hdr.status = CTL_SUCCESS;
9744 
9745 	ctl_done((union ctl_io *)ctsio);
9746 
9747 	return (CTL_RETVAL_COMPLETE);
9748 }
9749 
9750 #ifdef notyet
9751 static int
9752 ctl_cmddt_inquiry(struct ctl_scsiio *ctsio)
9753 {
9754 
9755 }
9756 #endif
9757 
9758 static int
9759 ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9760 {
9761 	struct scsi_vpd_supported_pages *pages;
9762 	int sup_page_size;
9763 	struct ctl_lun *lun;
9764 
9765 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9766 
9767 	sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9768 	    SCSI_EVPD_NUM_SUPPORTED_PAGES;
9769 	ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9770 	pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9771 	ctsio->kern_sg_entries = 0;
9772 
9773 	if (sup_page_size < alloc_len) {
9774 		ctsio->residual = alloc_len - sup_page_size;
9775 		ctsio->kern_data_len = sup_page_size;
9776 		ctsio->kern_total_len = sup_page_size;
9777 	} else {
9778 		ctsio->residual = 0;
9779 		ctsio->kern_data_len = alloc_len;
9780 		ctsio->kern_total_len = alloc_len;
9781 	}
9782 	ctsio->kern_data_resid = 0;
9783 	ctsio->kern_rel_offset = 0;
9784 	ctsio->kern_sg_entries = 0;
9785 
9786 	/*
9787 	 * The control device is always connected.  The disk device, on the
9788 	 * other hand, may not be online all the time.  Need to change this
9789 	 * to figure out whether the disk device is actually online or not.
9790 	 */
9791 	if (lun != NULL)
9792 		pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9793 				lun->be_lun->lun_type;
9794 	else
9795 		pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9796 
9797 	pages->length = SCSI_EVPD_NUM_SUPPORTED_PAGES;
9798 	/* Supported VPD pages */
9799 	pages->page_list[0] = SVPD_SUPPORTED_PAGES;
9800 	/* Serial Number */
9801 	pages->page_list[1] = SVPD_UNIT_SERIAL_NUMBER;
9802 	/* Device Identification */
9803 	pages->page_list[2] = SVPD_DEVICE_ID;
9804 	/* SCSI Ports */
9805 	pages->page_list[3] = SVPD_SCSI_PORTS;
9806 	/* Third-party Copy */
9807 	pages->page_list[4] = SVPD_SCSI_TPC;
9808 	/* Block limits */
9809 	pages->page_list[5] = SVPD_BLOCK_LIMITS;
9810 	/* Logical Block Provisioning */
9811 	pages->page_list[6] = SVPD_LBP;
9812 
9813 	ctsio->scsi_status = SCSI_STATUS_OK;
9814 
9815 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9816 	ctsio->be_move_done = ctl_config_move_done;
9817 	ctl_datamove((union ctl_io *)ctsio);
9818 
9819 	return (CTL_RETVAL_COMPLETE);
9820 }
9821 
9822 static int
9823 ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9824 {
9825 	struct scsi_vpd_unit_serial_number *sn_ptr;
9826 	struct ctl_lun *lun;
9827 
9828 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9829 
9830 	ctsio->kern_data_ptr = malloc(sizeof(*sn_ptr), M_CTL, M_WAITOK | M_ZERO);
9831 	sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9832 	ctsio->kern_sg_entries = 0;
9833 
9834 	if (sizeof(*sn_ptr) < alloc_len) {
9835 		ctsio->residual = alloc_len - sizeof(*sn_ptr);
9836 		ctsio->kern_data_len = sizeof(*sn_ptr);
9837 		ctsio->kern_total_len = sizeof(*sn_ptr);
9838 	} else {
9839 		ctsio->residual = 0;
9840 		ctsio->kern_data_len = alloc_len;
9841 		ctsio->kern_total_len = alloc_len;
9842 	}
9843 	ctsio->kern_data_resid = 0;
9844 	ctsio->kern_rel_offset = 0;
9845 	ctsio->kern_sg_entries = 0;
9846 
9847 	/*
9848 	 * The control device is always connected.  The disk device, on the
9849 	 * other hand, may not be online all the time.  Need to change this
9850 	 * to figure out whether the disk device is actually online or not.
9851 	 */
9852 	if (lun != NULL)
9853 		sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9854 				  lun->be_lun->lun_type;
9855 	else
9856 		sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9857 
9858 	sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9859 	sn_ptr->length = ctl_min(sizeof(*sn_ptr) - 4, CTL_SN_LEN);
9860 	/*
9861 	 * If we don't have a LUN, we just leave the serial number as
9862 	 * all spaces.
9863 	 */
9864 	memset(sn_ptr->serial_num, 0x20, sizeof(sn_ptr->serial_num));
9865 	if (lun != NULL) {
9866 		strncpy((char *)sn_ptr->serial_num,
9867 			(char *)lun->be_lun->serial_num, CTL_SN_LEN);
9868 	}
9869 	ctsio->scsi_status = SCSI_STATUS_OK;
9870 
9871 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9872 	ctsio->be_move_done = ctl_config_move_done;
9873 	ctl_datamove((union ctl_io *)ctsio);
9874 
9875 	return (CTL_RETVAL_COMPLETE);
9876 }
9877 
9878 
9879 static int
9880 ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9881 {
9882 	struct scsi_vpd_device_id *devid_ptr;
9883 	struct scsi_vpd_id_descriptor *desc;
9884 	struct ctl_softc *ctl_softc;
9885 	struct ctl_lun *lun;
9886 	struct ctl_port *port;
9887 	int data_len;
9888 	uint8_t proto;
9889 
9890 	ctl_softc = control_softc;
9891 
9892 	port = ctl_softc->ctl_ports[ctl_port_idx(ctsio->io_hdr.nexus.targ_port)];
9893 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9894 
9895 	data_len = sizeof(struct scsi_vpd_device_id) +
9896 	    sizeof(struct scsi_vpd_id_descriptor) +
9897 		sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9898 	    sizeof(struct scsi_vpd_id_descriptor) +
9899 		sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9900 	if (lun && lun->lun_devid)
9901 		data_len += lun->lun_devid->len;
9902 	if (port->port_devid)
9903 		data_len += port->port_devid->len;
9904 	if (port->target_devid)
9905 		data_len += port->target_devid->len;
9906 
9907 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9908 	devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9909 	ctsio->kern_sg_entries = 0;
9910 
9911 	if (data_len < alloc_len) {
9912 		ctsio->residual = alloc_len - data_len;
9913 		ctsio->kern_data_len = data_len;
9914 		ctsio->kern_total_len = data_len;
9915 	} else {
9916 		ctsio->residual = 0;
9917 		ctsio->kern_data_len = alloc_len;
9918 		ctsio->kern_total_len = alloc_len;
9919 	}
9920 	ctsio->kern_data_resid = 0;
9921 	ctsio->kern_rel_offset = 0;
9922 	ctsio->kern_sg_entries = 0;
9923 
9924 	/*
9925 	 * The control device is always connected.  The disk device, on the
9926 	 * other hand, may not be online all the time.
9927 	 */
9928 	if (lun != NULL)
9929 		devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9930 				     lun->be_lun->lun_type;
9931 	else
9932 		devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9933 	devid_ptr->page_code = SVPD_DEVICE_ID;
9934 	scsi_ulto2b(data_len - 4, devid_ptr->length);
9935 
9936 	if (port->port_type == CTL_PORT_FC)
9937 		proto = SCSI_PROTO_FC << 4;
9938 	else if (port->port_type == CTL_PORT_ISCSI)
9939 		proto = SCSI_PROTO_ISCSI << 4;
9940 	else
9941 		proto = SCSI_PROTO_SPI << 4;
9942 	desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
9943 
9944 	/*
9945 	 * We're using a LUN association here.  i.e., this device ID is a
9946 	 * per-LUN identifier.
9947 	 */
9948 	if (lun && lun->lun_devid) {
9949 		memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
9950 		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9951 		    lun->lun_devid->len);
9952 	}
9953 
9954 	/*
9955 	 * This is for the WWPN which is a port association.
9956 	 */
9957 	if (port->port_devid) {
9958 		memcpy(desc, port->port_devid->data, port->port_devid->len);
9959 		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9960 		    port->port_devid->len);
9961 	}
9962 
9963 	/*
9964 	 * This is for the Relative Target Port(type 4h) identifier
9965 	 */
9966 	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9967 	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9968 	    SVPD_ID_TYPE_RELTARG;
9969 	desc->length = 4;
9970 	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
9971 	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9972 	    sizeof(struct scsi_vpd_id_rel_trgt_port_id));
9973 
9974 	/*
9975 	 * This is for the Target Port Group(type 5h) identifier
9976 	 */
9977 	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9978 	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9979 	    SVPD_ID_TYPE_TPORTGRP;
9980 	desc->length = 4;
9981 	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port / CTL_MAX_PORTS + 1,
9982 	    &desc->identifier[2]);
9983 	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9984 	    sizeof(struct scsi_vpd_id_trgt_port_grp_id));
9985 
9986 	/*
9987 	 * This is for the Target identifier
9988 	 */
9989 	if (port->target_devid) {
9990 		memcpy(desc, port->target_devid->data, port->target_devid->len);
9991 	}
9992 
9993 	ctsio->scsi_status = SCSI_STATUS_OK;
9994 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9995 	ctsio->be_move_done = ctl_config_move_done;
9996 	ctl_datamove((union ctl_io *)ctsio);
9997 
9998 	return (CTL_RETVAL_COMPLETE);
9999 }
10000 
10001 static int
10002 ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
10003 {
10004 	struct ctl_softc *softc = control_softc;
10005 	struct scsi_vpd_scsi_ports *sp;
10006 	struct scsi_vpd_port_designation *pd;
10007 	struct scsi_vpd_port_designation_cont *pdc;
10008 	struct ctl_lun *lun;
10009 	struct ctl_port *port;
10010 	int data_len, num_target_ports, iid_len, id_len, g, pg, p;
10011 	int num_target_port_groups, single;
10012 
10013 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10014 
10015 	single = ctl_is_single;
10016 	if (single)
10017 		num_target_port_groups = 1;
10018 	else
10019 		num_target_port_groups = NUM_TARGET_PORT_GROUPS;
10020 	num_target_ports = 0;
10021 	iid_len = 0;
10022 	id_len = 0;
10023 	mtx_lock(&softc->ctl_lock);
10024 	STAILQ_FOREACH(port, &softc->port_list, links) {
10025 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
10026 			continue;
10027 		if (ctl_map_lun_back(port->targ_port, lun->lun) >=
10028 		    CTL_MAX_LUNS)
10029 			continue;
10030 		num_target_ports++;
10031 		if (port->init_devid)
10032 			iid_len += port->init_devid->len;
10033 		if (port->port_devid)
10034 			id_len += port->port_devid->len;
10035 	}
10036 	mtx_unlock(&softc->ctl_lock);
10037 
10038 	data_len = sizeof(struct scsi_vpd_scsi_ports) + num_target_port_groups *
10039 	    num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
10040 	     sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
10041 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10042 	sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
10043 	ctsio->kern_sg_entries = 0;
10044 
10045 	if (data_len < alloc_len) {
10046 		ctsio->residual = alloc_len - data_len;
10047 		ctsio->kern_data_len = data_len;
10048 		ctsio->kern_total_len = data_len;
10049 	} else {
10050 		ctsio->residual = 0;
10051 		ctsio->kern_data_len = alloc_len;
10052 		ctsio->kern_total_len = alloc_len;
10053 	}
10054 	ctsio->kern_data_resid = 0;
10055 	ctsio->kern_rel_offset = 0;
10056 	ctsio->kern_sg_entries = 0;
10057 
10058 	/*
10059 	 * The control device is always connected.  The disk device, on the
10060 	 * other hand, may not be online all the time.  Need to change this
10061 	 * to figure out whether the disk device is actually online or not.
10062 	 */
10063 	if (lun != NULL)
10064 		sp->device = (SID_QUAL_LU_CONNECTED << 5) |
10065 				  lun->be_lun->lun_type;
10066 	else
10067 		sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10068 
10069 	sp->page_code = SVPD_SCSI_PORTS;
10070 	scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
10071 	    sp->page_length);
10072 	pd = &sp->design[0];
10073 
10074 	mtx_lock(&softc->ctl_lock);
10075 	if (softc->flags & CTL_FLAG_MASTER_SHELF)
10076 		pg = 0;
10077 	else
10078 		pg = 1;
10079 	for (g = 0; g < num_target_port_groups; g++) {
10080 		STAILQ_FOREACH(port, &softc->port_list, links) {
10081 			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
10082 				continue;
10083 			if (ctl_map_lun_back(port->targ_port, lun->lun) >=
10084 			    CTL_MAX_LUNS)
10085 				continue;
10086 			p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
10087 			scsi_ulto2b(p, pd->relative_port_id);
10088 			if (port->init_devid && g == pg) {
10089 				iid_len = port->init_devid->len;
10090 				memcpy(pd->initiator_transportid,
10091 				    port->init_devid->data, port->init_devid->len);
10092 			} else
10093 				iid_len = 0;
10094 			scsi_ulto2b(iid_len, pd->initiator_transportid_length);
10095 			pdc = (struct scsi_vpd_port_designation_cont *)
10096 			    (&pd->initiator_transportid[iid_len]);
10097 			if (port->port_devid && g == pg) {
10098 				id_len = port->port_devid->len;
10099 				memcpy(pdc->target_port_descriptors,
10100 				    port->port_devid->data, port->port_devid->len);
10101 			} else
10102 				id_len = 0;
10103 			scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
10104 			pd = (struct scsi_vpd_port_designation *)
10105 			    ((uint8_t *)pdc->target_port_descriptors + id_len);
10106 		}
10107 	}
10108 	mtx_unlock(&softc->ctl_lock);
10109 
10110 	ctsio->scsi_status = SCSI_STATUS_OK;
10111 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10112 	ctsio->be_move_done = ctl_config_move_done;
10113 	ctl_datamove((union ctl_io *)ctsio);
10114 
10115 	return (CTL_RETVAL_COMPLETE);
10116 }
10117 
10118 static int
10119 ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
10120 {
10121 	struct scsi_vpd_block_limits *bl_ptr;
10122 	struct ctl_lun *lun;
10123 	int bs;
10124 
10125 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10126 	bs = lun->be_lun->blocksize;
10127 
10128 	ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
10129 	bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
10130 	ctsio->kern_sg_entries = 0;
10131 
10132 	if (sizeof(*bl_ptr) < alloc_len) {
10133 		ctsio->residual = alloc_len - sizeof(*bl_ptr);
10134 		ctsio->kern_data_len = sizeof(*bl_ptr);
10135 		ctsio->kern_total_len = sizeof(*bl_ptr);
10136 	} else {
10137 		ctsio->residual = 0;
10138 		ctsio->kern_data_len = alloc_len;
10139 		ctsio->kern_total_len = alloc_len;
10140 	}
10141 	ctsio->kern_data_resid = 0;
10142 	ctsio->kern_rel_offset = 0;
10143 	ctsio->kern_sg_entries = 0;
10144 
10145 	/*
10146 	 * The control device is always connected.  The disk device, on the
10147 	 * other hand, may not be online all the time.  Need to change this
10148 	 * to figure out whether the disk device is actually online or not.
10149 	 */
10150 	if (lun != NULL)
10151 		bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10152 				  lun->be_lun->lun_type;
10153 	else
10154 		bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10155 
10156 	bl_ptr->page_code = SVPD_BLOCK_LIMITS;
10157 	scsi_ulto2b(sizeof(*bl_ptr), bl_ptr->page_length);
10158 	bl_ptr->max_cmp_write_len = 0xff;
10159 	scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
10160 	scsi_ulto4b(MAXPHYS / bs, bl_ptr->opt_txfer_len);
10161 	if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10162 		scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_lba_cnt);
10163 		scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_blk_cnt);
10164 	}
10165 	scsi_u64to8b(UINT64_MAX, bl_ptr->max_write_same_length);
10166 
10167 	ctsio->scsi_status = SCSI_STATUS_OK;
10168 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10169 	ctsio->be_move_done = ctl_config_move_done;
10170 	ctl_datamove((union ctl_io *)ctsio);
10171 
10172 	return (CTL_RETVAL_COMPLETE);
10173 }
10174 
10175 static int
10176 ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
10177 {
10178 	struct scsi_vpd_logical_block_prov *lbp_ptr;
10179 	struct ctl_lun *lun;
10180 	int bs;
10181 
10182 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10183 	bs = lun->be_lun->blocksize;
10184 
10185 	ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
10186 	lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
10187 	ctsio->kern_sg_entries = 0;
10188 
10189 	if (sizeof(*lbp_ptr) < alloc_len) {
10190 		ctsio->residual = alloc_len - sizeof(*lbp_ptr);
10191 		ctsio->kern_data_len = sizeof(*lbp_ptr);
10192 		ctsio->kern_total_len = sizeof(*lbp_ptr);
10193 	} else {
10194 		ctsio->residual = 0;
10195 		ctsio->kern_data_len = alloc_len;
10196 		ctsio->kern_total_len = alloc_len;
10197 	}
10198 	ctsio->kern_data_resid = 0;
10199 	ctsio->kern_rel_offset = 0;
10200 	ctsio->kern_sg_entries = 0;
10201 
10202 	/*
10203 	 * The control device is always connected.  The disk device, on the
10204 	 * other hand, may not be online all the time.  Need to change this
10205 	 * to figure out whether the disk device is actually online or not.
10206 	 */
10207 	if (lun != NULL)
10208 		lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10209 				  lun->be_lun->lun_type;
10210 	else
10211 		lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10212 
10213 	lbp_ptr->page_code = SVPD_LBP;
10214 	if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
10215 		lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 | SVPD_LBP_WS10;
10216 
10217 	ctsio->scsi_status = SCSI_STATUS_OK;
10218 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10219 	ctsio->be_move_done = ctl_config_move_done;
10220 	ctl_datamove((union ctl_io *)ctsio);
10221 
10222 	return (CTL_RETVAL_COMPLETE);
10223 }
10224 
10225 static int
10226 ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
10227 {
10228 	struct scsi_inquiry *cdb;
10229 	struct ctl_lun *lun;
10230 	int alloc_len, retval;
10231 
10232 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10233 	cdb = (struct scsi_inquiry *)ctsio->cdb;
10234 
10235 	retval = CTL_RETVAL_COMPLETE;
10236 
10237 	alloc_len = scsi_2btoul(cdb->length);
10238 
10239 	switch (cdb->page_code) {
10240 	case SVPD_SUPPORTED_PAGES:
10241 		retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
10242 		break;
10243 	case SVPD_UNIT_SERIAL_NUMBER:
10244 		retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
10245 		break;
10246 	case SVPD_DEVICE_ID:
10247 		retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
10248 		break;
10249 	case SVPD_SCSI_PORTS:
10250 		retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10251 		break;
10252 	case SVPD_SCSI_TPC:
10253 		retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
10254 		break;
10255 	case SVPD_BLOCK_LIMITS:
10256 		retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10257 		break;
10258 	case SVPD_LBP:
10259 		retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10260 		break;
10261 	default:
10262 		ctl_set_invalid_field(ctsio,
10263 				      /*sks_valid*/ 1,
10264 				      /*command*/ 1,
10265 				      /*field*/ 2,
10266 				      /*bit_valid*/ 0,
10267 				      /*bit*/ 0);
10268 		ctl_done((union ctl_io *)ctsio);
10269 		retval = CTL_RETVAL_COMPLETE;
10270 		break;
10271 	}
10272 
10273 	return (retval);
10274 }
10275 
10276 static int
10277 ctl_inquiry_std(struct ctl_scsiio *ctsio)
10278 {
10279 	struct scsi_inquiry_data *inq_ptr;
10280 	struct scsi_inquiry *cdb;
10281 	struct ctl_softc *ctl_softc;
10282 	struct ctl_lun *lun;
10283 	char *val;
10284 	uint32_t alloc_len;
10285 	ctl_port_type port_type;
10286 
10287 	ctl_softc = control_softc;
10288 
10289 	/*
10290 	 * Figure out whether we're talking to a Fibre Channel port or not.
10291 	 * We treat the ioctl front end, and any SCSI adapters, as packetized
10292 	 * SCSI front ends.
10293 	 */
10294 	port_type = ctl_softc->ctl_ports[
10295 	    ctl_port_idx(ctsio->io_hdr.nexus.targ_port)]->port_type;
10296 	if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10297 		port_type = CTL_PORT_SCSI;
10298 
10299 	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10300 	cdb = (struct scsi_inquiry *)ctsio->cdb;
10301 	alloc_len = scsi_2btoul(cdb->length);
10302 
10303 	/*
10304 	 * We malloc the full inquiry data size here and fill it
10305 	 * in.  If the user only asks for less, we'll give him
10306 	 * that much.
10307 	 */
10308 	ctsio->kern_data_ptr = malloc(sizeof(*inq_ptr), M_CTL, M_WAITOK | M_ZERO);
10309 	inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10310 	ctsio->kern_sg_entries = 0;
10311 	ctsio->kern_data_resid = 0;
10312 	ctsio->kern_rel_offset = 0;
10313 
10314 	if (sizeof(*inq_ptr) < alloc_len) {
10315 		ctsio->residual = alloc_len - sizeof(*inq_ptr);
10316 		ctsio->kern_data_len = sizeof(*inq_ptr);
10317 		ctsio->kern_total_len = sizeof(*inq_ptr);
10318 	} else {
10319 		ctsio->residual = 0;
10320 		ctsio->kern_data_len = alloc_len;
10321 		ctsio->kern_total_len = alloc_len;
10322 	}
10323 
10324 	/*
10325 	 * If we have a LUN configured, report it as connected.  Otherwise,
10326 	 * report that it is offline or no device is supported, depending
10327 	 * on the value of inquiry_pq_no_lun.
10328 	 *
10329 	 * According to the spec (SPC-4 r34), the peripheral qualifier
10330 	 * SID_QUAL_LU_OFFLINE (001b) is used in the following scenario:
10331 	 *
10332 	 * "A peripheral device having the specified peripheral device type
10333 	 * is not connected to this logical unit. However, the device
10334 	 * server is capable of supporting the specified peripheral device
10335 	 * type on this logical unit."
10336 	 *
10337 	 * According to the same spec, the peripheral qualifier
10338 	 * SID_QUAL_BAD_LU (011b) is used in this scenario:
10339 	 *
10340 	 * "The device server is not capable of supporting a peripheral
10341 	 * device on this logical unit. For this peripheral qualifier the
10342 	 * peripheral device type shall be set to 1Fh. All other peripheral
10343 	 * device type values are reserved for this peripheral qualifier."
10344 	 *
10345 	 * Given the text, it would seem that we probably want to report that
10346 	 * the LUN is offline here.  There is no LUN connected, but we can
10347 	 * support a LUN at the given LUN number.
10348 	 *
10349 	 * In the real world, though, it sounds like things are a little
10350 	 * different:
10351 	 *
10352 	 * - Linux, when presented with a LUN with the offline peripheral
10353 	 *   qualifier, will create an sg driver instance for it.  So when
10354 	 *   you attach it to CTL, you wind up with a ton of sg driver
10355 	 *   instances.  (One for every LUN that Linux bothered to probe.)
10356 	 *   Linux does this despite the fact that it issues a REPORT LUNs
10357 	 *   to LUN 0 to get the inventory of supported LUNs.
10358 	 *
10359 	 * - There is other anecdotal evidence (from Emulex folks) about
10360 	 *   arrays that use the offline peripheral qualifier for LUNs that
10361 	 *   are on the "passive" path in an active/passive array.
10362 	 *
10363 	 * So the solution is provide a hopefully reasonable default
10364 	 * (return bad/no LUN) and allow the user to change the behavior
10365 	 * with a tunable/sysctl variable.
10366 	 */
10367 	if (lun != NULL)
10368 		inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10369 				  lun->be_lun->lun_type;
10370 	else if (ctl_softc->inquiry_pq_no_lun == 0)
10371 		inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10372 	else
10373 		inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10374 
10375 	/* RMB in byte 2 is 0 */
10376 	inq_ptr->version = SCSI_REV_SPC4;
10377 
10378 	/*
10379 	 * According to SAM-3, even if a device only supports a single
10380 	 * level of LUN addressing, it should still set the HISUP bit:
10381 	 *
10382 	 * 4.9.1 Logical unit numbers overview
10383 	 *
10384 	 * All logical unit number formats described in this standard are
10385 	 * hierarchical in structure even when only a single level in that
10386 	 * hierarchy is used. The HISUP bit shall be set to one in the
10387 	 * standard INQUIRY data (see SPC-2) when any logical unit number
10388 	 * format described in this standard is used.  Non-hierarchical
10389 	 * formats are outside the scope of this standard.
10390 	 *
10391 	 * Therefore we set the HiSup bit here.
10392 	 *
10393 	 * The reponse format is 2, per SPC-3.
10394 	 */
10395 	inq_ptr->response_format = SID_HiSup | 2;
10396 
10397 	inq_ptr->additional_length = sizeof(*inq_ptr) - 4;
10398 	CTL_DEBUG_PRINT(("additional_length = %d\n",
10399 			 inq_ptr->additional_length));
10400 
10401 	inq_ptr->spc3_flags = SPC3_SID_3PC;
10402 	if (!ctl_is_single)
10403 		inq_ptr->spc3_flags |= SPC3_SID_TPGS_IMPLICIT;
10404 	/* 16 bit addressing */
10405 	if (port_type == CTL_PORT_SCSI)
10406 		inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10407 	/* XXX set the SID_MultiP bit here if we're actually going to
10408 	   respond on multiple ports */
10409 	inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10410 
10411 	/* 16 bit data bus, synchronous transfers */
10412 	if (port_type == CTL_PORT_SCSI)
10413 		inq_ptr->flags = SID_WBus16 | SID_Sync;
10414 	/*
10415 	 * XXX KDM do we want to support tagged queueing on the control
10416 	 * device at all?
10417 	 */
10418 	if ((lun == NULL)
10419 	 || (lun->be_lun->lun_type != T_PROCESSOR))
10420 		inq_ptr->flags |= SID_CmdQue;
10421 	/*
10422 	 * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10423 	 * We have 8 bytes for the vendor name, and 16 bytes for the device
10424 	 * name and 4 bytes for the revision.
10425 	 */
10426 	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10427 	    "vendor")) == NULL) {
10428 		strcpy(inq_ptr->vendor, CTL_VENDOR);
10429 	} else {
10430 		memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10431 		strncpy(inq_ptr->vendor, val,
10432 		    min(sizeof(inq_ptr->vendor), strlen(val)));
10433 	}
10434 	if (lun == NULL) {
10435 		strcpy(inq_ptr->product, CTL_DIRECT_PRODUCT);
10436 	} else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10437 		switch (lun->be_lun->lun_type) {
10438 		case T_DIRECT:
10439 			strcpy(inq_ptr->product, CTL_DIRECT_PRODUCT);
10440 			break;
10441 		case T_PROCESSOR:
10442 			strcpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT);
10443 			break;
10444 		default:
10445 			strcpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT);
10446 			break;
10447 		}
10448 	} else {
10449 		memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10450 		strncpy(inq_ptr->product, val,
10451 		    min(sizeof(inq_ptr->product), strlen(val)));
10452 	}
10453 
10454 	/*
10455 	 * XXX make this a macro somewhere so it automatically gets
10456 	 * incremented when we make changes.
10457 	 */
10458 	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10459 	    "revision")) == NULL) {
10460 		strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10461 	} else {
10462 		memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10463 		strncpy(inq_ptr->revision, val,
10464 		    min(sizeof(inq_ptr->revision), strlen(val)));
10465 	}
10466 
10467 	/*
10468 	 * For parallel SCSI, we support double transition and single
10469 	 * transition clocking.  We also support QAS (Quick Arbitration
10470 	 * and Selection) and Information Unit transfers on both the
10471 	 * control and array devices.
10472 	 */
10473 	if (port_type == CTL_PORT_SCSI)
10474 		inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10475 				    SID_SPI_IUS;
10476 
10477 	/* SAM-5 (no version claimed) */
10478 	scsi_ulto2b(0x00A0, inq_ptr->version1);
10479 	/* SPC-4 (no version claimed) */
10480 	scsi_ulto2b(0x0460, inq_ptr->version2);
10481 	if (port_type == CTL_PORT_FC) {
10482 		/* FCP-2 ANSI INCITS.350:2003 */
10483 		scsi_ulto2b(0x0917, inq_ptr->version3);
10484 	} else if (port_type == CTL_PORT_SCSI) {
10485 		/* SPI-4 ANSI INCITS.362:200x */
10486 		scsi_ulto2b(0x0B56, inq_ptr->version3);
10487 	} else if (port_type == CTL_PORT_ISCSI) {
10488 		/* iSCSI (no version claimed) */
10489 		scsi_ulto2b(0x0960, inq_ptr->version3);
10490 	} else if (port_type == CTL_PORT_SAS) {
10491 		/* SAS (no version claimed) */
10492 		scsi_ulto2b(0x0BE0, inq_ptr->version3);
10493 	}
10494 
10495 	if (lun == NULL) {
10496 		/* SBC-3 (no version claimed) */
10497 		scsi_ulto2b(0x04C0, inq_ptr->version4);
10498 	} else {
10499 		switch (lun->be_lun->lun_type) {
10500 		case T_DIRECT:
10501 			/* SBC-3 (no version claimed) */
10502 			scsi_ulto2b(0x04C0, inq_ptr->version4);
10503 			break;
10504 		case T_PROCESSOR:
10505 		default:
10506 			break;
10507 		}
10508 	}
10509 
10510 	ctsio->scsi_status = SCSI_STATUS_OK;
10511 	if (ctsio->kern_data_len > 0) {
10512 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10513 		ctsio->be_move_done = ctl_config_move_done;
10514 		ctl_datamove((union ctl_io *)ctsio);
10515 	} else {
10516 		ctsio->io_hdr.status = CTL_SUCCESS;
10517 		ctl_done((union ctl_io *)ctsio);
10518 	}
10519 
10520 	return (CTL_RETVAL_COMPLETE);
10521 }
10522 
10523 int
10524 ctl_inquiry(struct ctl_scsiio *ctsio)
10525 {
10526 	struct scsi_inquiry *cdb;
10527 	int retval;
10528 
10529 	cdb = (struct scsi_inquiry *)ctsio->cdb;
10530 
10531 	retval = 0;
10532 
10533 	CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10534 
10535 	/*
10536 	 * Right now, we don't support the CmdDt inquiry information.
10537 	 * This would be nice to support in the future.  When we do
10538 	 * support it, we should change this test so that it checks to make
10539 	 * sure SI_EVPD and SI_CMDDT aren't both set at the same time.
10540 	 */
10541 #ifdef notyet
10542 	if (((cdb->byte2 & SI_EVPD)
10543 	 && (cdb->byte2 & SI_CMDDT)))
10544 #endif
10545 	if (cdb->byte2 & SI_CMDDT) {
10546 		/*
10547 		 * Point to the SI_CMDDT bit.  We might change this
10548 		 * when we support SI_CMDDT, but since both bits would be
10549 		 * "wrong", this should probably just stay as-is then.
10550 		 */
10551 		ctl_set_invalid_field(ctsio,
10552 				      /*sks_valid*/ 1,
10553 				      /*command*/ 1,
10554 				      /*field*/ 1,
10555 				      /*bit_valid*/ 1,
10556 				      /*bit*/ 1);
10557 		ctl_done((union ctl_io *)ctsio);
10558 		return (CTL_RETVAL_COMPLETE);
10559 	}
10560 	if (cdb->byte2 & SI_EVPD)
10561 		retval = ctl_inquiry_evpd(ctsio);
10562 #ifdef notyet
10563 	else if (cdb->byte2 & SI_CMDDT)
10564 		retval = ctl_inquiry_cmddt(ctsio);
10565 #endif
10566 	else
10567 		retval = ctl_inquiry_std(ctsio);
10568 
10569 	return (retval);
10570 }
10571 
10572 /*
10573  * For known CDB types, parse the LBA and length.
10574  */
10575 static int
10576 ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint32_t *len)
10577 {
10578 	if (io->io_hdr.io_type != CTL_IO_SCSI)
10579 		return (1);
10580 
10581 	switch (io->scsiio.cdb[0]) {
10582 	case COMPARE_AND_WRITE: {
10583 		struct scsi_compare_and_write *cdb;
10584 
10585 		cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10586 
10587 		*lba = scsi_8btou64(cdb->addr);
10588 		*len = cdb->length;
10589 		break;
10590 	}
10591 	case READ_6:
10592 	case WRITE_6: {
10593 		struct scsi_rw_6 *cdb;
10594 
10595 		cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10596 
10597 		*lba = scsi_3btoul(cdb->addr);
10598 		/* only 5 bits are valid in the most significant address byte */
10599 		*lba &= 0x1fffff;
10600 		*len = cdb->length;
10601 		break;
10602 	}
10603 	case READ_10:
10604 	case WRITE_10: {
10605 		struct scsi_rw_10 *cdb;
10606 
10607 		cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10608 
10609 		*lba = scsi_4btoul(cdb->addr);
10610 		*len = scsi_2btoul(cdb->length);
10611 		break;
10612 	}
10613 	case WRITE_VERIFY_10: {
10614 		struct scsi_write_verify_10 *cdb;
10615 
10616 		cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10617 
10618 		*lba = scsi_4btoul(cdb->addr);
10619 		*len = scsi_2btoul(cdb->length);
10620 		break;
10621 	}
10622 	case READ_12:
10623 	case WRITE_12: {
10624 		struct scsi_rw_12 *cdb;
10625 
10626 		cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10627 
10628 		*lba = scsi_4btoul(cdb->addr);
10629 		*len = scsi_4btoul(cdb->length);
10630 		break;
10631 	}
10632 	case WRITE_VERIFY_12: {
10633 		struct scsi_write_verify_12 *cdb;
10634 
10635 		cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10636 
10637 		*lba = scsi_4btoul(cdb->addr);
10638 		*len = scsi_4btoul(cdb->length);
10639 		break;
10640 	}
10641 	case READ_16:
10642 	case WRITE_16: {
10643 		struct scsi_rw_16 *cdb;
10644 
10645 		cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10646 
10647 		*lba = scsi_8btou64(cdb->addr);
10648 		*len = scsi_4btoul(cdb->length);
10649 		break;
10650 	}
10651 	case WRITE_VERIFY_16: {
10652 		struct scsi_write_verify_16 *cdb;
10653 
10654 		cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10655 
10656 
10657 		*lba = scsi_8btou64(cdb->addr);
10658 		*len = scsi_4btoul(cdb->length);
10659 		break;
10660 	}
10661 	case WRITE_SAME_10: {
10662 		struct scsi_write_same_10 *cdb;
10663 
10664 		cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10665 
10666 		*lba = scsi_4btoul(cdb->addr);
10667 		*len = scsi_2btoul(cdb->length);
10668 		break;
10669 	}
10670 	case WRITE_SAME_16: {
10671 		struct scsi_write_same_16 *cdb;
10672 
10673 		cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10674 
10675 		*lba = scsi_8btou64(cdb->addr);
10676 		*len = scsi_4btoul(cdb->length);
10677 		break;
10678 	}
10679 	case VERIFY_10: {
10680 		struct scsi_verify_10 *cdb;
10681 
10682 		cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10683 
10684 		*lba = scsi_4btoul(cdb->addr);
10685 		*len = scsi_2btoul(cdb->length);
10686 		break;
10687 	}
10688 	case VERIFY_12: {
10689 		struct scsi_verify_12 *cdb;
10690 
10691 		cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10692 
10693 		*lba = scsi_4btoul(cdb->addr);
10694 		*len = scsi_4btoul(cdb->length);
10695 		break;
10696 	}
10697 	case VERIFY_16: {
10698 		struct scsi_verify_16 *cdb;
10699 
10700 		cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10701 
10702 		*lba = scsi_8btou64(cdb->addr);
10703 		*len = scsi_4btoul(cdb->length);
10704 		break;
10705 	}
10706 	default:
10707 		return (1);
10708 		break; /* NOTREACHED */
10709 	}
10710 
10711 	return (0);
10712 }
10713 
10714 static ctl_action
10715 ctl_extent_check_lba(uint64_t lba1, uint32_t len1, uint64_t lba2, uint32_t len2)
10716 {
10717 	uint64_t endlba1, endlba2;
10718 
10719 	endlba1 = lba1 + len1 - 1;
10720 	endlba2 = lba2 + len2 - 1;
10721 
10722 	if ((endlba1 < lba2)
10723 	 || (endlba2 < lba1))
10724 		return (CTL_ACTION_PASS);
10725 	else
10726 		return (CTL_ACTION_BLOCK);
10727 }
10728 
10729 static ctl_action
10730 ctl_extent_check(union ctl_io *io1, union ctl_io *io2)
10731 {
10732 	uint64_t lba1, lba2;
10733 	uint32_t len1, len2;
10734 	int retval;
10735 
10736 	retval = ctl_get_lba_len(io1, &lba1, &len1);
10737 	if (retval != 0)
10738 		return (CTL_ACTION_ERROR);
10739 
10740 	retval = ctl_get_lba_len(io2, &lba2, &len2);
10741 	if (retval != 0)
10742 		return (CTL_ACTION_ERROR);
10743 
10744 	return (ctl_extent_check_lba(lba1, len1, lba2, len2));
10745 }
10746 
10747 static ctl_action
10748 ctl_check_for_blockage(union ctl_io *pending_io, union ctl_io *ooa_io)
10749 {
10750 	const struct ctl_cmd_entry *pending_entry, *ooa_entry;
10751 	ctl_serialize_action *serialize_row;
10752 
10753 	/*
10754 	 * The initiator attempted multiple untagged commands at the same
10755 	 * time.  Can't do that.
10756 	 */
10757 	if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10758 	 && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10759 	 && ((pending_io->io_hdr.nexus.targ_port ==
10760 	      ooa_io->io_hdr.nexus.targ_port)
10761 	  && (pending_io->io_hdr.nexus.initid.id ==
10762 	      ooa_io->io_hdr.nexus.initid.id))
10763 	 && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
10764 		return (CTL_ACTION_OVERLAP);
10765 
10766 	/*
10767 	 * The initiator attempted to send multiple tagged commands with
10768 	 * the same ID.  (It's fine if different initiators have the same
10769 	 * tag ID.)
10770 	 *
10771 	 * Even if all of those conditions are true, we don't kill the I/O
10772 	 * if the command ahead of us has been aborted.  We won't end up
10773 	 * sending it to the FETD, and it's perfectly legal to resend a
10774 	 * command with the same tag number as long as the previous
10775 	 * instance of this tag number has been aborted somehow.
10776 	 */
10777 	if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10778 	 && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10779 	 && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
10780 	 && ((pending_io->io_hdr.nexus.targ_port ==
10781 	      ooa_io->io_hdr.nexus.targ_port)
10782 	  && (pending_io->io_hdr.nexus.initid.id ==
10783 	      ooa_io->io_hdr.nexus.initid.id))
10784 	 && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
10785 		return (CTL_ACTION_OVERLAP_TAG);
10786 
10787 	/*
10788 	 * If we get a head of queue tag, SAM-3 says that we should
10789 	 * immediately execute it.
10790 	 *
10791 	 * What happens if this command would normally block for some other
10792 	 * reason?  e.g. a request sense with a head of queue tag
10793 	 * immediately after a write.  Normally that would block, but this
10794 	 * will result in its getting executed immediately...
10795 	 *
10796 	 * We currently return "pass" instead of "skip", so we'll end up
10797 	 * going through the rest of the queue to check for overlapped tags.
10798 	 *
10799 	 * XXX KDM check for other types of blockage first??
10800 	 */
10801 	if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10802 		return (CTL_ACTION_PASS);
10803 
10804 	/*
10805 	 * Ordered tags have to block until all items ahead of them
10806 	 * have completed.  If we get called with an ordered tag, we always
10807 	 * block, if something else is ahead of us in the queue.
10808 	 */
10809 	if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
10810 		return (CTL_ACTION_BLOCK);
10811 
10812 	/*
10813 	 * Simple tags get blocked until all head of queue and ordered tags
10814 	 * ahead of them have completed.  I'm lumping untagged commands in
10815 	 * with simple tags here.  XXX KDM is that the right thing to do?
10816 	 */
10817 	if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10818 	  || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
10819 	 && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10820 	  || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
10821 		return (CTL_ACTION_BLOCK);
10822 
10823 	pending_entry = ctl_get_cmd_entry(&pending_io->scsiio);
10824 	ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio);
10825 
10826 	serialize_row = ctl_serialize_table[ooa_entry->seridx];
10827 
10828 	switch (serialize_row[pending_entry->seridx]) {
10829 	case CTL_SER_BLOCK:
10830 		return (CTL_ACTION_BLOCK);
10831 		break; /* NOTREACHED */
10832 	case CTL_SER_EXTENT:
10833 		return (ctl_extent_check(pending_io, ooa_io));
10834 		break; /* NOTREACHED */
10835 	case CTL_SER_PASS:
10836 		return (CTL_ACTION_PASS);
10837 		break; /* NOTREACHED */
10838 	case CTL_SER_SKIP:
10839 		return (CTL_ACTION_SKIP);
10840 		break;
10841 	default:
10842 		panic("invalid serialization value %d",
10843 		      serialize_row[pending_entry->seridx]);
10844 		break; /* NOTREACHED */
10845 	}
10846 
10847 	return (CTL_ACTION_ERROR);
10848 }
10849 
10850 /*
10851  * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
10852  * Assumptions:
10853  * - pending_io is generally either incoming, or on the blocked queue
10854  * - starting I/O is the I/O we want to start the check with.
10855  */
10856 static ctl_action
10857 ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
10858 	      union ctl_io *starting_io)
10859 {
10860 	union ctl_io *ooa_io;
10861 	ctl_action action;
10862 
10863 	mtx_assert(&lun->lun_lock, MA_OWNED);
10864 
10865 	/*
10866 	 * Run back along the OOA queue, starting with the current
10867 	 * blocked I/O and going through every I/O before it on the
10868 	 * queue.  If starting_io is NULL, we'll just end up returning
10869 	 * CTL_ACTION_PASS.
10870 	 */
10871 	for (ooa_io = starting_io; ooa_io != NULL;
10872 	     ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
10873 	     ooa_links)){
10874 
10875 		/*
10876 		 * This routine just checks to see whether
10877 		 * cur_blocked is blocked by ooa_io, which is ahead
10878 		 * of it in the queue.  It doesn't queue/dequeue
10879 		 * cur_blocked.
10880 		 */
10881 		action = ctl_check_for_blockage(pending_io, ooa_io);
10882 		switch (action) {
10883 		case CTL_ACTION_BLOCK:
10884 		case CTL_ACTION_OVERLAP:
10885 		case CTL_ACTION_OVERLAP_TAG:
10886 		case CTL_ACTION_SKIP:
10887 		case CTL_ACTION_ERROR:
10888 			return (action);
10889 			break; /* NOTREACHED */
10890 		case CTL_ACTION_PASS:
10891 			break;
10892 		default:
10893 			panic("invalid action %d", action);
10894 			break;  /* NOTREACHED */
10895 		}
10896 	}
10897 
10898 	return (CTL_ACTION_PASS);
10899 }
10900 
10901 /*
10902  * Assumptions:
10903  * - An I/O has just completed, and has been removed from the per-LUN OOA
10904  *   queue, so some items on the blocked queue may now be unblocked.
10905  */
10906 static int
10907 ctl_check_blocked(struct ctl_lun *lun)
10908 {
10909 	union ctl_io *cur_blocked, *next_blocked;
10910 
10911 	mtx_assert(&lun->lun_lock, MA_OWNED);
10912 
10913 	/*
10914 	 * Run forward from the head of the blocked queue, checking each
10915 	 * entry against the I/Os prior to it on the OOA queue to see if
10916 	 * there is still any blockage.
10917 	 *
10918 	 * We cannot use the TAILQ_FOREACH() macro, because it can't deal
10919 	 * with our removing a variable on it while it is traversing the
10920 	 * list.
10921 	 */
10922 	for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
10923 	     cur_blocked != NULL; cur_blocked = next_blocked) {
10924 		union ctl_io *prev_ooa;
10925 		ctl_action action;
10926 
10927 		next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
10928 							  blocked_links);
10929 
10930 		prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
10931 						      ctl_ooaq, ooa_links);
10932 
10933 		/*
10934 		 * If cur_blocked happens to be the first item in the OOA
10935 		 * queue now, prev_ooa will be NULL, and the action
10936 		 * returned will just be CTL_ACTION_PASS.
10937 		 */
10938 		action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
10939 
10940 		switch (action) {
10941 		case CTL_ACTION_BLOCK:
10942 			/* Nothing to do here, still blocked */
10943 			break;
10944 		case CTL_ACTION_OVERLAP:
10945 		case CTL_ACTION_OVERLAP_TAG:
10946 			/*
10947 			 * This shouldn't happen!  In theory we've already
10948 			 * checked this command for overlap...
10949 			 */
10950 			break;
10951 		case CTL_ACTION_PASS:
10952 		case CTL_ACTION_SKIP: {
10953 			struct ctl_softc *softc;
10954 			const struct ctl_cmd_entry *entry;
10955 			uint32_t initidx;
10956 			int isc_retval;
10957 
10958 			/*
10959 			 * The skip case shouldn't happen, this transaction
10960 			 * should have never made it onto the blocked queue.
10961 			 */
10962 			/*
10963 			 * This I/O is no longer blocked, we can remove it
10964 			 * from the blocked queue.  Since this is a TAILQ
10965 			 * (doubly linked list), we can do O(1) removals
10966 			 * from any place on the list.
10967 			 */
10968 			TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
10969 				     blocked_links);
10970 			cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
10971 
10972 			if (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC){
10973 				/*
10974 				 * Need to send IO back to original side to
10975 				 * run
10976 				 */
10977 				union ctl_ha_msg msg_info;
10978 
10979 				msg_info.hdr.original_sc =
10980 					cur_blocked->io_hdr.original_sc;
10981 				msg_info.hdr.serializing_sc = cur_blocked;
10982 				msg_info.hdr.msg_type = CTL_MSG_R2R;
10983 				if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
10984 				     &msg_info, sizeof(msg_info), 0)) >
10985 				     CTL_HA_STATUS_SUCCESS) {
10986 					printf("CTL:Check Blocked error from "
10987 					       "ctl_ha_msg_send %d\n",
10988 					       isc_retval);
10989 				}
10990 				break;
10991 			}
10992 			entry = ctl_get_cmd_entry(&cur_blocked->scsiio);
10993 			softc = control_softc;
10994 
10995 			initidx = ctl_get_initindex(&cur_blocked->io_hdr.nexus);
10996 
10997 			/*
10998 			 * Check this I/O for LUN state changes that may
10999 			 * have happened while this command was blocked.
11000 			 * The LUN state may have been changed by a command
11001 			 * ahead of us in the queue, so we need to re-check
11002 			 * for any states that can be caused by SCSI
11003 			 * commands.
11004 			 */
11005 			if (ctl_scsiio_lun_check(softc, lun, entry,
11006 						 &cur_blocked->scsiio) == 0) {
11007 				cur_blocked->io_hdr.flags |=
11008 				                      CTL_FLAG_IS_WAS_ON_RTR;
11009 				ctl_enqueue_rtr(cur_blocked);
11010 			} else
11011 				ctl_done(cur_blocked);
11012 			break;
11013 		}
11014 		default:
11015 			/*
11016 			 * This probably shouldn't happen -- we shouldn't
11017 			 * get CTL_ACTION_ERROR, or anything else.
11018 			 */
11019 			break;
11020 		}
11021 	}
11022 
11023 	return (CTL_RETVAL_COMPLETE);
11024 }
11025 
11026 /*
11027  * This routine (with one exception) checks LUN flags that can be set by
11028  * commands ahead of us in the OOA queue.  These flags have to be checked
11029  * when a command initially comes in, and when we pull a command off the
11030  * blocked queue and are preparing to execute it.  The reason we have to
11031  * check these flags for commands on the blocked queue is that the LUN
11032  * state may have been changed by a command ahead of us while we're on the
11033  * blocked queue.
11034  *
11035  * Ordering is somewhat important with these checks, so please pay
11036  * careful attention to the placement of any new checks.
11037  */
11038 static int
11039 ctl_scsiio_lun_check(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
11040     const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11041 {
11042 	int retval;
11043 
11044 	retval = 0;
11045 
11046 	mtx_assert(&lun->lun_lock, MA_OWNED);
11047 
11048 	/*
11049 	 * If this shelf is a secondary shelf controller, we have to reject
11050 	 * any media access commands.
11051 	 */
11052 #if 0
11053 	/* No longer needed for HA */
11054 	if (((ctl_softc->flags & CTL_FLAG_MASTER_SHELF) == 0)
11055 	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_SECONDARY) == 0)) {
11056 		ctl_set_lun_standby(ctsio);
11057 		retval = 1;
11058 		goto bailout;
11059 	}
11060 #endif
11061 
11062 	/*
11063 	 * Check for a reservation conflict.  If this command isn't allowed
11064 	 * even on reserved LUNs, and if this initiator isn't the one who
11065 	 * reserved us, reject the command with a reservation conflict.
11066 	 */
11067 	if ((lun->flags & CTL_LUN_RESERVED)
11068 	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11069 		if ((ctsio->io_hdr.nexus.initid.id != lun->rsv_nexus.initid.id)
11070 		 || (ctsio->io_hdr.nexus.targ_port != lun->rsv_nexus.targ_port)
11071 		 || (ctsio->io_hdr.nexus.targ_target.id !=
11072 		     lun->rsv_nexus.targ_target.id)) {
11073 			ctsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
11074 			ctsio->io_hdr.status = CTL_SCSI_ERROR;
11075 			retval = 1;
11076 			goto bailout;
11077 		}
11078 	}
11079 
11080 	if ( (lun->flags & CTL_LUN_PR_RESERVED)
11081 	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV) == 0)) {
11082 		uint32_t residx;
11083 
11084 		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
11085 		/*
11086 		 * if we aren't registered or it's a res holder type
11087 		 * reservation and this isn't the res holder then set a
11088 		 * conflict.
11089 		 * NOTE: Commands which might be allowed on write exclusive
11090 		 * type reservations are checked in the particular command
11091 		 * for a conflict. Read and SSU are the only ones.
11092 		 */
11093 		if (!lun->per_res[residx].registered
11094 		 || (residx != lun->pr_res_idx && lun->res_type < 4)) {
11095 			ctsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
11096 			ctsio->io_hdr.status = CTL_SCSI_ERROR;
11097 			retval = 1;
11098 			goto bailout;
11099 		}
11100 
11101 	}
11102 
11103 	if ((lun->flags & CTL_LUN_OFFLINE)
11104 	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_OFFLINE) == 0)) {
11105 		ctl_set_lun_not_ready(ctsio);
11106 		retval = 1;
11107 		goto bailout;
11108 	}
11109 
11110 	/*
11111 	 * If the LUN is stopped, see if this particular command is allowed
11112 	 * for a stopped lun.  Otherwise, reject it with 0x04,0x02.
11113 	 */
11114 	if ((lun->flags & CTL_LUN_STOPPED)
11115 	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_STOPPED) == 0)) {
11116 		/* "Logical unit not ready, initializing cmd. required" */
11117 		ctl_set_lun_stopped(ctsio);
11118 		retval = 1;
11119 		goto bailout;
11120 	}
11121 
11122 	if ((lun->flags & CTL_LUN_INOPERABLE)
11123 	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_INOPERABLE) == 0)) {
11124 		/* "Medium format corrupted" */
11125 		ctl_set_medium_format_corrupted(ctsio);
11126 		retval = 1;
11127 		goto bailout;
11128 	}
11129 
11130 bailout:
11131 	return (retval);
11132 
11133 }
11134 
11135 static void
11136 ctl_failover_io(union ctl_io *io, int have_lock)
11137 {
11138 	ctl_set_busy(&io->scsiio);
11139 	ctl_done(io);
11140 }
11141 
11142 static void
11143 ctl_failover(void)
11144 {
11145 	struct ctl_lun *lun;
11146 	struct ctl_softc *ctl_softc;
11147 	union ctl_io *next_io, *pending_io;
11148 	union ctl_io *io;
11149 	int lun_idx;
11150 	int i;
11151 
11152 	ctl_softc = control_softc;
11153 
11154 	mtx_lock(&ctl_softc->ctl_lock);
11155 	/*
11156 	 * Remove any cmds from the other SC from the rtr queue.  These
11157 	 * will obviously only be for LUNs for which we're the primary.
11158 	 * We can't send status or get/send data for these commands.
11159 	 * Since they haven't been executed yet, we can just remove them.
11160 	 * We'll either abort them or delete them below, depending on
11161 	 * which HA mode we're in.
11162 	 */
11163 #ifdef notyet
11164 	mtx_lock(&ctl_softc->queue_lock);
11165 	for (io = (union ctl_io *)STAILQ_FIRST(&ctl_softc->rtr_queue);
11166 	     io != NULL; io = next_io) {
11167 		next_io = (union ctl_io *)STAILQ_NEXT(&io->io_hdr, links);
11168 		if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11169 			STAILQ_REMOVE(&ctl_softc->rtr_queue, &io->io_hdr,
11170 				      ctl_io_hdr, links);
11171 	}
11172 	mtx_unlock(&ctl_softc->queue_lock);
11173 #endif
11174 
11175 	for (lun_idx=0; lun_idx < ctl_softc->num_luns; lun_idx++) {
11176 		lun = ctl_softc->ctl_luns[lun_idx];
11177 		if (lun==NULL)
11178 			continue;
11179 
11180 		/*
11181 		 * Processor LUNs are primary on both sides.
11182 		 * XXX will this always be true?
11183 		 */
11184 		if (lun->be_lun->lun_type == T_PROCESSOR)
11185 			continue;
11186 
11187 		if ((lun->flags & CTL_LUN_PRIMARY_SC)
11188 		 && (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11189 			printf("FAILOVER: primary lun %d\n", lun_idx);
11190 		        /*
11191 			 * Remove all commands from the other SC. First from the
11192 			 * blocked queue then from the ooa queue. Once we have
11193 			 * removed them. Call ctl_check_blocked to see if there
11194 			 * is anything that can run.
11195 			 */
11196 			for (io = (union ctl_io *)TAILQ_FIRST(
11197 			     &lun->blocked_queue); io != NULL; io = next_io) {
11198 
11199 		        	next_io = (union ctl_io *)TAILQ_NEXT(
11200 				    &io->io_hdr, blocked_links);
11201 
11202 				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11203 					TAILQ_REMOVE(&lun->blocked_queue,
11204 						     &io->io_hdr,blocked_links);
11205 					io->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11206 					TAILQ_REMOVE(&lun->ooa_queue,
11207 						     &io->io_hdr, ooa_links);
11208 
11209 					ctl_free_io(io);
11210 				}
11211 			}
11212 
11213 			for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11214 	     		     io != NULL; io = next_io) {
11215 
11216 		        	next_io = (union ctl_io *)TAILQ_NEXT(
11217 				    &io->io_hdr, ooa_links);
11218 
11219 				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11220 
11221 					TAILQ_REMOVE(&lun->ooa_queue,
11222 						&io->io_hdr,
11223 					     	ooa_links);
11224 
11225 					ctl_free_io(io);
11226 				}
11227 			}
11228 			ctl_check_blocked(lun);
11229 		} else if ((lun->flags & CTL_LUN_PRIMARY_SC)
11230 			&& (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
11231 
11232 			printf("FAILOVER: primary lun %d\n", lun_idx);
11233 			/*
11234 			 * Abort all commands from the other SC.  We can't
11235 			 * send status back for them now.  These should get
11236 			 * cleaned up when they are completed or come out
11237 			 * for a datamove operation.
11238 			 */
11239 			for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11240 	     		     io != NULL; io = next_io) {
11241 		        	next_io = (union ctl_io *)TAILQ_NEXT(
11242 					&io->io_hdr, ooa_links);
11243 
11244 				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11245 					io->io_hdr.flags |= CTL_FLAG_ABORT;
11246 			}
11247 		} else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11248 			&& (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
11249 
11250 			printf("FAILOVER: secondary lun %d\n", lun_idx);
11251 
11252 			lun->flags |= CTL_LUN_PRIMARY_SC;
11253 
11254 			/*
11255 			 * We send all I/O that was sent to this controller
11256 			 * and redirected to the other side back with
11257 			 * busy status, and have the initiator retry it.
11258 			 * Figuring out how much data has been transferred,
11259 			 * etc. and picking up where we left off would be
11260 			 * very tricky.
11261 			 *
11262 			 * XXX KDM need to remove I/O from the blocked
11263 			 * queue as well!
11264 			 */
11265 			for (pending_io = (union ctl_io *)TAILQ_FIRST(
11266 			     &lun->ooa_queue); pending_io != NULL;
11267 			     pending_io = next_io) {
11268 
11269 				next_io =  (union ctl_io *)TAILQ_NEXT(
11270 					&pending_io->io_hdr, ooa_links);
11271 
11272 				pending_io->io_hdr.flags &=
11273 					~CTL_FLAG_SENT_2OTHER_SC;
11274 
11275 				if (pending_io->io_hdr.flags &
11276 				    CTL_FLAG_IO_ACTIVE) {
11277 					pending_io->io_hdr.flags |=
11278 						CTL_FLAG_FAILOVER;
11279 				} else {
11280 					ctl_set_busy(&pending_io->scsiio);
11281 					ctl_done(pending_io);
11282 				}
11283 			}
11284 
11285 			/*
11286 			 * Build Unit Attention
11287 			 */
11288 			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11289 				lun->pending_ua[i] |=
11290 				                     CTL_UA_ASYM_ACC_CHANGE;
11291 			}
11292 		} else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11293 			&& (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11294 			printf("FAILOVER: secondary lun %d\n", lun_idx);
11295 			/*
11296 			 * if the first io on the OOA is not on the RtR queue
11297 			 * add it.
11298 			 */
11299 			lun->flags |= CTL_LUN_PRIMARY_SC;
11300 
11301 			pending_io = (union ctl_io *)TAILQ_FIRST(
11302 			    &lun->ooa_queue);
11303 			if (pending_io==NULL) {
11304 				printf("Nothing on OOA queue\n");
11305 				continue;
11306 			}
11307 
11308 			pending_io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11309 			if ((pending_io->io_hdr.flags &
11310 			     CTL_FLAG_IS_WAS_ON_RTR) == 0) {
11311 				pending_io->io_hdr.flags |=
11312 				    CTL_FLAG_IS_WAS_ON_RTR;
11313 				ctl_enqueue_rtr(pending_io);
11314 			}
11315 #if 0
11316 			else
11317 			{
11318 				printf("Tag 0x%04x is running\n",
11319 				      pending_io->scsiio.tag_num);
11320 			}
11321 #endif
11322 
11323 			next_io = (union ctl_io *)TAILQ_NEXT(
11324 			    &pending_io->io_hdr, ooa_links);
11325 			for (pending_io=next_io; pending_io != NULL;
11326 			     pending_io = next_io) {
11327 				pending_io->io_hdr.flags &=
11328 				    ~CTL_FLAG_SENT_2OTHER_SC;
11329 				next_io = (union ctl_io *)TAILQ_NEXT(
11330 					&pending_io->io_hdr, ooa_links);
11331 				if (pending_io->io_hdr.flags &
11332 				    CTL_FLAG_IS_WAS_ON_RTR) {
11333 #if 0
11334 				        printf("Tag 0x%04x is running\n",
11335 				      		pending_io->scsiio.tag_num);
11336 #endif
11337 					continue;
11338 				}
11339 
11340 				switch (ctl_check_ooa(lun, pending_io,
11341 			            (union ctl_io *)TAILQ_PREV(
11342 				    &pending_io->io_hdr, ctl_ooaq,
11343 				    ooa_links))) {
11344 
11345 				case CTL_ACTION_BLOCK:
11346 					TAILQ_INSERT_TAIL(&lun->blocked_queue,
11347 							  &pending_io->io_hdr,
11348 							  blocked_links);
11349 					pending_io->io_hdr.flags |=
11350 					    CTL_FLAG_BLOCKED;
11351 					break;
11352 				case CTL_ACTION_PASS:
11353 				case CTL_ACTION_SKIP:
11354 					pending_io->io_hdr.flags |=
11355 					    CTL_FLAG_IS_WAS_ON_RTR;
11356 					ctl_enqueue_rtr(pending_io);
11357 					break;
11358 				case CTL_ACTION_OVERLAP:
11359 					ctl_set_overlapped_cmd(
11360 					    (struct ctl_scsiio *)pending_io);
11361 					ctl_done(pending_io);
11362 					break;
11363 				case CTL_ACTION_OVERLAP_TAG:
11364 					ctl_set_overlapped_tag(
11365 					    (struct ctl_scsiio *)pending_io,
11366 					    pending_io->scsiio.tag_num & 0xff);
11367 					ctl_done(pending_io);
11368 					break;
11369 				case CTL_ACTION_ERROR:
11370 				default:
11371 					ctl_set_internal_failure(
11372 						(struct ctl_scsiio *)pending_io,
11373 						0,  // sks_valid
11374 						0); //retry count
11375 					ctl_done(pending_io);
11376 					break;
11377 				}
11378 			}
11379 
11380 			/*
11381 			 * Build Unit Attention
11382 			 */
11383 			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11384 				lun->pending_ua[i] |=
11385 				                     CTL_UA_ASYM_ACC_CHANGE;
11386 			}
11387 		} else {
11388 			panic("Unhandled HA mode failover, LUN flags = %#x, "
11389 			      "ha_mode = #%x", lun->flags, ctl_softc->ha_mode);
11390 		}
11391 	}
11392 	ctl_pause_rtr = 0;
11393 	mtx_unlock(&ctl_softc->ctl_lock);
11394 }
11395 
11396 static int
11397 ctl_scsiio_precheck(struct ctl_softc *ctl_softc, struct ctl_scsiio *ctsio)
11398 {
11399 	struct ctl_lun *lun;
11400 	const struct ctl_cmd_entry *entry;
11401 	uint32_t initidx, targ_lun;
11402 	int retval;
11403 
11404 	retval = 0;
11405 
11406 	lun = NULL;
11407 
11408 	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11409 	if ((targ_lun < CTL_MAX_LUNS)
11410 	 && (ctl_softc->ctl_luns[targ_lun] != NULL)) {
11411 		lun = ctl_softc->ctl_luns[targ_lun];
11412 		/*
11413 		 * If the LUN is invalid, pretend that it doesn't exist.
11414 		 * It will go away as soon as all pending I/O has been
11415 		 * completed.
11416 		 */
11417 		if (lun->flags & CTL_LUN_DISABLED) {
11418 			lun = NULL;
11419 		} else {
11420 			ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
11421 			ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr =
11422 				lun->be_lun;
11423 			if (lun->be_lun->lun_type == T_PROCESSOR) {
11424 				ctsio->io_hdr.flags |= CTL_FLAG_CONTROL_DEV;
11425 			}
11426 
11427 			/*
11428 			 * Every I/O goes into the OOA queue for a
11429 			 * particular LUN, and stays there until completion.
11430 			 */
11431 			mtx_lock(&lun->lun_lock);
11432 			TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr,
11433 			    ooa_links);
11434 		}
11435 	} else {
11436 		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11437 		ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11438 	}
11439 
11440 	/* Get command entry and return error if it is unsuppotyed. */
11441 	entry = ctl_validate_command(ctsio);
11442 	if (entry == NULL) {
11443 		if (lun)
11444 			mtx_unlock(&lun->lun_lock);
11445 		return (retval);
11446 	}
11447 
11448 	ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11449 	ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11450 
11451 	/*
11452 	 * Check to see whether we can send this command to LUNs that don't
11453 	 * exist.  This should pretty much only be the case for inquiry
11454 	 * and request sense.  Further checks, below, really require having
11455 	 * a LUN, so we can't really check the command anymore.  Just put
11456 	 * it on the rtr queue.
11457 	 */
11458 	if (lun == NULL) {
11459 		if (entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) {
11460 			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11461 			ctl_enqueue_rtr((union ctl_io *)ctsio);
11462 			return (retval);
11463 		}
11464 
11465 		ctl_set_unsupported_lun(ctsio);
11466 		ctl_done((union ctl_io *)ctsio);
11467 		CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11468 		return (retval);
11469 	} else {
11470 		/*
11471 		 * Make sure we support this particular command on this LUN.
11472 		 * e.g., we don't support writes to the control LUN.
11473 		 */
11474 		if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11475 			mtx_unlock(&lun->lun_lock);
11476 			ctl_set_invalid_opcode(ctsio);
11477 			ctl_done((union ctl_io *)ctsio);
11478 			return (retval);
11479 		}
11480 	}
11481 
11482 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11483 
11484 #ifdef CTL_WITH_CA
11485 	/*
11486 	 * If we've got a request sense, it'll clear the contingent
11487 	 * allegiance condition.  Otherwise, if we have a CA condition for
11488 	 * this initiator, clear it, because it sent down a command other
11489 	 * than request sense.
11490 	 */
11491 	if ((ctsio->cdb[0] != REQUEST_SENSE)
11492 	 && (ctl_is_set(lun->have_ca, initidx)))
11493 		ctl_clear_mask(lun->have_ca, initidx);
11494 #endif
11495 
11496 	/*
11497 	 * If the command has this flag set, it handles its own unit
11498 	 * attention reporting, we shouldn't do anything.  Otherwise we
11499 	 * check for any pending unit attentions, and send them back to the
11500 	 * initiator.  We only do this when a command initially comes in,
11501 	 * not when we pull it off the blocked queue.
11502 	 *
11503 	 * According to SAM-3, section 5.3.2, the order that things get
11504 	 * presented back to the host is basically unit attentions caused
11505 	 * by some sort of reset event, busy status, reservation conflicts
11506 	 * or task set full, and finally any other status.
11507 	 *
11508 	 * One issue here is that some of the unit attentions we report
11509 	 * don't fall into the "reset" category (e.g. "reported luns data
11510 	 * has changed").  So reporting it here, before the reservation
11511 	 * check, may be technically wrong.  I guess the only thing to do
11512 	 * would be to check for and report the reset events here, and then
11513 	 * check for the other unit attention types after we check for a
11514 	 * reservation conflict.
11515 	 *
11516 	 * XXX KDM need to fix this
11517 	 */
11518 	if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11519 		ctl_ua_type ua_type;
11520 
11521 		ua_type = lun->pending_ua[initidx];
11522 		if (ua_type != CTL_UA_NONE) {
11523 			scsi_sense_data_type sense_format;
11524 
11525 			if (lun != NULL)
11526 				sense_format = (lun->flags &
11527 				    CTL_LUN_SENSE_DESC) ? SSD_TYPE_DESC :
11528 				    SSD_TYPE_FIXED;
11529 			else
11530 				sense_format = SSD_TYPE_FIXED;
11531 
11532 			ua_type = ctl_build_ua(ua_type, &ctsio->sense_data,
11533 					       sense_format);
11534 			if (ua_type != CTL_UA_NONE) {
11535 				ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11536 				ctsio->io_hdr.status = CTL_SCSI_ERROR |
11537 						       CTL_AUTOSENSE;
11538 				ctsio->sense_len = SSD_FULL_SIZE;
11539 				lun->pending_ua[initidx] &= ~ua_type;
11540 				mtx_unlock(&lun->lun_lock);
11541 				ctl_done((union ctl_io *)ctsio);
11542 				return (retval);
11543 			}
11544 		}
11545 	}
11546 
11547 
11548 	if (ctl_scsiio_lun_check(ctl_softc, lun, entry, ctsio) != 0) {
11549 		mtx_unlock(&lun->lun_lock);
11550 		ctl_done((union ctl_io *)ctsio);
11551 		return (retval);
11552 	}
11553 
11554 	/*
11555 	 * XXX CHD this is where we want to send IO to other side if
11556 	 * this LUN is secondary on this SC. We will need to make a copy
11557 	 * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11558 	 * the copy we send as FROM_OTHER.
11559 	 * We also need to stuff the address of the original IO so we can
11560 	 * find it easily. Something similar will need be done on the other
11561 	 * side so when we are done we can find the copy.
11562 	 */
11563 	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11564 		union ctl_ha_msg msg_info;
11565 		int isc_retval;
11566 
11567 		ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11568 
11569 		msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11570 		msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11571 #if 0
11572 		printf("1. ctsio %p\n", ctsio);
11573 #endif
11574 		msg_info.hdr.serializing_sc = NULL;
11575 		msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11576 		msg_info.scsi.tag_num = ctsio->tag_num;
11577 		msg_info.scsi.tag_type = ctsio->tag_type;
11578 		memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11579 
11580 		ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11581 
11582 		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11583 		    (void *)&msg_info, sizeof(msg_info), 0)) >
11584 		    CTL_HA_STATUS_SUCCESS) {
11585 			printf("CTL:precheck, ctl_ha_msg_send returned %d\n",
11586 			       isc_retval);
11587 			printf("CTL:opcode is %x\n", ctsio->cdb[0]);
11588 		} else {
11589 #if 0
11590 			printf("CTL:Precheck sent msg, opcode is %x\n",opcode);
11591 #endif
11592 		}
11593 
11594 		/*
11595 		 * XXX KDM this I/O is off the incoming queue, but hasn't
11596 		 * been inserted on any other queue.  We may need to come
11597 		 * up with a holding queue while we wait for serialization
11598 		 * so that we have an idea of what we're waiting for from
11599 		 * the other side.
11600 		 */
11601 		mtx_unlock(&lun->lun_lock);
11602 		return (retval);
11603 	}
11604 
11605 	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11606 			      (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11607 			      ctl_ooaq, ooa_links))) {
11608 	case CTL_ACTION_BLOCK:
11609 		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11610 		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11611 				  blocked_links);
11612 		mtx_unlock(&lun->lun_lock);
11613 		return (retval);
11614 	case CTL_ACTION_PASS:
11615 	case CTL_ACTION_SKIP:
11616 		ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11617 		mtx_unlock(&lun->lun_lock);
11618 		ctl_enqueue_rtr((union ctl_io *)ctsio);
11619 		break;
11620 	case CTL_ACTION_OVERLAP:
11621 		mtx_unlock(&lun->lun_lock);
11622 		ctl_set_overlapped_cmd(ctsio);
11623 		ctl_done((union ctl_io *)ctsio);
11624 		break;
11625 	case CTL_ACTION_OVERLAP_TAG:
11626 		mtx_unlock(&lun->lun_lock);
11627 		ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11628 		ctl_done((union ctl_io *)ctsio);
11629 		break;
11630 	case CTL_ACTION_ERROR:
11631 	default:
11632 		mtx_unlock(&lun->lun_lock);
11633 		ctl_set_internal_failure(ctsio,
11634 					 /*sks_valid*/ 0,
11635 					 /*retry_count*/ 0);
11636 		ctl_done((union ctl_io *)ctsio);
11637 		break;
11638 	}
11639 	return (retval);
11640 }
11641 
11642 const struct ctl_cmd_entry *
11643 ctl_get_cmd_entry(struct ctl_scsiio *ctsio)
11644 {
11645 	const struct ctl_cmd_entry *entry;
11646 	int service_action;
11647 
11648 	entry = &ctl_cmd_table[ctsio->cdb[0]];
11649 	if (entry->flags & CTL_CMD_FLAG_SA5) {
11650 		service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11651 		entry = &((const struct ctl_cmd_entry *)
11652 		    entry->execute)[service_action];
11653 	}
11654 	return (entry);
11655 }
11656 
11657 const struct ctl_cmd_entry *
11658 ctl_validate_command(struct ctl_scsiio *ctsio)
11659 {
11660 	const struct ctl_cmd_entry *entry;
11661 	int i;
11662 	uint8_t diff;
11663 
11664 	entry = ctl_get_cmd_entry(ctsio);
11665 	if (entry->execute == NULL) {
11666 		ctl_set_invalid_opcode(ctsio);
11667 		ctl_done((union ctl_io *)ctsio);
11668 		return (NULL);
11669 	}
11670 	KASSERT(entry->length > 0,
11671 	    ("Not defined length for command 0x%02x/0x%02x",
11672 	     ctsio->cdb[0], ctsio->cdb[1]));
11673 	for (i = 1; i < entry->length; i++) {
11674 		diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11675 		if (diff == 0)
11676 			continue;
11677 		ctl_set_invalid_field(ctsio,
11678 				      /*sks_valid*/ 1,
11679 				      /*command*/ 1,
11680 				      /*field*/ i,
11681 				      /*bit_valid*/ 1,
11682 				      /*bit*/ fls(diff) - 1);
11683 		ctl_done((union ctl_io *)ctsio);
11684 		return (NULL);
11685 	}
11686 	return (entry);
11687 }
11688 
11689 static int
11690 ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11691 {
11692 
11693 	switch (lun_type) {
11694 	case T_PROCESSOR:
11695 		if (((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0) &&
11696 		    ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11697 			return (0);
11698 		break;
11699 	case T_DIRECT:
11700 		if (((entry->flags & CTL_CMD_FLAG_OK_ON_SLUN) == 0) &&
11701 		    ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11702 			return (0);
11703 		break;
11704 	default:
11705 		return (0);
11706 	}
11707 	return (1);
11708 }
11709 
11710 static int
11711 ctl_scsiio(struct ctl_scsiio *ctsio)
11712 {
11713 	int retval;
11714 	const struct ctl_cmd_entry *entry;
11715 
11716 	retval = CTL_RETVAL_COMPLETE;
11717 
11718 	CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11719 
11720 	entry = ctl_get_cmd_entry(ctsio);
11721 
11722 	/*
11723 	 * If this I/O has been aborted, just send it straight to
11724 	 * ctl_done() without executing it.
11725 	 */
11726 	if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11727 		ctl_done((union ctl_io *)ctsio);
11728 		goto bailout;
11729 	}
11730 
11731 	/*
11732 	 * All the checks should have been handled by ctl_scsiio_precheck().
11733 	 * We should be clear now to just execute the I/O.
11734 	 */
11735 	retval = entry->execute(ctsio);
11736 
11737 bailout:
11738 	return (retval);
11739 }
11740 
11741 /*
11742  * Since we only implement one target right now, a bus reset simply resets
11743  * our single target.
11744  */
11745 static int
11746 ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io)
11747 {
11748 	return(ctl_target_reset(ctl_softc, io, CTL_UA_BUS_RESET));
11749 }
11750 
11751 static int
11752 ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
11753 		 ctl_ua_type ua_type)
11754 {
11755 	struct ctl_lun *lun;
11756 	int retval;
11757 
11758 	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11759 		union ctl_ha_msg msg_info;
11760 
11761 		io->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11762 		msg_info.hdr.nexus = io->io_hdr.nexus;
11763 		if (ua_type==CTL_UA_TARG_RESET)
11764 			msg_info.task.task_action = CTL_TASK_TARGET_RESET;
11765 		else
11766 			msg_info.task.task_action = CTL_TASK_BUS_RESET;
11767 		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11768 		msg_info.hdr.original_sc = NULL;
11769 		msg_info.hdr.serializing_sc = NULL;
11770 		if (CTL_HA_STATUS_SUCCESS != ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11771 		    (void *)&msg_info, sizeof(msg_info), 0)) {
11772 		}
11773 	}
11774 	retval = 0;
11775 
11776 	mtx_lock(&ctl_softc->ctl_lock);
11777 	STAILQ_FOREACH(lun, &ctl_softc->lun_list, links)
11778 		retval += ctl_lun_reset(lun, io, ua_type);
11779 	mtx_unlock(&ctl_softc->ctl_lock);
11780 
11781 	return (retval);
11782 }
11783 
11784 /*
11785  * The LUN should always be set.  The I/O is optional, and is used to
11786  * distinguish between I/Os sent by this initiator, and by other
11787  * initiators.  We set unit attention for initiators other than this one.
11788  * SAM-3 is vague on this point.  It does say that a unit attention should
11789  * be established for other initiators when a LUN is reset (see section
11790  * 5.7.3), but it doesn't specifically say that the unit attention should
11791  * be established for this particular initiator when a LUN is reset.  Here
11792  * is the relevant text, from SAM-3 rev 8:
11793  *
11794  * 5.7.2 When a SCSI initiator port aborts its own tasks
11795  *
11796  * When a SCSI initiator port causes its own task(s) to be aborted, no
11797  * notification that the task(s) have been aborted shall be returned to
11798  * the SCSI initiator port other than the completion response for the
11799  * command or task management function action that caused the task(s) to
11800  * be aborted and notification(s) associated with related effects of the
11801  * action (e.g., a reset unit attention condition).
11802  *
11803  * XXX KDM for now, we're setting unit attention for all initiators.
11804  */
11805 static int
11806 ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
11807 {
11808 	union ctl_io *xio;
11809 #if 0
11810 	uint32_t initindex;
11811 #endif
11812 	int i;
11813 
11814 	mtx_lock(&lun->lun_lock);
11815 	/*
11816 	 * Run through the OOA queue and abort each I/O.
11817 	 */
11818 #if 0
11819 	TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
11820 #endif
11821 	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11822 	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11823 		xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
11824 	}
11825 
11826 	/*
11827 	 * This version sets unit attention for every
11828 	 */
11829 #if 0
11830 	initindex = ctl_get_initindex(&io->io_hdr.nexus);
11831 	for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11832 		if (initindex == i)
11833 			continue;
11834 		lun->pending_ua[i] |= ua_type;
11835 	}
11836 #endif
11837 
11838 	/*
11839 	 * A reset (any kind, really) clears reservations established with
11840 	 * RESERVE/RELEASE.  It does not clear reservations established
11841 	 * with PERSISTENT RESERVE OUT, but we don't support that at the
11842 	 * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
11843 	 * reservations made with the RESERVE/RELEASE commands, because
11844 	 * those commands are obsolete in SPC-3.
11845 	 */
11846 	lun->flags &= ~CTL_LUN_RESERVED;
11847 
11848 	for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11849 #ifdef CTL_WITH_CA
11850 		ctl_clear_mask(lun->have_ca, i);
11851 #endif
11852 		lun->pending_ua[i] |= ua_type;
11853 	}
11854 	mtx_unlock(&lun->lun_lock);
11855 
11856 	return (0);
11857 }
11858 
11859 static int
11860 ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
11861     int other_sc)
11862 {
11863 	union ctl_io *xio;
11864 	int found;
11865 
11866 	mtx_assert(&lun->lun_lock, MA_OWNED);
11867 
11868 	/*
11869 	 * Run through the OOA queue and attempt to find the given I/O.
11870 	 * The target port, initiator ID, tag type and tag number have to
11871 	 * match the values that we got from the initiator.  If we have an
11872 	 * untagged command to abort, simply abort the first untagged command
11873 	 * we come to.  We only allow one untagged command at a time of course.
11874 	 */
11875 	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11876 	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11877 
11878 		if ((targ_port == UINT32_MAX ||
11879 		     targ_port == xio->io_hdr.nexus.targ_port) &&
11880 		    (init_id == UINT32_MAX ||
11881 		     init_id == xio->io_hdr.nexus.initid.id)) {
11882 			if (targ_port != xio->io_hdr.nexus.targ_port ||
11883 			    init_id != xio->io_hdr.nexus.initid.id)
11884 				xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
11885 			xio->io_hdr.flags |= CTL_FLAG_ABORT;
11886 			found = 1;
11887 			if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11888 				union ctl_ha_msg msg_info;
11889 
11890 				msg_info.hdr.nexus = xio->io_hdr.nexus;
11891 				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
11892 				msg_info.task.tag_num = xio->scsiio.tag_num;
11893 				msg_info.task.tag_type = xio->scsiio.tag_type;
11894 				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11895 				msg_info.hdr.original_sc = NULL;
11896 				msg_info.hdr.serializing_sc = NULL;
11897 				ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11898 				    (void *)&msg_info, sizeof(msg_info), 0);
11899 			}
11900 		}
11901 	}
11902 	return (found);
11903 }
11904 
11905 static int
11906 ctl_abort_task_set(union ctl_io *io)
11907 {
11908 	struct ctl_softc *softc = control_softc;
11909 	struct ctl_lun *lun;
11910 	uint32_t targ_lun;
11911 
11912 	/*
11913 	 * Look up the LUN.
11914 	 */
11915 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11916 	mtx_lock(&softc->ctl_lock);
11917 	if ((targ_lun < CTL_MAX_LUNS) && (softc->ctl_luns[targ_lun] != NULL))
11918 		lun = softc->ctl_luns[targ_lun];
11919 	else {
11920 		mtx_unlock(&softc->ctl_lock);
11921 		return (1);
11922 	}
11923 
11924 	mtx_lock(&lun->lun_lock);
11925 	mtx_unlock(&softc->ctl_lock);
11926 	if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
11927 		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
11928 		    io->io_hdr.nexus.initid.id,
11929 		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11930 	} else { /* CTL_TASK_CLEAR_TASK_SET */
11931 		ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
11932 		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11933 	}
11934 	mtx_unlock(&lun->lun_lock);
11935 	return (0);
11936 }
11937 
11938 static int
11939 ctl_i_t_nexus_reset(union ctl_io *io)
11940 {
11941 	struct ctl_softc *softc = control_softc;
11942 	struct ctl_lun *lun;
11943 	uint32_t initindex;
11944 
11945 	initindex = ctl_get_initindex(&io->io_hdr.nexus);
11946 	mtx_lock(&softc->ctl_lock);
11947 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
11948 		mtx_lock(&lun->lun_lock);
11949 		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
11950 		    io->io_hdr.nexus.initid.id,
11951 		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11952 #ifdef CTL_WITH_CA
11953 		ctl_clear_mask(lun->have_ca, initindex);
11954 #endif
11955 		lun->pending_ua[initindex] |= CTL_UA_I_T_NEXUS_LOSS;
11956 		mtx_unlock(&lun->lun_lock);
11957 	}
11958 	mtx_unlock(&softc->ctl_lock);
11959 	return (0);
11960 }
11961 
11962 static int
11963 ctl_abort_task(union ctl_io *io)
11964 {
11965 	union ctl_io *xio;
11966 	struct ctl_lun *lun;
11967 	struct ctl_softc *ctl_softc;
11968 #if 0
11969 	struct sbuf sb;
11970 	char printbuf[128];
11971 #endif
11972 	int found;
11973 	uint32_t targ_lun;
11974 
11975 	ctl_softc = control_softc;
11976 	found = 0;
11977 
11978 	/*
11979 	 * Look up the LUN.
11980 	 */
11981 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11982 	mtx_lock(&ctl_softc->ctl_lock);
11983 	if ((targ_lun < CTL_MAX_LUNS)
11984 	 && (ctl_softc->ctl_luns[targ_lun] != NULL))
11985 		lun = ctl_softc->ctl_luns[targ_lun];
11986 	else {
11987 		mtx_unlock(&ctl_softc->ctl_lock);
11988 		return (1);
11989 	}
11990 
11991 #if 0
11992 	printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
11993 	       lun->lun, io->taskio.tag_num, io->taskio.tag_type);
11994 #endif
11995 
11996 	mtx_lock(&lun->lun_lock);
11997 	mtx_unlock(&ctl_softc->ctl_lock);
11998 	/*
11999 	 * Run through the OOA queue and attempt to find the given I/O.
12000 	 * The target port, initiator ID, tag type and tag number have to
12001 	 * match the values that we got from the initiator.  If we have an
12002 	 * untagged command to abort, simply abort the first untagged command
12003 	 * we come to.  We only allow one untagged command at a time of course.
12004 	 */
12005 #if 0
12006 	TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
12007 #endif
12008 	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12009 	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12010 #if 0
12011 		sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
12012 
12013 		sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
12014 			    lun->lun, xio->scsiio.tag_num,
12015 			    xio->scsiio.tag_type,
12016 			    (xio->io_hdr.blocked_links.tqe_prev
12017 			    == NULL) ? "" : " BLOCKED",
12018 			    (xio->io_hdr.flags &
12019 			    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
12020 			    (xio->io_hdr.flags &
12021 			    CTL_FLAG_ABORT) ? " ABORT" : "",
12022 			    (xio->io_hdr.flags &
12023 			    CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
12024 		ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
12025 		sbuf_finish(&sb);
12026 		printf("%s\n", sbuf_data(&sb));
12027 #endif
12028 
12029 		if ((xio->io_hdr.nexus.targ_port == io->io_hdr.nexus.targ_port)
12030 		 && (xio->io_hdr.nexus.initid.id ==
12031 		     io->io_hdr.nexus.initid.id)) {
12032 			/*
12033 			 * If the abort says that the task is untagged, the
12034 			 * task in the queue must be untagged.  Otherwise,
12035 			 * we just check to see whether the tag numbers
12036 			 * match.  This is because the QLogic firmware
12037 			 * doesn't pass back the tag type in an abort
12038 			 * request.
12039 			 */
12040 #if 0
12041 			if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
12042 			  && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
12043 			 || (xio->scsiio.tag_num == io->taskio.tag_num)) {
12044 #endif
12045 			/*
12046 			 * XXX KDM we've got problems with FC, because it
12047 			 * doesn't send down a tag type with aborts.  So we
12048 			 * can only really go by the tag number...
12049 			 * This may cause problems with parallel SCSI.
12050 			 * Need to figure that out!!
12051 			 */
12052 			if (xio->scsiio.tag_num == io->taskio.tag_num) {
12053 				xio->io_hdr.flags |= CTL_FLAG_ABORT;
12054 				found = 1;
12055 				if ((io->io_hdr.flags &
12056 				     CTL_FLAG_FROM_OTHER_SC) == 0 &&
12057 				    !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12058 					union ctl_ha_msg msg_info;
12059 
12060 					io->io_hdr.flags |=
12061 					                CTL_FLAG_SENT_2OTHER_SC;
12062 					msg_info.hdr.nexus = io->io_hdr.nexus;
12063 					msg_info.task.task_action =
12064 						CTL_TASK_ABORT_TASK;
12065 					msg_info.task.tag_num =
12066 						io->taskio.tag_num;
12067 					msg_info.task.tag_type =
12068 						io->taskio.tag_type;
12069 					msg_info.hdr.msg_type =
12070 						CTL_MSG_MANAGE_TASKS;
12071 					msg_info.hdr.original_sc = NULL;
12072 					msg_info.hdr.serializing_sc = NULL;
12073 #if 0
12074 					printf("Sent Abort to other side\n");
12075 #endif
12076 					if (CTL_HA_STATUS_SUCCESS !=
12077 					        ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12078 		    				(void *)&msg_info,
12079 						sizeof(msg_info), 0)) {
12080 					}
12081 				}
12082 #if 0
12083 				printf("ctl_abort_task: found I/O to abort\n");
12084 #endif
12085 				break;
12086 			}
12087 		}
12088 	}
12089 	mtx_unlock(&lun->lun_lock);
12090 
12091 	if (found == 0) {
12092 		/*
12093 		 * This isn't really an error.  It's entirely possible for
12094 		 * the abort and command completion to cross on the wire.
12095 		 * This is more of an informative/diagnostic error.
12096 		 */
12097 #if 0
12098 		printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
12099 		       "%d:%d:%d:%d tag %d type %d\n",
12100 		       io->io_hdr.nexus.initid.id,
12101 		       io->io_hdr.nexus.targ_port,
12102 		       io->io_hdr.nexus.targ_target.id,
12103 		       io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
12104 		       io->taskio.tag_type);
12105 #endif
12106 	}
12107 	return (0);
12108 }
12109 
12110 static void
12111 ctl_run_task(union ctl_io *io)
12112 {
12113 	struct ctl_softc *ctl_softc = control_softc;
12114 	int retval = 1;
12115 	const char *task_desc;
12116 
12117 	CTL_DEBUG_PRINT(("ctl_run_task\n"));
12118 
12119 	KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12120 	    ("ctl_run_task: Unextected io_type %d\n",
12121 	     io->io_hdr.io_type));
12122 
12123 	task_desc = ctl_scsi_task_string(&io->taskio);
12124 	if (task_desc != NULL) {
12125 #ifdef NEEDTOPORT
12126 		csevent_log(CSC_CTL | CSC_SHELF_SW |
12127 			    CTL_TASK_REPORT,
12128 			    csevent_LogType_Trace,
12129 			    csevent_Severity_Information,
12130 			    csevent_AlertLevel_Green,
12131 			    csevent_FRU_Firmware,
12132 			    csevent_FRU_Unknown,
12133 			    "CTL: received task: %s",task_desc);
12134 #endif
12135 	} else {
12136 #ifdef NEEDTOPORT
12137 		csevent_log(CSC_CTL | CSC_SHELF_SW |
12138 			    CTL_TASK_REPORT,
12139 			    csevent_LogType_Trace,
12140 			    csevent_Severity_Information,
12141 			    csevent_AlertLevel_Green,
12142 			    csevent_FRU_Firmware,
12143 			    csevent_FRU_Unknown,
12144 			    "CTL: received unknown task "
12145 			    "type: %d (%#x)",
12146 			    io->taskio.task_action,
12147 			    io->taskio.task_action);
12148 #endif
12149 	}
12150 	switch (io->taskio.task_action) {
12151 	case CTL_TASK_ABORT_TASK:
12152 		retval = ctl_abort_task(io);
12153 		break;
12154 	case CTL_TASK_ABORT_TASK_SET:
12155 	case CTL_TASK_CLEAR_TASK_SET:
12156 		retval = ctl_abort_task_set(io);
12157 		break;
12158 	case CTL_TASK_CLEAR_ACA:
12159 		break;
12160 	case CTL_TASK_I_T_NEXUS_RESET:
12161 		retval = ctl_i_t_nexus_reset(io);
12162 		break;
12163 	case CTL_TASK_LUN_RESET: {
12164 		struct ctl_lun *lun;
12165 		uint32_t targ_lun;
12166 
12167 		targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12168 		mtx_lock(&ctl_softc->ctl_lock);
12169 		if ((targ_lun < CTL_MAX_LUNS)
12170 		 && (ctl_softc->ctl_luns[targ_lun] != NULL))
12171 			lun = ctl_softc->ctl_luns[targ_lun];
12172 		else {
12173 			mtx_unlock(&ctl_softc->ctl_lock);
12174 			retval = 1;
12175 			break;
12176 		}
12177 
12178 		if (!(io->io_hdr.flags &
12179 		    CTL_FLAG_FROM_OTHER_SC)) {
12180 			union ctl_ha_msg msg_info;
12181 
12182 			io->io_hdr.flags |=
12183 				CTL_FLAG_SENT_2OTHER_SC;
12184 			msg_info.hdr.msg_type =
12185 				CTL_MSG_MANAGE_TASKS;
12186 			msg_info.hdr.nexus = io->io_hdr.nexus;
12187 			msg_info.task.task_action =
12188 				CTL_TASK_LUN_RESET;
12189 			msg_info.hdr.original_sc = NULL;
12190 			msg_info.hdr.serializing_sc = NULL;
12191 			if (CTL_HA_STATUS_SUCCESS !=
12192 			    ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12193 			    (void *)&msg_info,
12194 			    sizeof(msg_info), 0)) {
12195 			}
12196 		}
12197 
12198 		retval = ctl_lun_reset(lun, io,
12199 				       CTL_UA_LUN_RESET);
12200 		mtx_unlock(&ctl_softc->ctl_lock);
12201 		break;
12202 	}
12203 	case CTL_TASK_TARGET_RESET:
12204 		retval = ctl_target_reset(ctl_softc, io, CTL_UA_TARG_RESET);
12205 		break;
12206 	case CTL_TASK_BUS_RESET:
12207 		retval = ctl_bus_reset(ctl_softc, io);
12208 		break;
12209 	case CTL_TASK_PORT_LOGIN:
12210 		break;
12211 	case CTL_TASK_PORT_LOGOUT:
12212 		break;
12213 	default:
12214 		printf("ctl_run_task: got unknown task management event %d\n",
12215 		       io->taskio.task_action);
12216 		break;
12217 	}
12218 	if (retval == 0)
12219 		io->io_hdr.status = CTL_SUCCESS;
12220 	else
12221 		io->io_hdr.status = CTL_ERROR;
12222 	ctl_done(io);
12223 }
12224 
12225 /*
12226  * For HA operation.  Handle commands that come in from the other
12227  * controller.
12228  */
12229 static void
12230 ctl_handle_isc(union ctl_io *io)
12231 {
12232 	int free_io;
12233 	struct ctl_lun *lun;
12234 	struct ctl_softc *ctl_softc;
12235 	uint32_t targ_lun;
12236 
12237 	ctl_softc = control_softc;
12238 
12239 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12240 	lun = ctl_softc->ctl_luns[targ_lun];
12241 
12242 	switch (io->io_hdr.msg_type) {
12243 	case CTL_MSG_SERIALIZE:
12244 		free_io = ctl_serialize_other_sc_cmd(&io->scsiio);
12245 		break;
12246 	case CTL_MSG_R2R: {
12247 		const struct ctl_cmd_entry *entry;
12248 
12249 		/*
12250 		 * This is only used in SER_ONLY mode.
12251 		 */
12252 		free_io = 0;
12253 		entry = ctl_get_cmd_entry(&io->scsiio);
12254 		mtx_lock(&lun->lun_lock);
12255 		if (ctl_scsiio_lun_check(ctl_softc, lun,
12256 		    entry, (struct ctl_scsiio *)io) != 0) {
12257 			mtx_unlock(&lun->lun_lock);
12258 			ctl_done(io);
12259 			break;
12260 		}
12261 		io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12262 		mtx_unlock(&lun->lun_lock);
12263 		ctl_enqueue_rtr(io);
12264 		break;
12265 	}
12266 	case CTL_MSG_FINISH_IO:
12267 		if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
12268 			free_io = 0;
12269 			ctl_done(io);
12270 		} else {
12271 			free_io = 1;
12272 			mtx_lock(&lun->lun_lock);
12273 			TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr,
12274 				     ooa_links);
12275 			ctl_check_blocked(lun);
12276 			mtx_unlock(&lun->lun_lock);
12277 		}
12278 		break;
12279 	case CTL_MSG_PERS_ACTION:
12280 		ctl_hndl_per_res_out_on_other_sc(
12281 			(union ctl_ha_msg *)&io->presio.pr_msg);
12282 		free_io = 1;
12283 		break;
12284 	case CTL_MSG_BAD_JUJU:
12285 		free_io = 0;
12286 		ctl_done(io);
12287 		break;
12288 	case CTL_MSG_DATAMOVE:
12289 		/* Only used in XFER mode */
12290 		free_io = 0;
12291 		ctl_datamove_remote(io);
12292 		break;
12293 	case CTL_MSG_DATAMOVE_DONE:
12294 		/* Only used in XFER mode */
12295 		free_io = 0;
12296 		io->scsiio.be_move_done(io);
12297 		break;
12298 	default:
12299 		free_io = 1;
12300 		printf("%s: Invalid message type %d\n",
12301 		       __func__, io->io_hdr.msg_type);
12302 		break;
12303 	}
12304 	if (free_io)
12305 		ctl_free_io(io);
12306 
12307 }
12308 
12309 
12310 /*
12311  * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12312  * there is no match.
12313  */
12314 static ctl_lun_error_pattern
12315 ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12316 {
12317 	const struct ctl_cmd_entry *entry;
12318 	ctl_lun_error_pattern filtered_pattern, pattern;
12319 
12320 	pattern = desc->error_pattern;
12321 
12322 	/*
12323 	 * XXX KDM we need more data passed into this function to match a
12324 	 * custom pattern, and we actually need to implement custom pattern
12325 	 * matching.
12326 	 */
12327 	if (pattern & CTL_LUN_PAT_CMD)
12328 		return (CTL_LUN_PAT_CMD);
12329 
12330 	if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12331 		return (CTL_LUN_PAT_ANY);
12332 
12333 	entry = ctl_get_cmd_entry(ctsio);
12334 
12335 	filtered_pattern = entry->pattern & pattern;
12336 
12337 	/*
12338 	 * If the user requested specific flags in the pattern (e.g.
12339 	 * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12340 	 * flags.
12341 	 *
12342 	 * If the user did not specify any flags, it doesn't matter whether
12343 	 * or not the command supports the flags.
12344 	 */
12345 	if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12346 	     (pattern & ~CTL_LUN_PAT_MASK))
12347 		return (CTL_LUN_PAT_NONE);
12348 
12349 	/*
12350 	 * If the user asked for a range check, see if the requested LBA
12351 	 * range overlaps with this command's LBA range.
12352 	 */
12353 	if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12354 		uint64_t lba1;
12355 		uint32_t len1;
12356 		ctl_action action;
12357 		int retval;
12358 
12359 		retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12360 		if (retval != 0)
12361 			return (CTL_LUN_PAT_NONE);
12362 
12363 		action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12364 					      desc->lba_range.len);
12365 		/*
12366 		 * A "pass" means that the LBA ranges don't overlap, so
12367 		 * this doesn't match the user's range criteria.
12368 		 */
12369 		if (action == CTL_ACTION_PASS)
12370 			return (CTL_LUN_PAT_NONE);
12371 	}
12372 
12373 	return (filtered_pattern);
12374 }
12375 
12376 static void
12377 ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12378 {
12379 	struct ctl_error_desc *desc, *desc2;
12380 
12381 	mtx_assert(&lun->lun_lock, MA_OWNED);
12382 
12383 	STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12384 		ctl_lun_error_pattern pattern;
12385 		/*
12386 		 * Check to see whether this particular command matches
12387 		 * the pattern in the descriptor.
12388 		 */
12389 		pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12390 		if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12391 			continue;
12392 
12393 		switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12394 		case CTL_LUN_INJ_ABORTED:
12395 			ctl_set_aborted(&io->scsiio);
12396 			break;
12397 		case CTL_LUN_INJ_MEDIUM_ERR:
12398 			ctl_set_medium_error(&io->scsiio);
12399 			break;
12400 		case CTL_LUN_INJ_UA:
12401 			/* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12402 			 * OCCURRED */
12403 			ctl_set_ua(&io->scsiio, 0x29, 0x00);
12404 			break;
12405 		case CTL_LUN_INJ_CUSTOM:
12406 			/*
12407 			 * We're assuming the user knows what he is doing.
12408 			 * Just copy the sense information without doing
12409 			 * checks.
12410 			 */
12411 			bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12412 			      ctl_min(sizeof(desc->custom_sense),
12413 				      sizeof(io->scsiio.sense_data)));
12414 			io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12415 			io->scsiio.sense_len = SSD_FULL_SIZE;
12416 			io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12417 			break;
12418 		case CTL_LUN_INJ_NONE:
12419 		default:
12420 			/*
12421 			 * If this is an error injection type we don't know
12422 			 * about, clear the continuous flag (if it is set)
12423 			 * so it will get deleted below.
12424 			 */
12425 			desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12426 			break;
12427 		}
12428 		/*
12429 		 * By default, each error injection action is a one-shot
12430 		 */
12431 		if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12432 			continue;
12433 
12434 		STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12435 
12436 		free(desc, M_CTL);
12437 	}
12438 }
12439 
12440 #ifdef CTL_IO_DELAY
12441 static void
12442 ctl_datamove_timer_wakeup(void *arg)
12443 {
12444 	union ctl_io *io;
12445 
12446 	io = (union ctl_io *)arg;
12447 
12448 	ctl_datamove(io);
12449 }
12450 #endif /* CTL_IO_DELAY */
12451 
12452 void
12453 ctl_datamove(union ctl_io *io)
12454 {
12455 	void (*fe_datamove)(union ctl_io *io);
12456 
12457 	mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12458 
12459 	CTL_DEBUG_PRINT(("ctl_datamove\n"));
12460 
12461 #ifdef CTL_TIME_IO
12462 	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12463 		char str[256];
12464 		char path_str[64];
12465 		struct sbuf sb;
12466 
12467 		ctl_scsi_path_string(io, path_str, sizeof(path_str));
12468 		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12469 
12470 		sbuf_cat(&sb, path_str);
12471 		switch (io->io_hdr.io_type) {
12472 		case CTL_IO_SCSI:
12473 			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12474 			sbuf_printf(&sb, "\n");
12475 			sbuf_cat(&sb, path_str);
12476 			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12477 				    io->scsiio.tag_num, io->scsiio.tag_type);
12478 			break;
12479 		case CTL_IO_TASK:
12480 			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12481 				    "Tag Type: %d\n", io->taskio.task_action,
12482 				    io->taskio.tag_num, io->taskio.tag_type);
12483 			break;
12484 		default:
12485 			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12486 			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12487 			break;
12488 		}
12489 		sbuf_cat(&sb, path_str);
12490 		sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12491 			    (intmax_t)time_uptime - io->io_hdr.start_time);
12492 		sbuf_finish(&sb);
12493 		printf("%s", sbuf_data(&sb));
12494 	}
12495 #endif /* CTL_TIME_IO */
12496 
12497 #ifdef CTL_IO_DELAY
12498 	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12499 		struct ctl_lun *lun;
12500 
12501 		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12502 
12503 		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12504 	} else {
12505 		struct ctl_lun *lun;
12506 
12507 		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12508 		if ((lun != NULL)
12509 		 && (lun->delay_info.datamove_delay > 0)) {
12510 			struct callout *callout;
12511 
12512 			callout = (struct callout *)&io->io_hdr.timer_bytes;
12513 			callout_init(callout, /*mpsafe*/ 1);
12514 			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12515 			callout_reset(callout,
12516 				      lun->delay_info.datamove_delay * hz,
12517 				      ctl_datamove_timer_wakeup, io);
12518 			if (lun->delay_info.datamove_type ==
12519 			    CTL_DELAY_TYPE_ONESHOT)
12520 				lun->delay_info.datamove_delay = 0;
12521 			return;
12522 		}
12523 	}
12524 #endif
12525 
12526 	/*
12527 	 * This command has been aborted.  Set the port status, so we fail
12528 	 * the data move.
12529 	 */
12530 	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12531 		printf("ctl_datamove: tag 0x%04x on (%ju:%d:%ju:%d) aborted\n",
12532 		       io->scsiio.tag_num,(uintmax_t)io->io_hdr.nexus.initid.id,
12533 		       io->io_hdr.nexus.targ_port,
12534 		       (uintmax_t)io->io_hdr.nexus.targ_target.id,
12535 		       io->io_hdr.nexus.targ_lun);
12536 		io->io_hdr.port_status = 31337;
12537 		/*
12538 		 * Note that the backend, in this case, will get the
12539 		 * callback in its context.  In other cases it may get
12540 		 * called in the frontend's interrupt thread context.
12541 		 */
12542 		io->scsiio.be_move_done(io);
12543 		return;
12544 	}
12545 
12546 	/*
12547 	 * If we're in XFER mode and this I/O is from the other shelf
12548 	 * controller, we need to send the DMA to the other side to
12549 	 * actually transfer the data to/from the host.  In serialize only
12550 	 * mode the transfer happens below CTL and ctl_datamove() is only
12551 	 * called on the machine that originally received the I/O.
12552 	 */
12553 	if ((control_softc->ha_mode == CTL_HA_MODE_XFER)
12554 	 && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12555 		union ctl_ha_msg msg;
12556 		uint32_t sg_entries_sent;
12557 		int do_sg_copy;
12558 		int i;
12559 
12560 		memset(&msg, 0, sizeof(msg));
12561 		msg.hdr.msg_type = CTL_MSG_DATAMOVE;
12562 		msg.hdr.original_sc = io->io_hdr.original_sc;
12563 		msg.hdr.serializing_sc = io;
12564 		msg.hdr.nexus = io->io_hdr.nexus;
12565 		msg.dt.flags = io->io_hdr.flags;
12566 		/*
12567 		 * We convert everything into a S/G list here.  We can't
12568 		 * pass by reference, only by value between controllers.
12569 		 * So we can't pass a pointer to the S/G list, only as many
12570 		 * S/G entries as we can fit in here.  If it's possible for
12571 		 * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
12572 		 * then we need to break this up into multiple transfers.
12573 		 */
12574 		if (io->scsiio.kern_sg_entries == 0) {
12575 			msg.dt.kern_sg_entries = 1;
12576 			/*
12577 			 * If this is in cached memory, flush the cache
12578 			 * before we send the DMA request to the other
12579 			 * controller.  We want to do this in either the
12580 			 * read or the write case.  The read case is
12581 			 * straightforward.  In the write case, we want to
12582 			 * make sure nothing is in the local cache that
12583 			 * could overwrite the DMAed data.
12584 			 */
12585 			if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12586 				/*
12587 				 * XXX KDM use bus_dmamap_sync() here.
12588 				 */
12589 			}
12590 
12591 			/*
12592 			 * Convert to a physical address if this is a
12593 			 * virtual address.
12594 			 */
12595 			if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
12596 				msg.dt.sg_list[0].addr =
12597 					io->scsiio.kern_data_ptr;
12598 			} else {
12599 				/*
12600 				 * XXX KDM use busdma here!
12601 				 */
12602 #if 0
12603 				msg.dt.sg_list[0].addr = (void *)
12604 					vtophys(io->scsiio.kern_data_ptr);
12605 #endif
12606 			}
12607 
12608 			msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
12609 			do_sg_copy = 0;
12610 		} else {
12611 			struct ctl_sg_entry *sgl;
12612 
12613 			do_sg_copy = 1;
12614 			msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
12615 			sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
12616 			if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12617 				/*
12618 				 * XXX KDM use bus_dmamap_sync() here.
12619 				 */
12620 			}
12621 		}
12622 
12623 		msg.dt.kern_data_len = io->scsiio.kern_data_len;
12624 		msg.dt.kern_total_len = io->scsiio.kern_total_len;
12625 		msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
12626 		msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
12627 		msg.dt.sg_sequence = 0;
12628 
12629 		/*
12630 		 * Loop until we've sent all of the S/G entries.  On the
12631 		 * other end, we'll recompose these S/G entries into one
12632 		 * contiguous list before passing it to the
12633 		 */
12634 		for (sg_entries_sent = 0; sg_entries_sent <
12635 		     msg.dt.kern_sg_entries; msg.dt.sg_sequence++) {
12636 			msg.dt.cur_sg_entries = ctl_min((sizeof(msg.dt.sg_list)/
12637 				sizeof(msg.dt.sg_list[0])),
12638 				msg.dt.kern_sg_entries - sg_entries_sent);
12639 
12640 			if (do_sg_copy != 0) {
12641 				struct ctl_sg_entry *sgl;
12642 				int j;
12643 
12644 				sgl = (struct ctl_sg_entry *)
12645 					io->scsiio.kern_data_ptr;
12646 				/*
12647 				 * If this is in cached memory, flush the cache
12648 				 * before we send the DMA request to the other
12649 				 * controller.  We want to do this in either
12650 				 * the * read or the write case.  The read
12651 				 * case is straightforward.  In the write
12652 				 * case, we want to make sure nothing is
12653 				 * in the local cache that could overwrite
12654 				 * the DMAed data.
12655 				 */
12656 
12657 				for (i = sg_entries_sent, j = 0;
12658 				     i < msg.dt.cur_sg_entries; i++, j++) {
12659 					if ((io->io_hdr.flags &
12660 					     CTL_FLAG_NO_DATASYNC) == 0) {
12661 						/*
12662 						 * XXX KDM use bus_dmamap_sync()
12663 						 */
12664 					}
12665 					if ((io->io_hdr.flags &
12666 					     CTL_FLAG_BUS_ADDR) == 0) {
12667 						/*
12668 						 * XXX KDM use busdma.
12669 						 */
12670 #if 0
12671 						msg.dt.sg_list[j].addr =(void *)
12672 						       vtophys(sgl[i].addr);
12673 #endif
12674 					} else {
12675 						msg.dt.sg_list[j].addr =
12676 							sgl[i].addr;
12677 					}
12678 					msg.dt.sg_list[j].len = sgl[i].len;
12679 				}
12680 			}
12681 
12682 			sg_entries_sent += msg.dt.cur_sg_entries;
12683 			if (sg_entries_sent >= msg.dt.kern_sg_entries)
12684 				msg.dt.sg_last = 1;
12685 			else
12686 				msg.dt.sg_last = 0;
12687 
12688 			/*
12689 			 * XXX KDM drop and reacquire the lock here?
12690 			 */
12691 			if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12692 			    sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
12693 				/*
12694 				 * XXX do something here.
12695 				 */
12696 			}
12697 
12698 			msg.dt.sent_sg_entries = sg_entries_sent;
12699 		}
12700 		io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12701 		if (io->io_hdr.flags & CTL_FLAG_FAILOVER)
12702 			ctl_failover_io(io, /*have_lock*/ 0);
12703 
12704 	} else {
12705 
12706 		/*
12707 		 * Lookup the fe_datamove() function for this particular
12708 		 * front end.
12709 		 */
12710 		fe_datamove =
12711 		    control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12712 
12713 		fe_datamove(io);
12714 	}
12715 }
12716 
12717 static void
12718 ctl_send_datamove_done(union ctl_io *io, int have_lock)
12719 {
12720 	union ctl_ha_msg msg;
12721 	int isc_status;
12722 
12723 	memset(&msg, 0, sizeof(msg));
12724 
12725 	msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12726 	msg.hdr.original_sc = io;
12727 	msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12728 	msg.hdr.nexus = io->io_hdr.nexus;
12729 	msg.hdr.status = io->io_hdr.status;
12730 	msg.scsi.tag_num = io->scsiio.tag_num;
12731 	msg.scsi.tag_type = io->scsiio.tag_type;
12732 	msg.scsi.scsi_status = io->scsiio.scsi_status;
12733 	memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12734 	       sizeof(io->scsiio.sense_data));
12735 	msg.scsi.sense_len = io->scsiio.sense_len;
12736 	msg.scsi.sense_residual = io->scsiio.sense_residual;
12737 	msg.scsi.fetd_status = io->io_hdr.port_status;
12738 	msg.scsi.residual = io->scsiio.residual;
12739 	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12740 
12741 	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12742 		ctl_failover_io(io, /*have_lock*/ have_lock);
12743 		return;
12744 	}
12745 
12746 	isc_status = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0);
12747 	if (isc_status > CTL_HA_STATUS_SUCCESS) {
12748 		/* XXX do something if this fails */
12749 	}
12750 
12751 }
12752 
12753 /*
12754  * The DMA to the remote side is done, now we need to tell the other side
12755  * we're done so it can continue with its data movement.
12756  */
12757 static void
12758 ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12759 {
12760 	union ctl_io *io;
12761 
12762 	io = rq->context;
12763 
12764 	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12765 		printf("%s: ISC DMA write failed with error %d", __func__,
12766 		       rq->ret);
12767 		ctl_set_internal_failure(&io->scsiio,
12768 					 /*sks_valid*/ 1,
12769 					 /*retry_count*/ rq->ret);
12770 	}
12771 
12772 	ctl_dt_req_free(rq);
12773 
12774 	/*
12775 	 * In this case, we had to malloc the memory locally.  Free it.
12776 	 */
12777 	if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
12778 		int i;
12779 		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12780 			free(io->io_hdr.local_sglist[i].addr, M_CTL);
12781 	}
12782 	/*
12783 	 * The data is in local and remote memory, so now we need to send
12784 	 * status (good or back) back to the other side.
12785 	 */
12786 	ctl_send_datamove_done(io, /*have_lock*/ 0);
12787 }
12788 
12789 /*
12790  * We've moved the data from the host/controller into local memory.  Now we
12791  * need to push it over to the remote controller's memory.
12792  */
12793 static int
12794 ctl_datamove_remote_dm_write_cb(union ctl_io *io)
12795 {
12796 	int retval;
12797 
12798 	retval = 0;
12799 
12800 	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
12801 					  ctl_datamove_remote_write_cb);
12802 
12803 	return (retval);
12804 }
12805 
12806 static void
12807 ctl_datamove_remote_write(union ctl_io *io)
12808 {
12809 	int retval;
12810 	void (*fe_datamove)(union ctl_io *io);
12811 
12812 	/*
12813 	 * - Get the data from the host/HBA into local memory.
12814 	 * - DMA memory from the local controller to the remote controller.
12815 	 * - Send status back to the remote controller.
12816 	 */
12817 
12818 	retval = ctl_datamove_remote_sgl_setup(io);
12819 	if (retval != 0)
12820 		return;
12821 
12822 	/* Switch the pointer over so the FETD knows what to do */
12823 	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12824 
12825 	/*
12826 	 * Use a custom move done callback, since we need to send completion
12827 	 * back to the other controller, not to the backend on this side.
12828 	 */
12829 	io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
12830 
12831 	fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12832 
12833 	fe_datamove(io);
12834 
12835 	return;
12836 
12837 }
12838 
12839 static int
12840 ctl_datamove_remote_dm_read_cb(union ctl_io *io)
12841 {
12842 #if 0
12843 	char str[256];
12844 	char path_str[64];
12845 	struct sbuf sb;
12846 #endif
12847 
12848 	/*
12849 	 * In this case, we had to malloc the memory locally.  Free it.
12850 	 */
12851 	if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
12852 		int i;
12853 		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12854 			free(io->io_hdr.local_sglist[i].addr, M_CTL);
12855 	}
12856 
12857 #if 0
12858 	scsi_path_string(io, path_str, sizeof(path_str));
12859 	sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12860 	sbuf_cat(&sb, path_str);
12861 	scsi_command_string(&io->scsiio, NULL, &sb);
12862 	sbuf_printf(&sb, "\n");
12863 	sbuf_cat(&sb, path_str);
12864 	sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12865 		    io->scsiio.tag_num, io->scsiio.tag_type);
12866 	sbuf_cat(&sb, path_str);
12867 	sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
12868 		    io->io_hdr.flags, io->io_hdr.status);
12869 	sbuf_finish(&sb);
12870 	printk("%s", sbuf_data(&sb));
12871 #endif
12872 
12873 
12874 	/*
12875 	 * The read is done, now we need to send status (good or bad) back
12876 	 * to the other side.
12877 	 */
12878 	ctl_send_datamove_done(io, /*have_lock*/ 0);
12879 
12880 	return (0);
12881 }
12882 
12883 static void
12884 ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
12885 {
12886 	union ctl_io *io;
12887 	void (*fe_datamove)(union ctl_io *io);
12888 
12889 	io = rq->context;
12890 
12891 	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12892 		printf("%s: ISC DMA read failed with error %d", __func__,
12893 		       rq->ret);
12894 		ctl_set_internal_failure(&io->scsiio,
12895 					 /*sks_valid*/ 1,
12896 					 /*retry_count*/ rq->ret);
12897 	}
12898 
12899 	ctl_dt_req_free(rq);
12900 
12901 	/* Switch the pointer over so the FETD knows what to do */
12902 	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12903 
12904 	/*
12905 	 * Use a custom move done callback, since we need to send completion
12906 	 * back to the other controller, not to the backend on this side.
12907 	 */
12908 	io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
12909 
12910 	/* XXX KDM add checks like the ones in ctl_datamove? */
12911 
12912 	fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12913 
12914 	fe_datamove(io);
12915 }
12916 
12917 static int
12918 ctl_datamove_remote_sgl_setup(union ctl_io *io)
12919 {
12920 	struct ctl_sg_entry *local_sglist, *remote_sglist;
12921 	struct ctl_sg_entry *local_dma_sglist, *remote_dma_sglist;
12922 	struct ctl_softc *softc;
12923 	int retval;
12924 	int i;
12925 
12926 	retval = 0;
12927 	softc = control_softc;
12928 
12929 	local_sglist = io->io_hdr.local_sglist;
12930 	local_dma_sglist = io->io_hdr.local_dma_sglist;
12931 	remote_sglist = io->io_hdr.remote_sglist;
12932 	remote_dma_sglist = io->io_hdr.remote_dma_sglist;
12933 
12934 	if (io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) {
12935 		for (i = 0; i < io->scsiio.kern_sg_entries; i++) {
12936 			local_sglist[i].len = remote_sglist[i].len;
12937 
12938 			/*
12939 			 * XXX Detect the situation where the RS-level I/O
12940 			 * redirector on the other side has already read the
12941 			 * data off of the AOR RS on this side, and
12942 			 * transferred it to remote (mirror) memory on the
12943 			 * other side.  Since we already have the data in
12944 			 * memory here, we just need to use it.
12945 			 *
12946 			 * XXX KDM this can probably be removed once we
12947 			 * get the cache device code in and take the
12948 			 * current AOR implementation out.
12949 			 */
12950 #ifdef NEEDTOPORT
12951 			if ((remote_sglist[i].addr >=
12952 			     (void *)vtophys(softc->mirr->addr))
12953 			 && (remote_sglist[i].addr <
12954 			     ((void *)vtophys(softc->mirr->addr) +
12955 			     CacheMirrorOffset))) {
12956 				local_sglist[i].addr = remote_sglist[i].addr -
12957 					CacheMirrorOffset;
12958 				if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
12959 				     CTL_FLAG_DATA_IN)
12960 					io->io_hdr.flags |= CTL_FLAG_REDIR_DONE;
12961 			} else {
12962 				local_sglist[i].addr = remote_sglist[i].addr +
12963 					CacheMirrorOffset;
12964 			}
12965 #endif
12966 #if 0
12967 			printf("%s: local %p, remote %p, len %d\n",
12968 			       __func__, local_sglist[i].addr,
12969 			       remote_sglist[i].addr, local_sglist[i].len);
12970 #endif
12971 		}
12972 	} else {
12973 		uint32_t len_to_go;
12974 
12975 		/*
12976 		 * In this case, we don't have automatically allocated
12977 		 * memory for this I/O on this controller.  This typically
12978 		 * happens with internal CTL I/O -- e.g. inquiry, mode
12979 		 * sense, etc.  Anything coming from RAIDCore will have
12980 		 * a mirror area available.
12981 		 */
12982 		len_to_go = io->scsiio.kern_data_len;
12983 
12984 		/*
12985 		 * Clear the no datasync flag, we have to use malloced
12986 		 * buffers.
12987 		 */
12988 		io->io_hdr.flags &= ~CTL_FLAG_NO_DATASYNC;
12989 
12990 		/*
12991 		 * The difficult thing here is that the size of the various
12992 		 * S/G segments may be different than the size from the
12993 		 * remote controller.  That'll make it harder when DMAing
12994 		 * the data back to the other side.
12995 		 */
12996 		for (i = 0; (i < sizeof(io->io_hdr.remote_sglist) /
12997 		     sizeof(io->io_hdr.remote_sglist[0])) &&
12998 		     (len_to_go > 0); i++) {
12999 			local_sglist[i].len = ctl_min(len_to_go, 131072);
13000 			CTL_SIZE_8B(local_dma_sglist[i].len,
13001 				    local_sglist[i].len);
13002 			local_sglist[i].addr =
13003 				malloc(local_dma_sglist[i].len, M_CTL,M_WAITOK);
13004 
13005 			local_dma_sglist[i].addr = local_sglist[i].addr;
13006 
13007 			if (local_sglist[i].addr == NULL) {
13008 				int j;
13009 
13010 				printf("malloc failed for %zd bytes!",
13011 				       local_dma_sglist[i].len);
13012 				for (j = 0; j < i; j++) {
13013 					free(local_sglist[j].addr, M_CTL);
13014 				}
13015 				ctl_set_internal_failure(&io->scsiio,
13016 							 /*sks_valid*/ 1,
13017 							 /*retry_count*/ 4857);
13018 				retval = 1;
13019 				goto bailout_error;
13020 
13021 			}
13022 			/* XXX KDM do we need a sync here? */
13023 
13024 			len_to_go -= local_sglist[i].len;
13025 		}
13026 		/*
13027 		 * Reset the number of S/G entries accordingly.  The
13028 		 * original number of S/G entries is available in
13029 		 * rem_sg_entries.
13030 		 */
13031 		io->scsiio.kern_sg_entries = i;
13032 
13033 #if 0
13034 		printf("%s: kern_sg_entries = %d\n", __func__,
13035 		       io->scsiio.kern_sg_entries);
13036 		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13037 			printf("%s: sg[%d] = %p, %d (DMA: %d)\n", __func__, i,
13038 			       local_sglist[i].addr, local_sglist[i].len,
13039 			       local_dma_sglist[i].len);
13040 #endif
13041 	}
13042 
13043 
13044 	return (retval);
13045 
13046 bailout_error:
13047 
13048 	ctl_send_datamove_done(io, /*have_lock*/ 0);
13049 
13050 	return (retval);
13051 }
13052 
13053 static int
13054 ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
13055 			 ctl_ha_dt_cb callback)
13056 {
13057 	struct ctl_ha_dt_req *rq;
13058 	struct ctl_sg_entry *remote_sglist, *local_sglist;
13059 	struct ctl_sg_entry *remote_dma_sglist, *local_dma_sglist;
13060 	uint32_t local_used, remote_used, total_used;
13061 	int retval;
13062 	int i, j;
13063 
13064 	retval = 0;
13065 
13066 	rq = ctl_dt_req_alloc();
13067 
13068 	/*
13069 	 * If we failed to allocate the request, and if the DMA didn't fail
13070 	 * anyway, set busy status.  This is just a resource allocation
13071 	 * failure.
13072 	 */
13073 	if ((rq == NULL)
13074 	 && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE))
13075 		ctl_set_busy(&io->scsiio);
13076 
13077 	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE) {
13078 
13079 		if (rq != NULL)
13080 			ctl_dt_req_free(rq);
13081 
13082 		/*
13083 		 * The data move failed.  We need to return status back
13084 		 * to the other controller.  No point in trying to DMA
13085 		 * data to the remote controller.
13086 		 */
13087 
13088 		ctl_send_datamove_done(io, /*have_lock*/ 0);
13089 
13090 		retval = 1;
13091 
13092 		goto bailout;
13093 	}
13094 
13095 	local_sglist = io->io_hdr.local_sglist;
13096 	local_dma_sglist = io->io_hdr.local_dma_sglist;
13097 	remote_sglist = io->io_hdr.remote_sglist;
13098 	remote_dma_sglist = io->io_hdr.remote_dma_sglist;
13099 	local_used = 0;
13100 	remote_used = 0;
13101 	total_used = 0;
13102 
13103 	if (io->io_hdr.flags & CTL_FLAG_REDIR_DONE) {
13104 		rq->ret = CTL_HA_STATUS_SUCCESS;
13105 		rq->context = io;
13106 		callback(rq);
13107 		goto bailout;
13108 	}
13109 
13110 	/*
13111 	 * Pull/push the data over the wire from/to the other controller.
13112 	 * This takes into account the possibility that the local and
13113 	 * remote sglists may not be identical in terms of the size of
13114 	 * the elements and the number of elements.
13115 	 *
13116 	 * One fundamental assumption here is that the length allocated for
13117 	 * both the local and remote sglists is identical.  Otherwise, we've
13118 	 * essentially got a coding error of some sort.
13119 	 */
13120 	for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
13121 		int isc_ret;
13122 		uint32_t cur_len, dma_length;
13123 		uint8_t *tmp_ptr;
13124 
13125 		rq->id = CTL_HA_DATA_CTL;
13126 		rq->command = command;
13127 		rq->context = io;
13128 
13129 		/*
13130 		 * Both pointers should be aligned.  But it is possible
13131 		 * that the allocation length is not.  They should both
13132 		 * also have enough slack left over at the end, though,
13133 		 * to round up to the next 8 byte boundary.
13134 		 */
13135 		cur_len = ctl_min(local_sglist[i].len - local_used,
13136 				  remote_sglist[j].len - remote_used);
13137 
13138 		/*
13139 		 * In this case, we have a size issue and need to decrease
13140 		 * the size, except in the case where we actually have less
13141 		 * than 8 bytes left.  In that case, we need to increase
13142 		 * the DMA length to get the last bit.
13143 		 */
13144 		if ((cur_len & 0x7) != 0) {
13145 			if (cur_len > 0x7) {
13146 				cur_len = cur_len - (cur_len & 0x7);
13147 				dma_length = cur_len;
13148 			} else {
13149 				CTL_SIZE_8B(dma_length, cur_len);
13150 			}
13151 
13152 		} else
13153 			dma_length = cur_len;
13154 
13155 		/*
13156 		 * If we had to allocate memory for this I/O, instead of using
13157 		 * the non-cached mirror memory, we'll need to flush the cache
13158 		 * before trying to DMA to the other controller.
13159 		 *
13160 		 * We could end up doing this multiple times for the same
13161 		 * segment if we have a larger local segment than remote
13162 		 * segment.  That shouldn't be an issue.
13163 		 */
13164 		if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
13165 			/*
13166 			 * XXX KDM use bus_dmamap_sync() here.
13167 			 */
13168 		}
13169 
13170 		rq->size = dma_length;
13171 
13172 		tmp_ptr = (uint8_t *)local_sglist[i].addr;
13173 		tmp_ptr += local_used;
13174 
13175 		/* Use physical addresses when talking to ISC hardware */
13176 		if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
13177 			/* XXX KDM use busdma */
13178 #if 0
13179 			rq->local = vtophys(tmp_ptr);
13180 #endif
13181 		} else
13182 			rq->local = tmp_ptr;
13183 
13184 		tmp_ptr = (uint8_t *)remote_sglist[j].addr;
13185 		tmp_ptr += remote_used;
13186 		rq->remote = tmp_ptr;
13187 
13188 		rq->callback = NULL;
13189 
13190 		local_used += cur_len;
13191 		if (local_used >= local_sglist[i].len) {
13192 			i++;
13193 			local_used = 0;
13194 		}
13195 
13196 		remote_used += cur_len;
13197 		if (remote_used >= remote_sglist[j].len) {
13198 			j++;
13199 			remote_used = 0;
13200 		}
13201 		total_used += cur_len;
13202 
13203 		if (total_used >= io->scsiio.kern_data_len)
13204 			rq->callback = callback;
13205 
13206 		if ((rq->size & 0x7) != 0) {
13207 			printf("%s: warning: size %d is not on 8b boundary\n",
13208 			       __func__, rq->size);
13209 		}
13210 		if (((uintptr_t)rq->local & 0x7) != 0) {
13211 			printf("%s: warning: local %p not on 8b boundary\n",
13212 			       __func__, rq->local);
13213 		}
13214 		if (((uintptr_t)rq->remote & 0x7) != 0) {
13215 			printf("%s: warning: remote %p not on 8b boundary\n",
13216 			       __func__, rq->local);
13217 		}
13218 #if 0
13219 		printf("%s: %s: local %#x remote %#x size %d\n", __func__,
13220 		       (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
13221 		       rq->local, rq->remote, rq->size);
13222 #endif
13223 
13224 		isc_ret = ctl_dt_single(rq);
13225 		if (isc_ret == CTL_HA_STATUS_WAIT)
13226 			continue;
13227 
13228 		if (isc_ret == CTL_HA_STATUS_DISCONNECT) {
13229 			rq->ret = CTL_HA_STATUS_SUCCESS;
13230 		} else {
13231 			rq->ret = isc_ret;
13232 		}
13233 		callback(rq);
13234 		goto bailout;
13235 	}
13236 
13237 bailout:
13238 	return (retval);
13239 
13240 }
13241 
13242 static void
13243 ctl_datamove_remote_read(union ctl_io *io)
13244 {
13245 	int retval;
13246 	int i;
13247 
13248 	/*
13249 	 * This will send an error to the other controller in the case of a
13250 	 * failure.
13251 	 */
13252 	retval = ctl_datamove_remote_sgl_setup(io);
13253 	if (retval != 0)
13254 		return;
13255 
13256 	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
13257 					  ctl_datamove_remote_read_cb);
13258 	if ((retval != 0)
13259 	 && ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0)) {
13260 		/*
13261 		 * Make sure we free memory if there was an error..  The
13262 		 * ctl_datamove_remote_xfer() function will send the
13263 		 * datamove done message, or call the callback with an
13264 		 * error if there is a problem.
13265 		 */
13266 		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13267 			free(io->io_hdr.local_sglist[i].addr, M_CTL);
13268 	}
13269 
13270 	return;
13271 }
13272 
13273 /*
13274  * Process a datamove request from the other controller.  This is used for
13275  * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
13276  * first.  Once that is complete, the data gets DMAed into the remote
13277  * controller's memory.  For reads, we DMA from the remote controller's
13278  * memory into our memory first, and then move it out to the FETD.
13279  */
13280 static void
13281 ctl_datamove_remote(union ctl_io *io)
13282 {
13283 	struct ctl_softc *softc;
13284 
13285 	softc = control_softc;
13286 
13287 	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
13288 
13289 	/*
13290 	 * Note that we look for an aborted I/O here, but don't do some of
13291 	 * the other checks that ctl_datamove() normally does.
13292 	 * We don't need to run the datamove delay code, since that should
13293 	 * have been done if need be on the other controller.
13294 	 */
13295 	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
13296 		printf("%s: tag 0x%04x on (%d:%d:%d:%d) aborted\n", __func__,
13297 		       io->scsiio.tag_num, io->io_hdr.nexus.initid.id,
13298 		       io->io_hdr.nexus.targ_port,
13299 		       io->io_hdr.nexus.targ_target.id,
13300 		       io->io_hdr.nexus.targ_lun);
13301 		io->io_hdr.port_status = 31338;
13302 		ctl_send_datamove_done(io, /*have_lock*/ 0);
13303 		return;
13304 	}
13305 
13306 	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT) {
13307 		ctl_datamove_remote_write(io);
13308 	} else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN){
13309 		ctl_datamove_remote_read(io);
13310 	} else {
13311 		union ctl_ha_msg msg;
13312 		struct scsi_sense_data *sense;
13313 		uint8_t sks[3];
13314 		int retry_count;
13315 
13316 		memset(&msg, 0, sizeof(msg));
13317 
13318 		msg.hdr.msg_type = CTL_MSG_BAD_JUJU;
13319 		msg.hdr.status = CTL_SCSI_ERROR;
13320 		msg.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
13321 
13322 		retry_count = 4243;
13323 
13324 		sense = &msg.scsi.sense_data;
13325 		sks[0] = SSD_SCS_VALID;
13326 		sks[1] = (retry_count >> 8) & 0xff;
13327 		sks[2] = retry_count & 0xff;
13328 
13329 		/* "Internal target failure" */
13330 		scsi_set_sense_data(sense,
13331 				    /*sense_format*/ SSD_TYPE_NONE,
13332 				    /*current_error*/ 1,
13333 				    /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
13334 				    /*asc*/ 0x44,
13335 				    /*ascq*/ 0x00,
13336 				    /*type*/ SSD_ELEM_SKS,
13337 				    /*size*/ sizeof(sks),
13338 				    /*data*/ sks,
13339 				    SSD_ELEM_NONE);
13340 
13341 		io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
13342 		if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13343 			ctl_failover_io(io, /*have_lock*/ 1);
13344 			return;
13345 		}
13346 
13347 		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0) >
13348 		    CTL_HA_STATUS_SUCCESS) {
13349 			/* XXX KDM what to do if this fails? */
13350 		}
13351 		return;
13352 	}
13353 
13354 }
13355 
13356 static int
13357 ctl_process_done(union ctl_io *io)
13358 {
13359 	struct ctl_lun *lun;
13360 	struct ctl_softc *ctl_softc;
13361 	void (*fe_done)(union ctl_io *io);
13362 	uint32_t targ_port = ctl_port_idx(io->io_hdr.nexus.targ_port);
13363 
13364 	CTL_DEBUG_PRINT(("ctl_process_done\n"));
13365 
13366 	fe_done =
13367 	    control_softc->ctl_ports[targ_port]->fe_done;
13368 
13369 #ifdef CTL_TIME_IO
13370 	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
13371 		char str[256];
13372 		char path_str[64];
13373 		struct sbuf sb;
13374 
13375 		ctl_scsi_path_string(io, path_str, sizeof(path_str));
13376 		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13377 
13378 		sbuf_cat(&sb, path_str);
13379 		switch (io->io_hdr.io_type) {
13380 		case CTL_IO_SCSI:
13381 			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
13382 			sbuf_printf(&sb, "\n");
13383 			sbuf_cat(&sb, path_str);
13384 			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13385 				    io->scsiio.tag_num, io->scsiio.tag_type);
13386 			break;
13387 		case CTL_IO_TASK:
13388 			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
13389 				    "Tag Type: %d\n", io->taskio.task_action,
13390 				    io->taskio.tag_num, io->taskio.tag_type);
13391 			break;
13392 		default:
13393 			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13394 			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13395 			break;
13396 		}
13397 		sbuf_cat(&sb, path_str);
13398 		sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
13399 			    (intmax_t)time_uptime - io->io_hdr.start_time);
13400 		sbuf_finish(&sb);
13401 		printf("%s", sbuf_data(&sb));
13402 	}
13403 #endif /* CTL_TIME_IO */
13404 
13405 	switch (io->io_hdr.io_type) {
13406 	case CTL_IO_SCSI:
13407 		break;
13408 	case CTL_IO_TASK:
13409 		if (bootverbose || verbose > 0)
13410 			ctl_io_error_print(io, NULL);
13411 		if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
13412 			ctl_free_io(io);
13413 		else
13414 			fe_done(io);
13415 		return (CTL_RETVAL_COMPLETE);
13416 		break;
13417 	default:
13418 		printf("ctl_process_done: invalid io type %d\n",
13419 		       io->io_hdr.io_type);
13420 		panic("ctl_process_done: invalid io type %d\n",
13421 		      io->io_hdr.io_type);
13422 		break; /* NOTREACHED */
13423 	}
13424 
13425 	lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13426 	if (lun == NULL) {
13427 		CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13428 				 io->io_hdr.nexus.targ_mapped_lun));
13429 		fe_done(io);
13430 		goto bailout;
13431 	}
13432 	ctl_softc = lun->ctl_softc;
13433 
13434 	mtx_lock(&lun->lun_lock);
13435 
13436 	/*
13437 	 * Check to see if we have any errors to inject here.  We only
13438 	 * inject errors for commands that don't already have errors set.
13439 	 */
13440 	if ((STAILQ_FIRST(&lun->error_list) != NULL)
13441 	 && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS))
13442 		ctl_inject_error(lun, io);
13443 
13444 	/*
13445 	 * XXX KDM how do we treat commands that aren't completed
13446 	 * successfully?
13447 	 *
13448 	 * XXX KDM should we also track I/O latency?
13449 	 */
13450 	if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13451 	    io->io_hdr.io_type == CTL_IO_SCSI) {
13452 #ifdef CTL_TIME_IO
13453 		struct bintime cur_bt;
13454 #endif
13455 		int type;
13456 
13457 		if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13458 		    CTL_FLAG_DATA_IN)
13459 			type = CTL_STATS_READ;
13460 		else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13461 		    CTL_FLAG_DATA_OUT)
13462 			type = CTL_STATS_WRITE;
13463 		else
13464 			type = CTL_STATS_NO_IO;
13465 
13466 		lun->stats.ports[targ_port].bytes[type] +=
13467 		    io->scsiio.kern_total_len;
13468 		lun->stats.ports[targ_port].operations[type]++;
13469 #ifdef CTL_TIME_IO
13470 		bintime_add(&lun->stats.ports[targ_port].dma_time[type],
13471 		   &io->io_hdr.dma_bt);
13472 		lun->stats.ports[targ_port].num_dmas[type] +=
13473 		    io->io_hdr.num_dmas;
13474 		getbintime(&cur_bt);
13475 		bintime_sub(&cur_bt, &io->io_hdr.start_bt);
13476 		bintime_add(&lun->stats.ports[targ_port].time[type], &cur_bt);
13477 #endif
13478 	}
13479 
13480 	/*
13481 	 * Remove this from the OOA queue.
13482 	 */
13483 	TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13484 
13485 	/*
13486 	 * Run through the blocked queue on this LUN and see if anything
13487 	 * has become unblocked, now that this transaction is done.
13488 	 */
13489 	ctl_check_blocked(lun);
13490 
13491 	/*
13492 	 * If the LUN has been invalidated, free it if there is nothing
13493 	 * left on its OOA queue.
13494 	 */
13495 	if ((lun->flags & CTL_LUN_INVALID)
13496 	 && TAILQ_EMPTY(&lun->ooa_queue)) {
13497 		mtx_unlock(&lun->lun_lock);
13498 		mtx_lock(&ctl_softc->ctl_lock);
13499 		ctl_free_lun(lun);
13500 		mtx_unlock(&ctl_softc->ctl_lock);
13501 	} else
13502 		mtx_unlock(&lun->lun_lock);
13503 
13504 	/*
13505 	 * If this command has been aborted, make sure we set the status
13506 	 * properly.  The FETD is responsible for freeing the I/O and doing
13507 	 * whatever it needs to do to clean up its state.
13508 	 */
13509 	if (io->io_hdr.flags & CTL_FLAG_ABORT)
13510 		ctl_set_task_aborted(&io->scsiio);
13511 
13512 	/*
13513 	 * We print out status for every task management command.  For SCSI
13514 	 * commands, we filter out any unit attention errors; they happen
13515 	 * on every boot, and would clutter up the log.  Note:  task
13516 	 * management commands aren't printed here, they are printed above,
13517 	 * since they should never even make it down here.
13518 	 */
13519 	switch (io->io_hdr.io_type) {
13520 	case CTL_IO_SCSI: {
13521 		int error_code, sense_key, asc, ascq;
13522 
13523 		sense_key = 0;
13524 
13525 		if (((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SCSI_ERROR)
13526 		 && (io->scsiio.scsi_status == SCSI_STATUS_CHECK_COND)) {
13527 			/*
13528 			 * Since this is just for printing, no need to
13529 			 * show errors here.
13530 			 */
13531 			scsi_extract_sense_len(&io->scsiio.sense_data,
13532 					       io->scsiio.sense_len,
13533 					       &error_code,
13534 					       &sense_key,
13535 					       &asc,
13536 					       &ascq,
13537 					       /*show_errors*/ 0);
13538 		}
13539 
13540 		if (((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)
13541 		 && (((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SCSI_ERROR)
13542 		  || (io->scsiio.scsi_status != SCSI_STATUS_CHECK_COND)
13543 		  || (sense_key != SSD_KEY_UNIT_ATTENTION))) {
13544 
13545 			if ((time_uptime - ctl_softc->last_print_jiffies) <= 0){
13546 				ctl_softc->skipped_prints++;
13547 			} else {
13548 				uint32_t skipped_prints;
13549 
13550 				skipped_prints = ctl_softc->skipped_prints;
13551 
13552 				ctl_softc->skipped_prints = 0;
13553 				ctl_softc->last_print_jiffies = time_uptime;
13554 
13555 				if (skipped_prints > 0) {
13556 #ifdef NEEDTOPORT
13557 					csevent_log(CSC_CTL | CSC_SHELF_SW |
13558 					    CTL_ERROR_REPORT,
13559 					    csevent_LogType_Trace,
13560 					    csevent_Severity_Information,
13561 					    csevent_AlertLevel_Green,
13562 					    csevent_FRU_Firmware,
13563 					    csevent_FRU_Unknown,
13564 					    "High CTL error volume, %d prints "
13565 					    "skipped", skipped_prints);
13566 #endif
13567 				}
13568 				if (bootverbose || verbose > 0)
13569 					ctl_io_error_print(io, NULL);
13570 			}
13571 		}
13572 		break;
13573 	}
13574 	case CTL_IO_TASK:
13575 		if (bootverbose || verbose > 0)
13576 			ctl_io_error_print(io, NULL);
13577 		break;
13578 	default:
13579 		break;
13580 	}
13581 
13582 	/*
13583 	 * Tell the FETD or the other shelf controller we're done with this
13584 	 * command.  Note that only SCSI commands get to this point.  Task
13585 	 * management commands are completed above.
13586 	 *
13587 	 * We only send status to the other controller if we're in XFER
13588 	 * mode.  In SER_ONLY mode, the I/O is done on the controller that
13589 	 * received the I/O (from CTL's perspective), and so the status is
13590 	 * generated there.
13591 	 *
13592 	 * XXX KDM if we hold the lock here, we could cause a deadlock
13593 	 * if the frontend comes back in in this context to queue
13594 	 * something.
13595 	 */
13596 	if ((ctl_softc->ha_mode == CTL_HA_MODE_XFER)
13597 	 && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
13598 		union ctl_ha_msg msg;
13599 
13600 		memset(&msg, 0, sizeof(msg));
13601 		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13602 		msg.hdr.original_sc = io->io_hdr.original_sc;
13603 		msg.hdr.nexus = io->io_hdr.nexus;
13604 		msg.hdr.status = io->io_hdr.status;
13605 		msg.scsi.scsi_status = io->scsiio.scsi_status;
13606 		msg.scsi.tag_num = io->scsiio.tag_num;
13607 		msg.scsi.tag_type = io->scsiio.tag_type;
13608 		msg.scsi.sense_len = io->scsiio.sense_len;
13609 		msg.scsi.sense_residual = io->scsiio.sense_residual;
13610 		msg.scsi.residual = io->scsiio.residual;
13611 		memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
13612 		       sizeof(io->scsiio.sense_data));
13613 		/*
13614 		 * We copy this whether or not this is an I/O-related
13615 		 * command.  Otherwise, we'd have to go and check to see
13616 		 * whether it's a read/write command, and it really isn't
13617 		 * worth it.
13618 		 */
13619 		memcpy(&msg.scsi.lbalen,
13620 		       &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
13621 		       sizeof(msg.scsi.lbalen));
13622 
13623 		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13624 				sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
13625 			/* XXX do something here */
13626 		}
13627 
13628 		ctl_free_io(io);
13629 	} else
13630 		fe_done(io);
13631 
13632 bailout:
13633 
13634 	return (CTL_RETVAL_COMPLETE);
13635 }
13636 
13637 #ifdef CTL_WITH_CA
13638 /*
13639  * Front end should call this if it doesn't do autosense.  When the request
13640  * sense comes back in from the initiator, we'll dequeue this and send it.
13641  */
13642 int
13643 ctl_queue_sense(union ctl_io *io)
13644 {
13645 	struct ctl_lun *lun;
13646 	struct ctl_softc *ctl_softc;
13647 	uint32_t initidx, targ_lun;
13648 
13649 	ctl_softc = control_softc;
13650 
13651 	CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13652 
13653 	/*
13654 	 * LUN lookup will likely move to the ctl_work_thread() once we
13655 	 * have our new queueing infrastructure (that doesn't put things on
13656 	 * a per-LUN queue initially).  That is so that we can handle
13657 	 * things like an INQUIRY to a LUN that we don't have enabled.  We
13658 	 * can't deal with that right now.
13659 	 */
13660 	mtx_lock(&ctl_softc->ctl_lock);
13661 
13662 	/*
13663 	 * If we don't have a LUN for this, just toss the sense
13664 	 * information.
13665 	 */
13666 	targ_lun = io->io_hdr.nexus.targ_lun;
13667 	targ_lun = ctl_map_lun(io->io_hdr.nexus.targ_port, targ_lun);
13668 	if ((targ_lun < CTL_MAX_LUNS)
13669 	 && (ctl_softc->ctl_luns[targ_lun] != NULL))
13670 		lun = ctl_softc->ctl_luns[targ_lun];
13671 	else
13672 		goto bailout;
13673 
13674 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
13675 
13676 	mtx_lock(&lun->lun_lock);
13677 	/*
13678 	 * Already have CA set for this LUN...toss the sense information.
13679 	 */
13680 	if (ctl_is_set(lun->have_ca, initidx)) {
13681 		mtx_unlock(&lun->lun_lock);
13682 		goto bailout;
13683 	}
13684 
13685 	memcpy(&lun->pending_sense[initidx], &io->scsiio.sense_data,
13686 	       ctl_min(sizeof(lun->pending_sense[initidx]),
13687 	       sizeof(io->scsiio.sense_data)));
13688 	ctl_set_mask(lun->have_ca, initidx);
13689 	mtx_unlock(&lun->lun_lock);
13690 
13691 bailout:
13692 	mtx_unlock(&ctl_softc->ctl_lock);
13693 
13694 	ctl_free_io(io);
13695 
13696 	return (CTL_RETVAL_COMPLETE);
13697 }
13698 #endif
13699 
13700 /*
13701  * Primary command inlet from frontend ports.  All SCSI and task I/O
13702  * requests must go through this function.
13703  */
13704 int
13705 ctl_queue(union ctl_io *io)
13706 {
13707 	struct ctl_softc *ctl_softc;
13708 
13709 	CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13710 
13711 	ctl_softc = control_softc;
13712 
13713 #ifdef CTL_TIME_IO
13714 	io->io_hdr.start_time = time_uptime;
13715 	getbintime(&io->io_hdr.start_bt);
13716 #endif /* CTL_TIME_IO */
13717 
13718 	/* Map FE-specific LUN ID into global one. */
13719 	io->io_hdr.nexus.targ_mapped_lun =
13720 	    ctl_map_lun(io->io_hdr.nexus.targ_port, io->io_hdr.nexus.targ_lun);
13721 
13722 	switch (io->io_hdr.io_type) {
13723 	case CTL_IO_SCSI:
13724 	case CTL_IO_TASK:
13725 		ctl_enqueue_incoming(io);
13726 		break;
13727 	default:
13728 		printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13729 		return (EINVAL);
13730 	}
13731 
13732 	return (CTL_RETVAL_COMPLETE);
13733 }
13734 
13735 #ifdef CTL_IO_DELAY
13736 static void
13737 ctl_done_timer_wakeup(void *arg)
13738 {
13739 	union ctl_io *io;
13740 
13741 	io = (union ctl_io *)arg;
13742 	ctl_done(io);
13743 }
13744 #endif /* CTL_IO_DELAY */
13745 
13746 void
13747 ctl_done(union ctl_io *io)
13748 {
13749 	struct ctl_softc *ctl_softc;
13750 
13751 	ctl_softc = control_softc;
13752 
13753 	/*
13754 	 * Enable this to catch duplicate completion issues.
13755 	 */
13756 #if 0
13757 	if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13758 		printf("%s: type %d msg %d cdb %x iptl: "
13759 		       "%d:%d:%d:%d tag 0x%04x "
13760 		       "flag %#x status %x\n",
13761 			__func__,
13762 			io->io_hdr.io_type,
13763 			io->io_hdr.msg_type,
13764 			io->scsiio.cdb[0],
13765 			io->io_hdr.nexus.initid.id,
13766 			io->io_hdr.nexus.targ_port,
13767 			io->io_hdr.nexus.targ_target.id,
13768 			io->io_hdr.nexus.targ_lun,
13769 			(io->io_hdr.io_type ==
13770 			CTL_IO_TASK) ?
13771 			io->taskio.tag_num :
13772 			io->scsiio.tag_num,
13773 		        io->io_hdr.flags,
13774 			io->io_hdr.status);
13775 	} else
13776 		io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13777 #endif
13778 
13779 	/*
13780 	 * This is an internal copy of an I/O, and should not go through
13781 	 * the normal done processing logic.
13782 	 */
13783 	if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13784 		return;
13785 
13786 	/*
13787 	 * We need to send a msg to the serializing shelf to finish the IO
13788 	 * as well.  We don't send a finish message to the other shelf if
13789 	 * this is a task management command.  Task management commands
13790 	 * aren't serialized in the OOA queue, but rather just executed on
13791 	 * both shelf controllers for commands that originated on that
13792 	 * controller.
13793 	 */
13794 	if ((io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)
13795 	 && (io->io_hdr.io_type != CTL_IO_TASK)) {
13796 		union ctl_ha_msg msg_io;
13797 
13798 		msg_io.hdr.msg_type = CTL_MSG_FINISH_IO;
13799 		msg_io.hdr.serializing_sc = io->io_hdr.serializing_sc;
13800 		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_io,
13801 		    sizeof(msg_io), 0 ) != CTL_HA_STATUS_SUCCESS) {
13802 		}
13803 		/* continue on to finish IO */
13804 	}
13805 #ifdef CTL_IO_DELAY
13806 	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13807 		struct ctl_lun *lun;
13808 
13809 		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13810 
13811 		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13812 	} else {
13813 		struct ctl_lun *lun;
13814 
13815 		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13816 
13817 		if ((lun != NULL)
13818 		 && (lun->delay_info.done_delay > 0)) {
13819 			struct callout *callout;
13820 
13821 			callout = (struct callout *)&io->io_hdr.timer_bytes;
13822 			callout_init(callout, /*mpsafe*/ 1);
13823 			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
13824 			callout_reset(callout,
13825 				      lun->delay_info.done_delay * hz,
13826 				      ctl_done_timer_wakeup, io);
13827 			if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
13828 				lun->delay_info.done_delay = 0;
13829 			return;
13830 		}
13831 	}
13832 #endif /* CTL_IO_DELAY */
13833 
13834 	ctl_enqueue_done(io);
13835 }
13836 
13837 int
13838 ctl_isc(struct ctl_scsiio *ctsio)
13839 {
13840 	struct ctl_lun *lun;
13841 	int retval;
13842 
13843 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13844 
13845 	CTL_DEBUG_PRINT(("ctl_isc: command: %02x\n", ctsio->cdb[0]));
13846 
13847 	CTL_DEBUG_PRINT(("ctl_isc: calling data_submit()\n"));
13848 
13849 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
13850 
13851 	return (retval);
13852 }
13853 
13854 
13855 static void
13856 ctl_work_thread(void *arg)
13857 {
13858 	struct ctl_thread *thr = (struct ctl_thread *)arg;
13859 	struct ctl_softc *softc = thr->ctl_softc;
13860 	union ctl_io *io;
13861 	int retval;
13862 
13863 	CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
13864 
13865 	for (;;) {
13866 		retval = 0;
13867 
13868 		/*
13869 		 * We handle the queues in this order:
13870 		 * - ISC
13871 		 * - done queue (to free up resources, unblock other commands)
13872 		 * - RtR queue
13873 		 * - incoming queue
13874 		 *
13875 		 * If those queues are empty, we break out of the loop and
13876 		 * go to sleep.
13877 		 */
13878 		mtx_lock(&thr->queue_lock);
13879 		io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
13880 		if (io != NULL) {
13881 			STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
13882 			mtx_unlock(&thr->queue_lock);
13883 			ctl_handle_isc(io);
13884 			continue;
13885 		}
13886 		io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
13887 		if (io != NULL) {
13888 			STAILQ_REMOVE_HEAD(&thr->done_queue, links);
13889 			/* clear any blocked commands, call fe_done */
13890 			mtx_unlock(&thr->queue_lock);
13891 			retval = ctl_process_done(io);
13892 			continue;
13893 		}
13894 		io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
13895 		if (io != NULL) {
13896 			STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
13897 			mtx_unlock(&thr->queue_lock);
13898 			if (io->io_hdr.io_type == CTL_IO_TASK)
13899 				ctl_run_task(io);
13900 			else
13901 				ctl_scsiio_precheck(softc, &io->scsiio);
13902 			continue;
13903 		}
13904 		if (!ctl_pause_rtr) {
13905 			io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
13906 			if (io != NULL) {
13907 				STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
13908 				mtx_unlock(&thr->queue_lock);
13909 				retval = ctl_scsiio(&io->scsiio);
13910 				if (retval != CTL_RETVAL_COMPLETE)
13911 					CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
13912 				continue;
13913 			}
13914 		}
13915 
13916 		/* Sleep until we have something to do. */
13917 		mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
13918 	}
13919 }
13920 
13921 static void
13922 ctl_lun_thread(void *arg)
13923 {
13924 	struct ctl_softc *softc = (struct ctl_softc *)arg;
13925 	struct ctl_be_lun *be_lun;
13926 	int retval;
13927 
13928 	CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
13929 
13930 	for (;;) {
13931 		retval = 0;
13932 		mtx_lock(&softc->ctl_lock);
13933 		be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
13934 		if (be_lun != NULL) {
13935 			STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
13936 			mtx_unlock(&softc->ctl_lock);
13937 			ctl_create_lun(be_lun);
13938 			continue;
13939 		}
13940 
13941 		/* Sleep until we have something to do. */
13942 		mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
13943 		    PDROP | PRIBIO, "-", 0);
13944 	}
13945 }
13946 
13947 static void
13948 ctl_enqueue_incoming(union ctl_io *io)
13949 {
13950 	struct ctl_softc *softc = control_softc;
13951 	struct ctl_thread *thr;
13952 	u_int idx;
13953 
13954 	idx = (io->io_hdr.nexus.targ_port * 127 +
13955 	       io->io_hdr.nexus.initid.id) % worker_threads;
13956 	thr = &softc->threads[idx];
13957 	mtx_lock(&thr->queue_lock);
13958 	STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
13959 	mtx_unlock(&thr->queue_lock);
13960 	wakeup(thr);
13961 }
13962 
13963 static void
13964 ctl_enqueue_rtr(union ctl_io *io)
13965 {
13966 	struct ctl_softc *softc = control_softc;
13967 	struct ctl_thread *thr;
13968 
13969 	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13970 	mtx_lock(&thr->queue_lock);
13971 	STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
13972 	mtx_unlock(&thr->queue_lock);
13973 	wakeup(thr);
13974 }
13975 
13976 static void
13977 ctl_enqueue_done(union ctl_io *io)
13978 {
13979 	struct ctl_softc *softc = control_softc;
13980 	struct ctl_thread *thr;
13981 
13982 	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13983 	mtx_lock(&thr->queue_lock);
13984 	STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
13985 	mtx_unlock(&thr->queue_lock);
13986 	wakeup(thr);
13987 }
13988 
13989 static void
13990 ctl_enqueue_isc(union ctl_io *io)
13991 {
13992 	struct ctl_softc *softc = control_softc;
13993 	struct ctl_thread *thr;
13994 
13995 	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13996 	mtx_lock(&thr->queue_lock);
13997 	STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
13998 	mtx_unlock(&thr->queue_lock);
13999 	wakeup(thr);
14000 }
14001 
14002 /* Initialization and failover */
14003 
14004 void
14005 ctl_init_isc_msg(void)
14006 {
14007 	printf("CTL: Still calling this thing\n");
14008 }
14009 
14010 /*
14011  * Init component
14012  * 	Initializes component into configuration defined by bootMode
14013  *	(see hasc-sv.c)
14014  *  	returns hasc_Status:
14015  * 		OK
14016  *		ERROR - fatal error
14017  */
14018 static ctl_ha_comp_status
14019 ctl_isc_init(struct ctl_ha_component *c)
14020 {
14021 	ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14022 
14023 	c->status = ret;
14024 	return ret;
14025 }
14026 
14027 /* Start component
14028  * 	Starts component in state requested. If component starts successfully,
14029  *	it must set its own state to the requestrd state
14030  *	When requested state is HASC_STATE_HA, the component may refine it
14031  * 	by adding _SLAVE or _MASTER flags.
14032  *	Currently allowed state transitions are:
14033  *	UNKNOWN->HA		- initial startup
14034  *	UNKNOWN->SINGLE - initial startup when no parter detected
14035  *	HA->SINGLE		- failover
14036  * returns ctl_ha_comp_status:
14037  * 		OK	- component successfully started in requested state
14038  *		FAILED  - could not start the requested state, failover may
14039  * 			  be possible
14040  *		ERROR	- fatal error detected, no future startup possible
14041  */
14042 static ctl_ha_comp_status
14043 ctl_isc_start(struct ctl_ha_component *c, ctl_ha_state state)
14044 {
14045 	ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14046 
14047 	printf("%s: go\n", __func__);
14048 
14049 	// UNKNOWN->HA or UNKNOWN->SINGLE (bootstrap)
14050 	if (c->state == CTL_HA_STATE_UNKNOWN ) {
14051 		ctl_is_single = 0;
14052 		if (ctl_ha_msg_create(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
14053 		    != CTL_HA_STATUS_SUCCESS) {
14054 			printf("ctl_isc_start: ctl_ha_msg_create failed.\n");
14055 			ret = CTL_HA_COMP_STATUS_ERROR;
14056 		}
14057 	} else if (CTL_HA_STATE_IS_HA(c->state)
14058 		&& CTL_HA_STATE_IS_SINGLE(state)){
14059 		// HA->SINGLE transition
14060 	        ctl_failover();
14061 		ctl_is_single = 1;
14062 	} else {
14063 		printf("ctl_isc_start:Invalid state transition %X->%X\n",
14064 		       c->state, state);
14065 		ret = CTL_HA_COMP_STATUS_ERROR;
14066 	}
14067 	if (CTL_HA_STATE_IS_SINGLE(state))
14068 		ctl_is_single = 1;
14069 
14070 	c->state = state;
14071 	c->status = ret;
14072 	return ret;
14073 }
14074 
14075 /*
14076  * Quiesce component
14077  * The component must clear any error conditions (set status to OK) and
14078  * prepare itself to another Start call
14079  * returns ctl_ha_comp_status:
14080  * 	OK
14081  *	ERROR
14082  */
14083 static ctl_ha_comp_status
14084 ctl_isc_quiesce(struct ctl_ha_component *c)
14085 {
14086 	int ret = CTL_HA_COMP_STATUS_OK;
14087 
14088 	ctl_pause_rtr = 1;
14089 	c->status = ret;
14090 	return ret;
14091 }
14092 
14093 struct ctl_ha_component ctl_ha_component_ctlisc =
14094 {
14095 	.name = "CTL ISC",
14096 	.state = CTL_HA_STATE_UNKNOWN,
14097 	.init = ctl_isc_init,
14098 	.start = ctl_isc_start,
14099 	.quiesce = ctl_isc_quiesce
14100 };
14101 
14102 /*
14103  *  vim: ts=8
14104  */
14105