xref: /freebsd/sys/cam/ctl/ctl.c (revision e72055b7feba695a760d45f01f0f8268b1cb4a74)
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*/ SCP_WCE | SCP_RCD,
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  * Extended INQUIRY Data (0x86), Mode Page Policy (0x87),
324  * SCSI Ports (0x88), Third-party Copy (0x8F), Block limits (0xB0),
325  * Block Device Characteristics (0xB1) and Logical Block Provisioning (0xB2)
326  */
327 #define SCSI_EVPD_NUM_SUPPORTED_PAGES	10
328 
329 static void ctl_isc_event_handler(ctl_ha_channel chanel, ctl_ha_event event,
330 				  int param);
331 static void ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest);
332 static int ctl_init(void);
333 void ctl_shutdown(void);
334 static int ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td);
335 static int ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td);
336 static void ctl_ioctl_online(void *arg);
337 static void ctl_ioctl_offline(void *arg);
338 static int ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id);
339 static int ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id);
340 static int ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio);
341 static int ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio);
342 static int ctl_ioctl_submit_wait(union ctl_io *io);
343 static void ctl_ioctl_datamove(union ctl_io *io);
344 static void ctl_ioctl_done(union ctl_io *io);
345 static void ctl_ioctl_hard_startstop_callback(void *arg,
346 					      struct cfi_metatask *metatask);
347 static void ctl_ioctl_bbrread_callback(void *arg,struct cfi_metatask *metatask);
348 static int ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
349 			      struct ctl_ooa *ooa_hdr,
350 			      struct ctl_ooa_entry *kern_entries);
351 static int ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
352 		     struct thread *td);
353 static uint32_t ctl_map_lun(int port_num, uint32_t lun);
354 static uint32_t ctl_map_lun_back(int port_num, uint32_t lun);
355 #ifdef unused
356 static union ctl_io *ctl_malloc_io(ctl_io_type io_type, uint32_t targ_port,
357 				   uint32_t targ_target, uint32_t targ_lun,
358 				   int can_wait);
359 static void ctl_kfree_io(union ctl_io *io);
360 #endif /* unused */
361 static int ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
362 			 struct ctl_be_lun *be_lun, struct ctl_id target_id);
363 static int ctl_free_lun(struct ctl_lun *lun);
364 static void ctl_create_lun(struct ctl_be_lun *be_lun);
365 /**
366 static void ctl_failover_change_pages(struct ctl_softc *softc,
367 				      struct ctl_scsiio *ctsio, int master);
368 **/
369 
370 static int ctl_do_mode_select(union ctl_io *io);
371 static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
372 			   uint64_t res_key, uint64_t sa_res_key,
373 			   uint8_t type, uint32_t residx,
374 			   struct ctl_scsiio *ctsio,
375 			   struct scsi_per_res_out *cdb,
376 			   struct scsi_per_res_out_parms* param);
377 static void ctl_pro_preempt_other(struct ctl_lun *lun,
378 				  union ctl_ha_msg *msg);
379 static void ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg);
380 static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
381 static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
382 static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
383 static int ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len);
384 static int ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len);
385 static int ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio,
386 					 int alloc_len);
387 static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
388 					 int alloc_len);
389 static int ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len);
390 static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
391 static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
392 static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
393 static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint32_t *len);
394 static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2);
395 static ctl_action ctl_check_for_blockage(union ctl_io *pending_io,
396 					 union ctl_io *ooa_io);
397 static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
398 				union ctl_io *starting_io);
399 static int ctl_check_blocked(struct ctl_lun *lun);
400 static int ctl_scsiio_lun_check(struct ctl_softc *ctl_softc,
401 				struct ctl_lun *lun,
402 				const struct ctl_cmd_entry *entry,
403 				struct ctl_scsiio *ctsio);
404 //static int ctl_check_rtr(union ctl_io *pending_io, struct ctl_softc *softc);
405 static void ctl_failover(void);
406 static int ctl_scsiio_precheck(struct ctl_softc *ctl_softc,
407 			       struct ctl_scsiio *ctsio);
408 static int ctl_scsiio(struct ctl_scsiio *ctsio);
409 
410 static int ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
411 static int ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
412 			    ctl_ua_type ua_type);
413 static int ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io,
414 			 ctl_ua_type ua_type);
415 static int ctl_abort_task(union ctl_io *io);
416 static int ctl_abort_task_set(union ctl_io *io);
417 static int ctl_i_t_nexus_reset(union ctl_io *io);
418 static void ctl_run_task(union ctl_io *io);
419 #ifdef CTL_IO_DELAY
420 static void ctl_datamove_timer_wakeup(void *arg);
421 static void ctl_done_timer_wakeup(void *arg);
422 #endif /* CTL_IO_DELAY */
423 
424 static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
425 static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
426 static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
427 static void ctl_datamove_remote_write(union ctl_io *io);
428 static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
429 static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
430 static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
431 static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
432 				    ctl_ha_dt_cb callback);
433 static void ctl_datamove_remote_read(union ctl_io *io);
434 static void ctl_datamove_remote(union ctl_io *io);
435 static int ctl_process_done(union ctl_io *io);
436 static void ctl_lun_thread(void *arg);
437 static void ctl_work_thread(void *arg);
438 static void ctl_enqueue_incoming(union ctl_io *io);
439 static void ctl_enqueue_rtr(union ctl_io *io);
440 static void ctl_enqueue_done(union ctl_io *io);
441 static void ctl_enqueue_isc(union ctl_io *io);
442 static const struct ctl_cmd_entry *
443     ctl_get_cmd_entry(struct ctl_scsiio *ctsio);
444 static const struct ctl_cmd_entry *
445     ctl_validate_command(struct ctl_scsiio *ctsio);
446 static int ctl_cmd_applicable(uint8_t lun_type,
447     const struct ctl_cmd_entry *entry);
448 
449 /*
450  * Load the serialization table.  This isn't very pretty, but is probably
451  * the easiest way to do it.
452  */
453 #include "ctl_ser_table.c"
454 
455 /*
456  * We only need to define open, close and ioctl routines for this driver.
457  */
458 static struct cdevsw ctl_cdevsw = {
459 	.d_version =	D_VERSION,
460 	.d_flags =	0,
461 	.d_open =	ctl_open,
462 	.d_close =	ctl_close,
463 	.d_ioctl =	ctl_ioctl,
464 	.d_name =	"ctl",
465 };
466 
467 
468 MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
469 MALLOC_DEFINE(M_CTLIO, "ctlio", "Memory used for CTL requests");
470 
471 static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
472 
473 static moduledata_t ctl_moduledata = {
474 	"ctl",
475 	ctl_module_event_handler,
476 	NULL
477 };
478 
479 DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
480 MODULE_VERSION(ctl, 1);
481 
482 static struct ctl_frontend ioctl_frontend =
483 {
484 	.name = "ioctl",
485 };
486 
487 static void
488 ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
489 			    union ctl_ha_msg *msg_info)
490 {
491 	struct ctl_scsiio *ctsio;
492 
493 	if (msg_info->hdr.original_sc == NULL) {
494 		printf("%s: original_sc == NULL!\n", __func__);
495 		/* XXX KDM now what? */
496 		return;
497 	}
498 
499 	ctsio = &msg_info->hdr.original_sc->scsiio;
500 	ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
501 	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
502 	ctsio->io_hdr.status = msg_info->hdr.status;
503 	ctsio->scsi_status = msg_info->scsi.scsi_status;
504 	ctsio->sense_len = msg_info->scsi.sense_len;
505 	ctsio->sense_residual = msg_info->scsi.sense_residual;
506 	ctsio->residual = msg_info->scsi.residual;
507 	memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
508 	       sizeof(ctsio->sense_data));
509 	memcpy(&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
510 	       &msg_info->scsi.lbalen, sizeof(msg_info->scsi.lbalen));
511 	ctl_enqueue_isc((union ctl_io *)ctsio);
512 }
513 
514 static void
515 ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
516 				union ctl_ha_msg *msg_info)
517 {
518 	struct ctl_scsiio *ctsio;
519 
520 	if (msg_info->hdr.serializing_sc == NULL) {
521 		printf("%s: serializing_sc == NULL!\n", __func__);
522 		/* XXX KDM now what? */
523 		return;
524 	}
525 
526 	ctsio = &msg_info->hdr.serializing_sc->scsiio;
527 #if 0
528 	/*
529 	 * Attempt to catch the situation where an I/O has
530 	 * been freed, and we're using it again.
531 	 */
532 	if (ctsio->io_hdr.io_type == 0xff) {
533 		union ctl_io *tmp_io;
534 		tmp_io = (union ctl_io *)ctsio;
535 		printf("%s: %p use after free!\n", __func__,
536 		       ctsio);
537 		printf("%s: type %d msg %d cdb %x iptl: "
538 		       "%d:%d:%d:%d tag 0x%04x "
539 		       "flag %#x status %x\n",
540 			__func__,
541 			tmp_io->io_hdr.io_type,
542 			tmp_io->io_hdr.msg_type,
543 			tmp_io->scsiio.cdb[0],
544 			tmp_io->io_hdr.nexus.initid.id,
545 			tmp_io->io_hdr.nexus.targ_port,
546 			tmp_io->io_hdr.nexus.targ_target.id,
547 			tmp_io->io_hdr.nexus.targ_lun,
548 			(tmp_io->io_hdr.io_type ==
549 			CTL_IO_TASK) ?
550 			tmp_io->taskio.tag_num :
551 			tmp_io->scsiio.tag_num,
552 		        tmp_io->io_hdr.flags,
553 			tmp_io->io_hdr.status);
554 	}
555 #endif
556 	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
557 	ctl_enqueue_isc((union ctl_io *)ctsio);
558 }
559 
560 /*
561  * ISC (Inter Shelf Communication) event handler.  Events from the HA
562  * subsystem come in here.
563  */
564 static void
565 ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
566 {
567 	struct ctl_softc *ctl_softc;
568 	union ctl_io *io;
569 	struct ctl_prio *presio;
570 	ctl_ha_status isc_status;
571 
572 	ctl_softc = control_softc;
573 	io = NULL;
574 
575 
576 #if 0
577 	printf("CTL: Isc Msg event %d\n", event);
578 #endif
579 	if (event == CTL_HA_EVT_MSG_RECV) {
580 		union ctl_ha_msg msg_info;
581 
582 		isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
583 					     sizeof(msg_info), /*wait*/ 0);
584 #if 0
585 		printf("CTL: msg_type %d\n", msg_info.msg_type);
586 #endif
587 		if (isc_status != 0) {
588 			printf("Error receiving message, status = %d\n",
589 			       isc_status);
590 			return;
591 		}
592 
593 		switch (msg_info.hdr.msg_type) {
594 		case CTL_MSG_SERIALIZE:
595 #if 0
596 			printf("Serialize\n");
597 #endif
598 			io = ctl_alloc_io((void *)ctl_softc->othersc_pool);
599 			if (io == NULL) {
600 				printf("ctl_isc_event_handler: can't allocate "
601 				       "ctl_io!\n");
602 				/* Bad Juju */
603 				/* Need to set busy and send msg back */
604 				msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
605 				msg_info.hdr.status = CTL_SCSI_ERROR;
606 				msg_info.scsi.scsi_status = SCSI_STATUS_BUSY;
607 				msg_info.scsi.sense_len = 0;
608 			        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
609 				    sizeof(msg_info), 0) > CTL_HA_STATUS_SUCCESS){
610 				}
611 				goto bailout;
612 			}
613 			ctl_zero_io(io);
614 			// populate ctsio from msg_info
615 			io->io_hdr.io_type = CTL_IO_SCSI;
616 			io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
617 			io->io_hdr.original_sc = msg_info.hdr.original_sc;
618 #if 0
619 			printf("pOrig %x\n", (int)msg_info.original_sc);
620 #endif
621 			io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
622 					    CTL_FLAG_IO_ACTIVE;
623 			/*
624 			 * If we're in serialization-only mode, we don't
625 			 * want to go through full done processing.  Thus
626 			 * the COPY flag.
627 			 *
628 			 * XXX KDM add another flag that is more specific.
629 			 */
630 			if (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)
631 				io->io_hdr.flags |= CTL_FLAG_INT_COPY;
632 			io->io_hdr.nexus = msg_info.hdr.nexus;
633 #if 0
634 			printf("targ %d, port %d, iid %d, lun %d\n",
635 			       io->io_hdr.nexus.targ_target.id,
636 			       io->io_hdr.nexus.targ_port,
637 			       io->io_hdr.nexus.initid.id,
638 			       io->io_hdr.nexus.targ_lun);
639 #endif
640 			io->scsiio.tag_num = msg_info.scsi.tag_num;
641 			io->scsiio.tag_type = msg_info.scsi.tag_type;
642 			memcpy(io->scsiio.cdb, msg_info.scsi.cdb,
643 			       CTL_MAX_CDBLEN);
644 			if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
645 				const struct ctl_cmd_entry *entry;
646 
647 				entry = ctl_get_cmd_entry(&io->scsiio);
648 				io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
649 				io->io_hdr.flags |=
650 					entry->flags & CTL_FLAG_DATA_MASK;
651 			}
652 			ctl_enqueue_isc(io);
653 			break;
654 
655 		/* Performed on the Originating SC, XFER mode only */
656 		case CTL_MSG_DATAMOVE: {
657 			struct ctl_sg_entry *sgl;
658 			int i, j;
659 
660 			io = msg_info.hdr.original_sc;
661 			if (io == NULL) {
662 				printf("%s: original_sc == NULL!\n", __func__);
663 				/* XXX KDM do something here */
664 				break;
665 			}
666 			io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
667 			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
668 			/*
669 			 * Keep track of this, we need to send it back over
670 			 * when the datamove is complete.
671 			 */
672 			io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
673 
674 			if (msg_info.dt.sg_sequence == 0) {
675 				/*
676 				 * XXX KDM we use the preallocated S/G list
677 				 * here, but we'll need to change this to
678 				 * dynamic allocation if we need larger S/G
679 				 * lists.
680 				 */
681 				if (msg_info.dt.kern_sg_entries >
682 				    sizeof(io->io_hdr.remote_sglist) /
683 				    sizeof(io->io_hdr.remote_sglist[0])) {
684 					printf("%s: number of S/G entries "
685 					    "needed %u > allocated num %zd\n",
686 					    __func__,
687 					    msg_info.dt.kern_sg_entries,
688 					    sizeof(io->io_hdr.remote_sglist)/
689 					    sizeof(io->io_hdr.remote_sglist[0]));
690 
691 					/*
692 					 * XXX KDM send a message back to
693 					 * the other side to shut down the
694 					 * DMA.  The error will come back
695 					 * through via the normal channel.
696 					 */
697 					break;
698 				}
699 				sgl = io->io_hdr.remote_sglist;
700 				memset(sgl, 0,
701 				       sizeof(io->io_hdr.remote_sglist));
702 
703 				io->scsiio.kern_data_ptr = (uint8_t *)sgl;
704 
705 				io->scsiio.kern_sg_entries =
706 					msg_info.dt.kern_sg_entries;
707 				io->scsiio.rem_sg_entries =
708 					msg_info.dt.kern_sg_entries;
709 				io->scsiio.kern_data_len =
710 					msg_info.dt.kern_data_len;
711 				io->scsiio.kern_total_len =
712 					msg_info.dt.kern_total_len;
713 				io->scsiio.kern_data_resid =
714 					msg_info.dt.kern_data_resid;
715 				io->scsiio.kern_rel_offset =
716 					msg_info.dt.kern_rel_offset;
717 				/*
718 				 * Clear out per-DMA flags.
719 				 */
720 				io->io_hdr.flags &= ~CTL_FLAG_RDMA_MASK;
721 				/*
722 				 * Add per-DMA flags that are set for this
723 				 * particular DMA request.
724 				 */
725 				io->io_hdr.flags |= msg_info.dt.flags &
726 						    CTL_FLAG_RDMA_MASK;
727 			} else
728 				sgl = (struct ctl_sg_entry *)
729 					io->scsiio.kern_data_ptr;
730 
731 			for (i = msg_info.dt.sent_sg_entries, j = 0;
732 			     i < (msg_info.dt.sent_sg_entries +
733 			     msg_info.dt.cur_sg_entries); i++, j++) {
734 				sgl[i].addr = msg_info.dt.sg_list[j].addr;
735 				sgl[i].len = msg_info.dt.sg_list[j].len;
736 
737 #if 0
738 				printf("%s: L: %p,%d -> %p,%d j=%d, i=%d\n",
739 				       __func__,
740 				       msg_info.dt.sg_list[j].addr,
741 				       msg_info.dt.sg_list[j].len,
742 				       sgl[i].addr, sgl[i].len, j, i);
743 #endif
744 			}
745 #if 0
746 			memcpy(&sgl[msg_info.dt.sent_sg_entries],
747 			       msg_info.dt.sg_list,
748 			       sizeof(*sgl) * msg_info.dt.cur_sg_entries);
749 #endif
750 
751 			/*
752 			 * If this is the last piece of the I/O, we've got
753 			 * the full S/G list.  Queue processing in the thread.
754 			 * Otherwise wait for the next piece.
755 			 */
756 			if (msg_info.dt.sg_last != 0)
757 				ctl_enqueue_isc(io);
758 			break;
759 		}
760 		/* Performed on the Serializing (primary) SC, XFER mode only */
761 		case CTL_MSG_DATAMOVE_DONE: {
762 			if (msg_info.hdr.serializing_sc == NULL) {
763 				printf("%s: serializing_sc == NULL!\n",
764 				       __func__);
765 				/* XXX KDM now what? */
766 				break;
767 			}
768 			/*
769 			 * We grab the sense information here in case
770 			 * there was a failure, so we can return status
771 			 * back to the initiator.
772 			 */
773 			io = msg_info.hdr.serializing_sc;
774 			io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
775 			io->io_hdr.status = msg_info.hdr.status;
776 			io->scsiio.scsi_status = msg_info.scsi.scsi_status;
777 			io->scsiio.sense_len = msg_info.scsi.sense_len;
778 			io->scsiio.sense_residual =msg_info.scsi.sense_residual;
779 			io->io_hdr.port_status = msg_info.scsi.fetd_status;
780 			io->scsiio.residual = msg_info.scsi.residual;
781 			memcpy(&io->scsiio.sense_data,&msg_info.scsi.sense_data,
782 			       sizeof(io->scsiio.sense_data));
783 			ctl_enqueue_isc(io);
784 			break;
785 		}
786 
787 		/* Preformed on Originating SC, SER_ONLY mode */
788 		case CTL_MSG_R2R:
789 			io = msg_info.hdr.original_sc;
790 			if (io == NULL) {
791 				printf("%s: Major Bummer\n", __func__);
792 				return;
793 			} else {
794 #if 0
795 				printf("pOrig %x\n",(int) ctsio);
796 #endif
797 			}
798 			io->io_hdr.msg_type = CTL_MSG_R2R;
799 			io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
800 			ctl_enqueue_isc(io);
801 			break;
802 
803 		/*
804 		 * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
805 		 * mode.
806 		 * Performed on the Originating (i.e. secondary) SC in XFER
807 		 * mode
808 		 */
809 		case CTL_MSG_FINISH_IO:
810 			if (ctl_softc->ha_mode == CTL_HA_MODE_XFER)
811 				ctl_isc_handler_finish_xfer(ctl_softc,
812 							    &msg_info);
813 			else
814 				ctl_isc_handler_finish_ser_only(ctl_softc,
815 								&msg_info);
816 			break;
817 
818 		/* Preformed on Originating SC */
819 		case CTL_MSG_BAD_JUJU:
820 			io = msg_info.hdr.original_sc;
821 			if (io == NULL) {
822 				printf("%s: Bad JUJU!, original_sc is NULL!\n",
823 				       __func__);
824 				break;
825 			}
826 			ctl_copy_sense_data(&msg_info, io);
827 			/*
828 			 * IO should have already been cleaned up on other
829 			 * SC so clear this flag so we won't send a message
830 			 * back to finish the IO there.
831 			 */
832 			io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
833 			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
834 
835 			/* io = msg_info.hdr.serializing_sc; */
836 			io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
837 			ctl_enqueue_isc(io);
838 			break;
839 
840 		/* Handle resets sent from the other side */
841 		case CTL_MSG_MANAGE_TASKS: {
842 			struct ctl_taskio *taskio;
843 			taskio = (struct ctl_taskio *)ctl_alloc_io(
844 				(void *)ctl_softc->othersc_pool);
845 			if (taskio == NULL) {
846 				printf("ctl_isc_event_handler: can't allocate "
847 				       "ctl_io!\n");
848 				/* Bad Juju */
849 				/* should I just call the proper reset func
850 				   here??? */
851 				goto bailout;
852 			}
853 			ctl_zero_io((union ctl_io *)taskio);
854 			taskio->io_hdr.io_type = CTL_IO_TASK;
855 			taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
856 			taskio->io_hdr.nexus = msg_info.hdr.nexus;
857 			taskio->task_action = msg_info.task.task_action;
858 			taskio->tag_num = msg_info.task.tag_num;
859 			taskio->tag_type = msg_info.task.tag_type;
860 #ifdef CTL_TIME_IO
861 			taskio->io_hdr.start_time = time_uptime;
862 			getbintime(&taskio->io_hdr.start_bt);
863 #if 0
864 			cs_prof_gettime(&taskio->io_hdr.start_ticks);
865 #endif
866 #endif /* CTL_TIME_IO */
867 			ctl_run_task((union ctl_io *)taskio);
868 			break;
869 		}
870 		/* Persistent Reserve action which needs attention */
871 		case CTL_MSG_PERS_ACTION:
872 			presio = (struct ctl_prio *)ctl_alloc_io(
873 				(void *)ctl_softc->othersc_pool);
874 			if (presio == NULL) {
875 				printf("ctl_isc_event_handler: can't allocate "
876 				       "ctl_io!\n");
877 				/* Bad Juju */
878 				/* Need to set busy and send msg back */
879 				goto bailout;
880 			}
881 			ctl_zero_io((union ctl_io *)presio);
882 			presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
883 			presio->pr_msg = msg_info.pr;
884 			ctl_enqueue_isc((union ctl_io *)presio);
885 			break;
886 		case CTL_MSG_SYNC_FE:
887 			rcv_sync_msg = 1;
888 			break;
889 		case CTL_MSG_APS_LOCK: {
890 			// It's quicker to execute this then to
891 			// queue it.
892 			struct ctl_lun *lun;
893 			struct ctl_page_index *page_index;
894 			struct copan_aps_subpage *current_sp;
895 			uint32_t targ_lun;
896 
897 			targ_lun = msg_info.hdr.nexus.targ_mapped_lun;
898 			lun = ctl_softc->ctl_luns[targ_lun];
899 			mtx_lock(&lun->lun_lock);
900 			page_index = &lun->mode_pages.index[index_to_aps_page];
901 			current_sp = (struct copan_aps_subpage *)
902 				     (page_index->page_data +
903 				     (page_index->page_len * CTL_PAGE_CURRENT));
904 
905 			current_sp->lock_active = msg_info.aps.lock_flag;
906 			mtx_unlock(&lun->lun_lock);
907 		        break;
908 		}
909 		default:
910 		        printf("How did I get here?\n");
911 		}
912 	} else if (event == CTL_HA_EVT_MSG_SENT) {
913 		if (param != CTL_HA_STATUS_SUCCESS) {
914 			printf("Bad status from ctl_ha_msg_send status %d\n",
915 			       param);
916 		}
917 		return;
918 	} else if (event == CTL_HA_EVT_DISCONNECT) {
919 		printf("CTL: Got a disconnect from Isc\n");
920 		return;
921 	} else {
922 		printf("ctl_isc_event_handler: Unknown event %d\n", event);
923 		return;
924 	}
925 
926 bailout:
927 	return;
928 }
929 
930 static void
931 ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
932 {
933 	struct scsi_sense_data *sense;
934 
935 	sense = &dest->scsiio.sense_data;
936 	bcopy(&src->scsi.sense_data, sense, sizeof(*sense));
937 	dest->scsiio.scsi_status = src->scsi.scsi_status;
938 	dest->scsiio.sense_len = src->scsi.sense_len;
939 	dest->io_hdr.status = src->hdr.status;
940 }
941 
942 static int
943 ctl_init(void)
944 {
945 	struct ctl_softc *softc;
946 	struct ctl_io_pool *internal_pool, *emergency_pool, *other_pool;
947 	struct ctl_port *port;
948         uint8_t sc_id =0;
949 	int i, error, retval;
950 	//int isc_retval;
951 
952 	retval = 0;
953 	ctl_pause_rtr = 0;
954         rcv_sync_msg = 0;
955 
956 	control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
957 			       M_WAITOK | M_ZERO);
958 	softc = control_softc;
959 
960 	softc->dev = make_dev(&ctl_cdevsw, 0, UID_ROOT, GID_OPERATOR, 0600,
961 			      "cam/ctl");
962 
963 	softc->dev->si_drv1 = softc;
964 
965 	/*
966 	 * By default, return a "bad LUN" peripheral qualifier for unknown
967 	 * LUNs.  The user can override this default using the tunable or
968 	 * sysctl.  See the comment in ctl_inquiry_std() for more details.
969 	 */
970 	softc->inquiry_pq_no_lun = 1;
971 	TUNABLE_INT_FETCH("kern.cam.ctl.inquiry_pq_no_lun",
972 			  &softc->inquiry_pq_no_lun);
973 	sysctl_ctx_init(&softc->sysctl_ctx);
974 	softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
975 		SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
976 		CTLFLAG_RD, 0, "CAM Target Layer");
977 
978 	if (softc->sysctl_tree == NULL) {
979 		printf("%s: unable to allocate sysctl tree\n", __func__);
980 		destroy_dev(softc->dev);
981 		free(control_softc, M_DEVBUF);
982 		control_softc = NULL;
983 		return (ENOMEM);
984 	}
985 
986 	SYSCTL_ADD_INT(&softc->sysctl_ctx,
987 		       SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
988 		       "inquiry_pq_no_lun", CTLFLAG_RW,
989 		       &softc->inquiry_pq_no_lun, 0,
990 		       "Report no lun possible for invalid LUNs");
991 
992 	mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
993 	mtx_init(&softc->pool_lock, "CTL pool mutex", NULL, MTX_DEF);
994 	softc->open_count = 0;
995 
996 	/*
997 	 * Default to actually sending a SYNCHRONIZE CACHE command down to
998 	 * the drive.
999 	 */
1000 	softc->flags = CTL_FLAG_REAL_SYNC;
1001 
1002 	/*
1003 	 * In Copan's HA scheme, the "master" and "slave" roles are
1004 	 * figured out through the slot the controller is in.  Although it
1005 	 * is an active/active system, someone has to be in charge.
1006  	 */
1007 #ifdef NEEDTOPORT
1008         scmicro_rw(SCMICRO_GET_SHELF_ID, &sc_id);
1009 #endif
1010 
1011         if (sc_id == 0) {
1012 		softc->flags |= CTL_FLAG_MASTER_SHELF;
1013 		persis_offset = 0;
1014 	} else
1015 		persis_offset = CTL_MAX_INITIATORS;
1016 
1017 	/*
1018 	 * XXX KDM need to figure out where we want to get our target ID
1019 	 * and WWID.  Is it different on each port?
1020 	 */
1021 	softc->target.id = 0;
1022 	softc->target.wwid[0] = 0x12345678;
1023 	softc->target.wwid[1] = 0x87654321;
1024 	STAILQ_INIT(&softc->lun_list);
1025 	STAILQ_INIT(&softc->pending_lun_queue);
1026 	STAILQ_INIT(&softc->fe_list);
1027 	STAILQ_INIT(&softc->port_list);
1028 	STAILQ_INIT(&softc->be_list);
1029 	STAILQ_INIT(&softc->io_pools);
1030 	ctl_tpc_init(softc);
1031 
1032 	if (ctl_pool_create(softc, CTL_POOL_INTERNAL, CTL_POOL_ENTRIES_INTERNAL,
1033 			    &internal_pool)!= 0){
1034 		printf("ctl: can't allocate %d entry internal pool, "
1035 		       "exiting\n", CTL_POOL_ENTRIES_INTERNAL);
1036 		return (ENOMEM);
1037 	}
1038 
1039 	if (ctl_pool_create(softc, CTL_POOL_EMERGENCY,
1040 			    CTL_POOL_ENTRIES_EMERGENCY, &emergency_pool) != 0) {
1041 		printf("ctl: can't allocate %d entry emergency pool, "
1042 		       "exiting\n", CTL_POOL_ENTRIES_EMERGENCY);
1043 		ctl_pool_free(internal_pool);
1044 		return (ENOMEM);
1045 	}
1046 
1047 	if (ctl_pool_create(softc, CTL_POOL_4OTHERSC, CTL_POOL_ENTRIES_OTHER_SC,
1048 	                    &other_pool) != 0)
1049 	{
1050 		printf("ctl: can't allocate %d entry other SC pool, "
1051 		       "exiting\n", CTL_POOL_ENTRIES_OTHER_SC);
1052 		ctl_pool_free(internal_pool);
1053 		ctl_pool_free(emergency_pool);
1054 		return (ENOMEM);
1055 	}
1056 
1057 	softc->internal_pool = internal_pool;
1058 	softc->emergency_pool = emergency_pool;
1059 	softc->othersc_pool = other_pool;
1060 
1061 	if (worker_threads <= 0)
1062 		worker_threads = max(1, mp_ncpus / 4);
1063 	if (worker_threads > CTL_MAX_THREADS)
1064 		worker_threads = CTL_MAX_THREADS;
1065 
1066 	for (i = 0; i < worker_threads; i++) {
1067 		struct ctl_thread *thr = &softc->threads[i];
1068 
1069 		mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1070 		thr->ctl_softc = softc;
1071 		STAILQ_INIT(&thr->incoming_queue);
1072 		STAILQ_INIT(&thr->rtr_queue);
1073 		STAILQ_INIT(&thr->done_queue);
1074 		STAILQ_INIT(&thr->isc_queue);
1075 
1076 		error = kproc_kthread_add(ctl_work_thread, thr,
1077 		    &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1078 		if (error != 0) {
1079 			printf("error creating CTL work thread!\n");
1080 			ctl_pool_free(internal_pool);
1081 			ctl_pool_free(emergency_pool);
1082 			ctl_pool_free(other_pool);
1083 			return (error);
1084 		}
1085 	}
1086 	error = kproc_kthread_add(ctl_lun_thread, softc,
1087 	    &softc->ctl_proc, NULL, 0, 0, "ctl", "lun");
1088 	if (error != 0) {
1089 		printf("error creating CTL lun thread!\n");
1090 		ctl_pool_free(internal_pool);
1091 		ctl_pool_free(emergency_pool);
1092 		ctl_pool_free(other_pool);
1093 		return (error);
1094 	}
1095 	if (bootverbose)
1096 		printf("ctl: CAM Target Layer loaded\n");
1097 
1098 	/*
1099 	 * Initialize the ioctl front end.
1100 	 */
1101 	ctl_frontend_register(&ioctl_frontend);
1102 	port = &softc->ioctl_info.port;
1103 	port->frontend = &ioctl_frontend;
1104 	sprintf(softc->ioctl_info.port_name, "ioctl");
1105 	port->port_type = CTL_PORT_IOCTL;
1106 	port->num_requested_ctl_io = 100;
1107 	port->port_name = softc->ioctl_info.port_name;
1108 	port->port_online = ctl_ioctl_online;
1109 	port->port_offline = ctl_ioctl_offline;
1110 	port->onoff_arg = &softc->ioctl_info;
1111 	port->lun_enable = ctl_ioctl_lun_enable;
1112 	port->lun_disable = ctl_ioctl_lun_disable;
1113 	port->targ_lun_arg = &softc->ioctl_info;
1114 	port->fe_datamove = ctl_ioctl_datamove;
1115 	port->fe_done = ctl_ioctl_done;
1116 	port->max_targets = 15;
1117 	port->max_target_id = 15;
1118 
1119 	if (ctl_port_register(&softc->ioctl_info.port,
1120 	                  (softc->flags & CTL_FLAG_MASTER_SHELF)) != 0) {
1121 		printf("ctl: ioctl front end registration failed, will "
1122 		       "continue anyway\n");
1123 	}
1124 
1125 #ifdef CTL_IO_DELAY
1126 	if (sizeof(struct callout) > CTL_TIMER_BYTES) {
1127 		printf("sizeof(struct callout) %zd > CTL_TIMER_BYTES %zd\n",
1128 		       sizeof(struct callout), CTL_TIMER_BYTES);
1129 		return (EINVAL);
1130 	}
1131 #endif /* CTL_IO_DELAY */
1132 
1133 	return (0);
1134 }
1135 
1136 void
1137 ctl_shutdown(void)
1138 {
1139 	struct ctl_softc *softc;
1140 	struct ctl_lun *lun, *next_lun;
1141 	struct ctl_io_pool *pool;
1142 
1143 	softc = (struct ctl_softc *)control_softc;
1144 
1145 	if (ctl_port_deregister(&softc->ioctl_info.port) != 0)
1146 		printf("ctl: ioctl front end deregistration failed\n");
1147 
1148 	mtx_lock(&softc->ctl_lock);
1149 
1150 	/*
1151 	 * Free up each LUN.
1152 	 */
1153 	for (lun = STAILQ_FIRST(&softc->lun_list); lun != NULL; lun = next_lun){
1154 		next_lun = STAILQ_NEXT(lun, links);
1155 		ctl_free_lun(lun);
1156 	}
1157 
1158 	mtx_unlock(&softc->ctl_lock);
1159 
1160 	ctl_frontend_deregister(&ioctl_frontend);
1161 
1162 	/*
1163 	 * This will rip the rug out from under any FETDs or anyone else
1164 	 * that has a pool allocated.  Since we increment our module
1165 	 * refcount any time someone outside the main CTL module allocates
1166 	 * a pool, we shouldn't have any problems here.  The user won't be
1167 	 * able to unload the CTL module until client modules have
1168 	 * successfully unloaded.
1169 	 */
1170 	while ((pool = STAILQ_FIRST(&softc->io_pools)) != NULL)
1171 		ctl_pool_free(pool);
1172 
1173 #if 0
1174 	ctl_shutdown_thread(softc->work_thread);
1175 	mtx_destroy(&softc->queue_lock);
1176 #endif
1177 
1178 	ctl_tpc_shutdown(softc);
1179 	mtx_destroy(&softc->pool_lock);
1180 	mtx_destroy(&softc->ctl_lock);
1181 
1182 	destroy_dev(softc->dev);
1183 
1184 	sysctl_ctx_free(&softc->sysctl_ctx);
1185 
1186 	free(control_softc, M_DEVBUF);
1187 	control_softc = NULL;
1188 
1189 	if (bootverbose)
1190 		printf("ctl: CAM Target Layer unloaded\n");
1191 }
1192 
1193 static int
1194 ctl_module_event_handler(module_t mod, int what, void *arg)
1195 {
1196 
1197 	switch (what) {
1198 	case MOD_LOAD:
1199 		return (ctl_init());
1200 	case MOD_UNLOAD:
1201 		return (EBUSY);
1202 	default:
1203 		return (EOPNOTSUPP);
1204 	}
1205 }
1206 
1207 /*
1208  * XXX KDM should we do some access checks here?  Bump a reference count to
1209  * prevent a CTL module from being unloaded while someone has it open?
1210  */
1211 static int
1212 ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
1213 {
1214 	return (0);
1215 }
1216 
1217 static int
1218 ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
1219 {
1220 	return (0);
1221 }
1222 
1223 int
1224 ctl_port_enable(ctl_port_type port_type)
1225 {
1226 	struct ctl_softc *softc;
1227 	struct ctl_port *port;
1228 
1229 	if (ctl_is_single == 0) {
1230 		union ctl_ha_msg msg_info;
1231 		int isc_retval;
1232 
1233 #if 0
1234 		printf("%s: HA mode, synchronizing frontend enable\n",
1235 		        __func__);
1236 #endif
1237 		msg_info.hdr.msg_type = CTL_MSG_SYNC_FE;
1238 	        if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1239 		        sizeof(msg_info), 1 )) > CTL_HA_STATUS_SUCCESS) {
1240 			printf("Sync msg send error retval %d\n", isc_retval);
1241 		}
1242 		if (!rcv_sync_msg) {
1243 			isc_retval=ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
1244 			        sizeof(msg_info), 1);
1245 		}
1246 #if 0
1247         	printf("CTL:Frontend Enable\n");
1248 	} else {
1249 		printf("%s: single mode, skipping frontend synchronization\n",
1250 		        __func__);
1251 #endif
1252 	}
1253 
1254 	softc = control_softc;
1255 
1256 	STAILQ_FOREACH(port, &softc->port_list, links) {
1257 		if (port_type & port->port_type)
1258 		{
1259 #if 0
1260 			printf("port %d\n", port->targ_port);
1261 #endif
1262 			ctl_port_online(port);
1263 		}
1264 	}
1265 
1266 	return (0);
1267 }
1268 
1269 int
1270 ctl_port_disable(ctl_port_type port_type)
1271 {
1272 	struct ctl_softc *softc;
1273 	struct ctl_port *port;
1274 
1275 	softc = control_softc;
1276 
1277 	STAILQ_FOREACH(port, &softc->port_list, links) {
1278 		if (port_type & port->port_type)
1279 			ctl_port_offline(port);
1280 	}
1281 
1282 	return (0);
1283 }
1284 
1285 /*
1286  * Returns 0 for success, 1 for failure.
1287  * Currently the only failure mode is if there aren't enough entries
1288  * allocated.  So, in case of a failure, look at num_entries_dropped,
1289  * reallocate and try again.
1290  */
1291 int
1292 ctl_port_list(struct ctl_port_entry *entries, int num_entries_alloced,
1293 	      int *num_entries_filled, int *num_entries_dropped,
1294 	      ctl_port_type port_type, int no_virtual)
1295 {
1296 	struct ctl_softc *softc;
1297 	struct ctl_port *port;
1298 	int entries_dropped, entries_filled;
1299 	int retval;
1300 	int i;
1301 
1302 	softc = control_softc;
1303 
1304 	retval = 0;
1305 	entries_filled = 0;
1306 	entries_dropped = 0;
1307 
1308 	i = 0;
1309 	mtx_lock(&softc->ctl_lock);
1310 	STAILQ_FOREACH(port, &softc->port_list, links) {
1311 		struct ctl_port_entry *entry;
1312 
1313 		if ((port->port_type & port_type) == 0)
1314 			continue;
1315 
1316 		if ((no_virtual != 0)
1317 		 && (port->virtual_port != 0))
1318 			continue;
1319 
1320 		if (entries_filled >= num_entries_alloced) {
1321 			entries_dropped++;
1322 			continue;
1323 		}
1324 		entry = &entries[i];
1325 
1326 		entry->port_type = port->port_type;
1327 		strlcpy(entry->port_name, port->port_name,
1328 			sizeof(entry->port_name));
1329 		entry->physical_port = port->physical_port;
1330 		entry->virtual_port = port->virtual_port;
1331 		entry->wwnn = port->wwnn;
1332 		entry->wwpn = port->wwpn;
1333 
1334 		i++;
1335 		entries_filled++;
1336 	}
1337 
1338 	mtx_unlock(&softc->ctl_lock);
1339 
1340 	if (entries_dropped > 0)
1341 		retval = 1;
1342 
1343 	*num_entries_dropped = entries_dropped;
1344 	*num_entries_filled = entries_filled;
1345 
1346 	return (retval);
1347 }
1348 
1349 static void
1350 ctl_ioctl_online(void *arg)
1351 {
1352 	struct ctl_ioctl_info *ioctl_info;
1353 
1354 	ioctl_info = (struct ctl_ioctl_info *)arg;
1355 
1356 	ioctl_info->flags |= CTL_IOCTL_FLAG_ENABLED;
1357 }
1358 
1359 static void
1360 ctl_ioctl_offline(void *arg)
1361 {
1362 	struct ctl_ioctl_info *ioctl_info;
1363 
1364 	ioctl_info = (struct ctl_ioctl_info *)arg;
1365 
1366 	ioctl_info->flags &= ~CTL_IOCTL_FLAG_ENABLED;
1367 }
1368 
1369 /*
1370  * Remove an initiator by port number and initiator ID.
1371  * Returns 0 for success, -1 for failure.
1372  */
1373 int
1374 ctl_remove_initiator(struct ctl_port *port, int iid)
1375 {
1376 	struct ctl_softc *softc = control_softc;
1377 
1378 	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1379 
1380 	if (iid > CTL_MAX_INIT_PER_PORT) {
1381 		printf("%s: initiator ID %u > maximun %u!\n",
1382 		       __func__, iid, CTL_MAX_INIT_PER_PORT);
1383 		return (-1);
1384 	}
1385 
1386 	mtx_lock(&softc->ctl_lock);
1387 	port->wwpn_iid[iid].in_use--;
1388 	port->wwpn_iid[iid].last_use = time_uptime;
1389 	mtx_unlock(&softc->ctl_lock);
1390 
1391 	return (0);
1392 }
1393 
1394 /*
1395  * Add an initiator to the initiator map.
1396  * Returns iid for success, < 0 for failure.
1397  */
1398 int
1399 ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
1400 {
1401 	struct ctl_softc *softc = control_softc;
1402 	time_t best_time;
1403 	int i, best;
1404 
1405 	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1406 
1407 	if (iid >= CTL_MAX_INIT_PER_PORT) {
1408 		printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
1409 		       __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
1410 		free(name, M_CTL);
1411 		return (-1);
1412 	}
1413 
1414 	mtx_lock(&softc->ctl_lock);
1415 
1416 	if (iid < 0 && (wwpn != 0 || name != NULL)) {
1417 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1418 			if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
1419 				iid = i;
1420 				break;
1421 			}
1422 			if (name != NULL && port->wwpn_iid[i].name != NULL &&
1423 			    strcmp(name, port->wwpn_iid[i].name) == 0) {
1424 				iid = i;
1425 				break;
1426 			}
1427 		}
1428 	}
1429 
1430 	if (iid < 0) {
1431 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1432 			if (port->wwpn_iid[i].in_use == 0 &&
1433 			    port->wwpn_iid[i].wwpn == 0 &&
1434 			    port->wwpn_iid[i].name == NULL) {
1435 				iid = i;
1436 				break;
1437 			}
1438 		}
1439 	}
1440 
1441 	if (iid < 0) {
1442 		best = -1;
1443 		best_time = INT32_MAX;
1444 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1445 			if (port->wwpn_iid[i].in_use == 0) {
1446 				if (port->wwpn_iid[i].last_use < best_time) {
1447 					best = i;
1448 					best_time = port->wwpn_iid[i].last_use;
1449 				}
1450 			}
1451 		}
1452 		iid = best;
1453 	}
1454 
1455 	if (iid < 0) {
1456 		mtx_unlock(&softc->ctl_lock);
1457 		free(name, M_CTL);
1458 		return (-2);
1459 	}
1460 
1461 	if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
1462 		/*
1463 		 * This is not an error yet.
1464 		 */
1465 		if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
1466 #if 0
1467 			printf("%s: port %d iid %u WWPN %#jx arrived"
1468 			    " again\n", __func__, port->targ_port,
1469 			    iid, (uintmax_t)wwpn);
1470 #endif
1471 			goto take;
1472 		}
1473 		if (name != NULL && port->wwpn_iid[iid].name != NULL &&
1474 		    strcmp(name, port->wwpn_iid[iid].name) == 0) {
1475 #if 0
1476 			printf("%s: port %d iid %u name '%s' arrived"
1477 			    " again\n", __func__, port->targ_port,
1478 			    iid, name);
1479 #endif
1480 			goto take;
1481 		}
1482 
1483 		/*
1484 		 * This is an error, but what do we do about it?  The
1485 		 * driver is telling us we have a new WWPN for this
1486 		 * initiator ID, so we pretty much need to use it.
1487 		 */
1488 		printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
1489 		    " but WWPN %#jx '%s' is still at that address\n",
1490 		    __func__, port->targ_port, iid, wwpn, name,
1491 		    (uintmax_t)port->wwpn_iid[iid].wwpn,
1492 		    port->wwpn_iid[iid].name);
1493 
1494 		/*
1495 		 * XXX KDM clear have_ca and ua_pending on each LUN for
1496 		 * this initiator.
1497 		 */
1498 	}
1499 take:
1500 	free(port->wwpn_iid[iid].name, M_CTL);
1501 	port->wwpn_iid[iid].name = name;
1502 	port->wwpn_iid[iid].wwpn = wwpn;
1503 	port->wwpn_iid[iid].in_use++;
1504 	mtx_unlock(&softc->ctl_lock);
1505 
1506 	return (iid);
1507 }
1508 
1509 static int
1510 ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
1511 {
1512 	int len;
1513 
1514 	switch (port->port_type) {
1515 	case CTL_PORT_FC:
1516 	{
1517 		struct scsi_transportid_fcp *id =
1518 		    (struct scsi_transportid_fcp *)buf;
1519 		if (port->wwpn_iid[iid].wwpn == 0)
1520 			return (0);
1521 		memset(id, 0, sizeof(*id));
1522 		id->format_protocol = SCSI_PROTO_FC;
1523 		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
1524 		return (sizeof(*id));
1525 	}
1526 	case CTL_PORT_ISCSI:
1527 	{
1528 		struct scsi_transportid_iscsi_port *id =
1529 		    (struct scsi_transportid_iscsi_port *)buf;
1530 		if (port->wwpn_iid[iid].name == NULL)
1531 			return (0);
1532 		memset(id, 0, 256);
1533 		id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
1534 		    SCSI_PROTO_ISCSI;
1535 		len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
1536 		len = roundup2(min(len, 252), 4);
1537 		scsi_ulto2b(len, id->additional_length);
1538 		return (sizeof(*id) + len);
1539 	}
1540 	case CTL_PORT_SAS:
1541 	{
1542 		struct scsi_transportid_sas *id =
1543 		    (struct scsi_transportid_sas *)buf;
1544 		if (port->wwpn_iid[iid].wwpn == 0)
1545 			return (0);
1546 		memset(id, 0, sizeof(*id));
1547 		id->format_protocol = SCSI_PROTO_SAS;
1548 		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
1549 		return (sizeof(*id));
1550 	}
1551 	default:
1552 	{
1553 		struct scsi_transportid_spi *id =
1554 		    (struct scsi_transportid_spi *)buf;
1555 		memset(id, 0, sizeof(*id));
1556 		id->format_protocol = SCSI_PROTO_SPI;
1557 		scsi_ulto2b(iid, id->scsi_addr);
1558 		scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
1559 		return (sizeof(*id));
1560 	}
1561 	}
1562 }
1563 
1564 static int
1565 ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id)
1566 {
1567 	return (0);
1568 }
1569 
1570 static int
1571 ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id)
1572 {
1573 	return (0);
1574 }
1575 
1576 /*
1577  * Data movement routine for the CTL ioctl frontend port.
1578  */
1579 static int
1580 ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio)
1581 {
1582 	struct ctl_sg_entry *ext_sglist, *kern_sglist;
1583 	struct ctl_sg_entry ext_entry, kern_entry;
1584 	int ext_sglen, ext_sg_entries, kern_sg_entries;
1585 	int ext_sg_start, ext_offset;
1586 	int len_to_copy, len_copied;
1587 	int kern_watermark, ext_watermark;
1588 	int ext_sglist_malloced;
1589 	int i, j;
1590 
1591 	ext_sglist_malloced = 0;
1592 	ext_sg_start = 0;
1593 	ext_offset = 0;
1594 
1595 	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove\n"));
1596 
1597 	/*
1598 	 * If this flag is set, fake the data transfer.
1599 	 */
1600 	if (ctsio->io_hdr.flags & CTL_FLAG_NO_DATAMOVE) {
1601 		ctsio->ext_data_filled = ctsio->ext_data_len;
1602 		goto bailout;
1603 	}
1604 
1605 	/*
1606 	 * To simplify things here, if we have a single buffer, stick it in
1607 	 * a S/G entry and just make it a single entry S/G list.
1608 	 */
1609 	if (ctsio->io_hdr.flags & CTL_FLAG_EDPTR_SGLIST) {
1610 		int len_seen;
1611 
1612 		ext_sglen = ctsio->ext_sg_entries * sizeof(*ext_sglist);
1613 
1614 		ext_sglist = (struct ctl_sg_entry *)malloc(ext_sglen, M_CTL,
1615 							   M_WAITOK);
1616 		ext_sglist_malloced = 1;
1617 		if (copyin(ctsio->ext_data_ptr, ext_sglist,
1618 				   ext_sglen) != 0) {
1619 			ctl_set_internal_failure(ctsio,
1620 						 /*sks_valid*/ 0,
1621 						 /*retry_count*/ 0);
1622 			goto bailout;
1623 		}
1624 		ext_sg_entries = ctsio->ext_sg_entries;
1625 		len_seen = 0;
1626 		for (i = 0; i < ext_sg_entries; i++) {
1627 			if ((len_seen + ext_sglist[i].len) >=
1628 			     ctsio->ext_data_filled) {
1629 				ext_sg_start = i;
1630 				ext_offset = ctsio->ext_data_filled - len_seen;
1631 				break;
1632 			}
1633 			len_seen += ext_sglist[i].len;
1634 		}
1635 	} else {
1636 		ext_sglist = &ext_entry;
1637 		ext_sglist->addr = ctsio->ext_data_ptr;
1638 		ext_sglist->len = ctsio->ext_data_len;
1639 		ext_sg_entries = 1;
1640 		ext_sg_start = 0;
1641 		ext_offset = ctsio->ext_data_filled;
1642 	}
1643 
1644 	if (ctsio->kern_sg_entries > 0) {
1645 		kern_sglist = (struct ctl_sg_entry *)ctsio->kern_data_ptr;
1646 		kern_sg_entries = ctsio->kern_sg_entries;
1647 	} else {
1648 		kern_sglist = &kern_entry;
1649 		kern_sglist->addr = ctsio->kern_data_ptr;
1650 		kern_sglist->len = ctsio->kern_data_len;
1651 		kern_sg_entries = 1;
1652 	}
1653 
1654 
1655 	kern_watermark = 0;
1656 	ext_watermark = ext_offset;
1657 	len_copied = 0;
1658 	for (i = ext_sg_start, j = 0;
1659 	     i < ext_sg_entries && j < kern_sg_entries;) {
1660 		uint8_t *ext_ptr, *kern_ptr;
1661 
1662 		len_to_copy = ctl_min(ext_sglist[i].len - ext_watermark,
1663 				      kern_sglist[j].len - kern_watermark);
1664 
1665 		ext_ptr = (uint8_t *)ext_sglist[i].addr;
1666 		ext_ptr = ext_ptr + ext_watermark;
1667 		if (ctsio->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
1668 			/*
1669 			 * XXX KDM fix this!
1670 			 */
1671 			panic("need to implement bus address support");
1672 #if 0
1673 			kern_ptr = bus_to_virt(kern_sglist[j].addr);
1674 #endif
1675 		} else
1676 			kern_ptr = (uint8_t *)kern_sglist[j].addr;
1677 		kern_ptr = kern_ptr + kern_watermark;
1678 
1679 		kern_watermark += len_to_copy;
1680 		ext_watermark += len_to_copy;
1681 
1682 		if ((ctsio->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
1683 		     CTL_FLAG_DATA_IN) {
1684 			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1685 					 "bytes to user\n", len_to_copy));
1686 			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1687 					 "to %p\n", kern_ptr, ext_ptr));
1688 			if (copyout(kern_ptr, ext_ptr, len_to_copy) != 0) {
1689 				ctl_set_internal_failure(ctsio,
1690 							 /*sks_valid*/ 0,
1691 							 /*retry_count*/ 0);
1692 				goto bailout;
1693 			}
1694 		} else {
1695 			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1696 					 "bytes from user\n", len_to_copy));
1697 			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1698 					 "to %p\n", ext_ptr, kern_ptr));
1699 			if (copyin(ext_ptr, kern_ptr, len_to_copy)!= 0){
1700 				ctl_set_internal_failure(ctsio,
1701 							 /*sks_valid*/ 0,
1702 							 /*retry_count*/0);
1703 				goto bailout;
1704 			}
1705 		}
1706 
1707 		len_copied += len_to_copy;
1708 
1709 		if (ext_sglist[i].len == ext_watermark) {
1710 			i++;
1711 			ext_watermark = 0;
1712 		}
1713 
1714 		if (kern_sglist[j].len == kern_watermark) {
1715 			j++;
1716 			kern_watermark = 0;
1717 		}
1718 	}
1719 
1720 	ctsio->ext_data_filled += len_copied;
1721 
1722 	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_sg_entries: %d, "
1723 			 "kern_sg_entries: %d\n", ext_sg_entries,
1724 			 kern_sg_entries));
1725 	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_data_len = %d, "
1726 			 "kern_data_len = %d\n", ctsio->ext_data_len,
1727 			 ctsio->kern_data_len));
1728 
1729 
1730 	/* XXX KDM set residual?? */
1731 bailout:
1732 
1733 	if (ext_sglist_malloced != 0)
1734 		free(ext_sglist, M_CTL);
1735 
1736 	return (CTL_RETVAL_COMPLETE);
1737 }
1738 
1739 /*
1740  * Serialize a command that went down the "wrong" side, and so was sent to
1741  * this controller for execution.  The logic is a little different than the
1742  * standard case in ctl_scsiio_precheck().  Errors in this case need to get
1743  * sent back to the other side, but in the success case, we execute the
1744  * command on this side (XFER mode) or tell the other side to execute it
1745  * (SER_ONLY mode).
1746  */
1747 static int
1748 ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
1749 {
1750 	struct ctl_softc *ctl_softc;
1751 	union ctl_ha_msg msg_info;
1752 	struct ctl_lun *lun;
1753 	int retval = 0;
1754 	uint32_t targ_lun;
1755 
1756 	ctl_softc = control_softc;
1757 
1758 	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
1759 	lun = ctl_softc->ctl_luns[targ_lun];
1760 	if (lun==NULL)
1761 	{
1762 		/*
1763 		 * Why isn't LUN defined? The other side wouldn't
1764 		 * send a cmd if the LUN is undefined.
1765 		 */
1766 		printf("%s: Bad JUJU!, LUN is NULL!\n", __func__);
1767 
1768 		/* "Logical unit not supported" */
1769 		ctl_set_sense_data(&msg_info.scsi.sense_data,
1770 				   lun,
1771 				   /*sense_format*/SSD_TYPE_NONE,
1772 				   /*current_error*/ 1,
1773 				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1774 				   /*asc*/ 0x25,
1775 				   /*ascq*/ 0x00,
1776 				   SSD_ELEM_NONE);
1777 
1778 		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1779 		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1780 		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1781 		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1782 		msg_info.hdr.serializing_sc = NULL;
1783 		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1784 	        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1785 				sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1786 		}
1787 		return(1);
1788 
1789 	}
1790 
1791 	mtx_lock(&lun->lun_lock);
1792     	TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1793 
1794 	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
1795 		(union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
1796 		 ooa_links))) {
1797 	case CTL_ACTION_BLOCK:
1798 		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
1799 		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
1800 				  blocked_links);
1801 		break;
1802 	case CTL_ACTION_PASS:
1803 	case CTL_ACTION_SKIP:
1804 		if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
1805 			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
1806 			ctl_enqueue_rtr((union ctl_io *)ctsio);
1807 		} else {
1808 
1809 			/* send msg back to other side */
1810 			msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1811 			msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
1812 			msg_info.hdr.msg_type = CTL_MSG_R2R;
1813 #if 0
1814 			printf("2. pOrig %x\n", (int)msg_info.hdr.original_sc);
1815 #endif
1816 		        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1817 			    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1818 			}
1819 		}
1820 		break;
1821 	case CTL_ACTION_OVERLAP:
1822 		/* OVERLAPPED COMMANDS ATTEMPTED */
1823 		ctl_set_sense_data(&msg_info.scsi.sense_data,
1824 				   lun,
1825 				   /*sense_format*/SSD_TYPE_NONE,
1826 				   /*current_error*/ 1,
1827 				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1828 				   /*asc*/ 0x4E,
1829 				   /*ascq*/ 0x00,
1830 				   SSD_ELEM_NONE);
1831 
1832 		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1833 		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1834 		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1835 		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1836 		msg_info.hdr.serializing_sc = NULL;
1837 		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1838 #if 0
1839 		printf("BAD JUJU:Major Bummer Overlap\n");
1840 #endif
1841 		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1842 		retval = 1;
1843 		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1844 		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1845 		}
1846 		break;
1847 	case CTL_ACTION_OVERLAP_TAG:
1848 		/* TAGGED OVERLAPPED COMMANDS (NN = QUEUE TAG) */
1849 		ctl_set_sense_data(&msg_info.scsi.sense_data,
1850 				   lun,
1851 				   /*sense_format*/SSD_TYPE_NONE,
1852 				   /*current_error*/ 1,
1853 				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1854 				   /*asc*/ 0x4D,
1855 				   /*ascq*/ ctsio->tag_num & 0xff,
1856 				   SSD_ELEM_NONE);
1857 
1858 		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1859 		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1860 		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1861 		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1862 		msg_info.hdr.serializing_sc = NULL;
1863 		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1864 #if 0
1865 		printf("BAD JUJU:Major Bummer Overlap Tag\n");
1866 #endif
1867 		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1868 		retval = 1;
1869 		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1870 		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1871 		}
1872 		break;
1873 	case CTL_ACTION_ERROR:
1874 	default:
1875 		/* "Internal target failure" */
1876 		ctl_set_sense_data(&msg_info.scsi.sense_data,
1877 				   lun,
1878 				   /*sense_format*/SSD_TYPE_NONE,
1879 				   /*current_error*/ 1,
1880 				   /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
1881 				   /*asc*/ 0x44,
1882 				   /*ascq*/ 0x00,
1883 				   SSD_ELEM_NONE);
1884 
1885 		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1886 		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1887 		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1888 		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1889 		msg_info.hdr.serializing_sc = NULL;
1890 		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1891 #if 0
1892 		printf("BAD JUJU:Major Bummer HW Error\n");
1893 #endif
1894 		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1895 		retval = 1;
1896 		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1897 		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1898 		}
1899 		break;
1900 	}
1901 	mtx_unlock(&lun->lun_lock);
1902 	return (retval);
1903 }
1904 
1905 static int
1906 ctl_ioctl_submit_wait(union ctl_io *io)
1907 {
1908 	struct ctl_fe_ioctl_params params;
1909 	ctl_fe_ioctl_state last_state;
1910 	int done, retval;
1911 
1912 	retval = 0;
1913 
1914 	bzero(&params, sizeof(params));
1915 
1916 	mtx_init(&params.ioctl_mtx, "ctliocmtx", NULL, MTX_DEF);
1917 	cv_init(&params.sem, "ctlioccv");
1918 	params.state = CTL_IOCTL_INPROG;
1919 	last_state = params.state;
1920 
1921 	io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr = &params;
1922 
1923 	CTL_DEBUG_PRINT(("ctl_ioctl_submit_wait\n"));
1924 
1925 	/* This shouldn't happen */
1926 	if ((retval = ctl_queue(io)) != CTL_RETVAL_COMPLETE)
1927 		return (retval);
1928 
1929 	done = 0;
1930 
1931 	do {
1932 		mtx_lock(&params.ioctl_mtx);
1933 		/*
1934 		 * Check the state here, and don't sleep if the state has
1935 		 * already changed (i.e. wakeup has already occured, but we
1936 		 * weren't waiting yet).
1937 		 */
1938 		if (params.state == last_state) {
1939 			/* XXX KDM cv_wait_sig instead? */
1940 			cv_wait(&params.sem, &params.ioctl_mtx);
1941 		}
1942 		last_state = params.state;
1943 
1944 		switch (params.state) {
1945 		case CTL_IOCTL_INPROG:
1946 			/* Why did we wake up? */
1947 			/* XXX KDM error here? */
1948 			mtx_unlock(&params.ioctl_mtx);
1949 			break;
1950 		case CTL_IOCTL_DATAMOVE:
1951 			CTL_DEBUG_PRINT(("got CTL_IOCTL_DATAMOVE\n"));
1952 
1953 			/*
1954 			 * change last_state back to INPROG to avoid
1955 			 * deadlock on subsequent data moves.
1956 			 */
1957 			params.state = last_state = CTL_IOCTL_INPROG;
1958 
1959 			mtx_unlock(&params.ioctl_mtx);
1960 			ctl_ioctl_do_datamove(&io->scsiio);
1961 			/*
1962 			 * Note that in some cases, most notably writes,
1963 			 * this will queue the I/O and call us back later.
1964 			 * In other cases, generally reads, this routine
1965 			 * will immediately call back and wake us up,
1966 			 * probably using our own context.
1967 			 */
1968 			io->scsiio.be_move_done(io);
1969 			break;
1970 		case CTL_IOCTL_DONE:
1971 			mtx_unlock(&params.ioctl_mtx);
1972 			CTL_DEBUG_PRINT(("got CTL_IOCTL_DONE\n"));
1973 			done = 1;
1974 			break;
1975 		default:
1976 			mtx_unlock(&params.ioctl_mtx);
1977 			/* XXX KDM error here? */
1978 			break;
1979 		}
1980 	} while (done == 0);
1981 
1982 	mtx_destroy(&params.ioctl_mtx);
1983 	cv_destroy(&params.sem);
1984 
1985 	return (CTL_RETVAL_COMPLETE);
1986 }
1987 
1988 static void
1989 ctl_ioctl_datamove(union ctl_io *io)
1990 {
1991 	struct ctl_fe_ioctl_params *params;
1992 
1993 	params = (struct ctl_fe_ioctl_params *)
1994 		io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
1995 
1996 	mtx_lock(&params->ioctl_mtx);
1997 	params->state = CTL_IOCTL_DATAMOVE;
1998 	cv_broadcast(&params->sem);
1999 	mtx_unlock(&params->ioctl_mtx);
2000 }
2001 
2002 static void
2003 ctl_ioctl_done(union ctl_io *io)
2004 {
2005 	struct ctl_fe_ioctl_params *params;
2006 
2007 	params = (struct ctl_fe_ioctl_params *)
2008 		io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2009 
2010 	mtx_lock(&params->ioctl_mtx);
2011 	params->state = CTL_IOCTL_DONE;
2012 	cv_broadcast(&params->sem);
2013 	mtx_unlock(&params->ioctl_mtx);
2014 }
2015 
2016 static void
2017 ctl_ioctl_hard_startstop_callback(void *arg, struct cfi_metatask *metatask)
2018 {
2019 	struct ctl_fe_ioctl_startstop_info *sd_info;
2020 
2021 	sd_info = (struct ctl_fe_ioctl_startstop_info *)arg;
2022 
2023 	sd_info->hs_info.status = metatask->status;
2024 	sd_info->hs_info.total_luns = metatask->taskinfo.startstop.total_luns;
2025 	sd_info->hs_info.luns_complete =
2026 		metatask->taskinfo.startstop.luns_complete;
2027 	sd_info->hs_info.luns_failed = metatask->taskinfo.startstop.luns_failed;
2028 
2029 	cv_broadcast(&sd_info->sem);
2030 }
2031 
2032 static void
2033 ctl_ioctl_bbrread_callback(void *arg, struct cfi_metatask *metatask)
2034 {
2035 	struct ctl_fe_ioctl_bbrread_info *fe_bbr_info;
2036 
2037 	fe_bbr_info = (struct ctl_fe_ioctl_bbrread_info *)arg;
2038 
2039 	mtx_lock(fe_bbr_info->lock);
2040 	fe_bbr_info->bbr_info->status = metatask->status;
2041 	fe_bbr_info->bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2042 	fe_bbr_info->wakeup_done = 1;
2043 	mtx_unlock(fe_bbr_info->lock);
2044 
2045 	cv_broadcast(&fe_bbr_info->sem);
2046 }
2047 
2048 /*
2049  * Returns 0 for success, errno for failure.
2050  */
2051 static int
2052 ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2053 		   struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2054 {
2055 	union ctl_io *io;
2056 	int retval;
2057 
2058 	retval = 0;
2059 
2060 	mtx_lock(&lun->lun_lock);
2061 	for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
2062 	     (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2063 	     ooa_links)) {
2064 		struct ctl_ooa_entry *entry;
2065 
2066 		/*
2067 		 * If we've got more than we can fit, just count the
2068 		 * remaining entries.
2069 		 */
2070 		if (*cur_fill_num >= ooa_hdr->alloc_num)
2071 			continue;
2072 
2073 		entry = &kern_entries[*cur_fill_num];
2074 
2075 		entry->tag_num = io->scsiio.tag_num;
2076 		entry->lun_num = lun->lun;
2077 #ifdef CTL_TIME_IO
2078 		entry->start_bt = io->io_hdr.start_bt;
2079 #endif
2080 		bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2081 		entry->cdb_len = io->scsiio.cdb_len;
2082 		if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
2083 			entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2084 
2085 		if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2086 			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2087 
2088 		if (io->io_hdr.flags & CTL_FLAG_ABORT)
2089 			entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2090 
2091 		if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2092 			entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2093 
2094 		if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2095 			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2096 	}
2097 	mtx_unlock(&lun->lun_lock);
2098 
2099 	return (retval);
2100 }
2101 
2102 static void *
2103 ctl_copyin_alloc(void *user_addr, int len, char *error_str,
2104 		 size_t error_str_len)
2105 {
2106 	void *kptr;
2107 
2108 	kptr = malloc(len, M_CTL, M_WAITOK | M_ZERO);
2109 
2110 	if (copyin(user_addr, kptr, len) != 0) {
2111 		snprintf(error_str, error_str_len, "Error copying %d bytes "
2112 			 "from user address %p to kernel address %p", len,
2113 			 user_addr, kptr);
2114 		free(kptr, M_CTL);
2115 		return (NULL);
2116 	}
2117 
2118 	return (kptr);
2119 }
2120 
2121 static void
2122 ctl_free_args(int num_args, struct ctl_be_arg *args)
2123 {
2124 	int i;
2125 
2126 	if (args == NULL)
2127 		return;
2128 
2129 	for (i = 0; i < num_args; i++) {
2130 		free(args[i].kname, M_CTL);
2131 		free(args[i].kvalue, M_CTL);
2132 	}
2133 
2134 	free(args, M_CTL);
2135 }
2136 
2137 static struct ctl_be_arg *
2138 ctl_copyin_args(int num_args, struct ctl_be_arg *uargs,
2139 		char *error_str, size_t error_str_len)
2140 {
2141 	struct ctl_be_arg *args;
2142 	int i;
2143 
2144 	args = ctl_copyin_alloc(uargs, num_args * sizeof(*args),
2145 				error_str, error_str_len);
2146 
2147 	if (args == NULL)
2148 		goto bailout;
2149 
2150 	for (i = 0; i < num_args; i++) {
2151 		args[i].kname = NULL;
2152 		args[i].kvalue = NULL;
2153 	}
2154 
2155 	for (i = 0; i < num_args; i++) {
2156 		uint8_t *tmpptr;
2157 
2158 		args[i].kname = ctl_copyin_alloc(args[i].name,
2159 			args[i].namelen, error_str, error_str_len);
2160 		if (args[i].kname == NULL)
2161 			goto bailout;
2162 
2163 		if (args[i].kname[args[i].namelen - 1] != '\0') {
2164 			snprintf(error_str, error_str_len, "Argument %d "
2165 				 "name is not NUL-terminated", i);
2166 			goto bailout;
2167 		}
2168 
2169 		if (args[i].flags & CTL_BEARG_RD) {
2170 			tmpptr = ctl_copyin_alloc(args[i].value,
2171 				args[i].vallen, error_str, error_str_len);
2172 			if (tmpptr == NULL)
2173 				goto bailout;
2174 			if ((args[i].flags & CTL_BEARG_ASCII)
2175 			 && (tmpptr[args[i].vallen - 1] != '\0')) {
2176 				snprintf(error_str, error_str_len, "Argument "
2177 				    "%d value is not NUL-terminated", i);
2178 				goto bailout;
2179 			}
2180 			args[i].kvalue = tmpptr;
2181 		} else {
2182 			args[i].kvalue = malloc(args[i].vallen,
2183 			    M_CTL, M_WAITOK | M_ZERO);
2184 		}
2185 	}
2186 
2187 	return (args);
2188 bailout:
2189 
2190 	ctl_free_args(num_args, args);
2191 
2192 	return (NULL);
2193 }
2194 
2195 static void
2196 ctl_copyout_args(int num_args, struct ctl_be_arg *args)
2197 {
2198 	int i;
2199 
2200 	for (i = 0; i < num_args; i++) {
2201 		if (args[i].flags & CTL_BEARG_WR)
2202 			copyout(args[i].kvalue, args[i].value, args[i].vallen);
2203 	}
2204 }
2205 
2206 /*
2207  * Escape characters that are illegal or not recommended in XML.
2208  */
2209 int
2210 ctl_sbuf_printf_esc(struct sbuf *sb, char *str)
2211 {
2212 	int retval;
2213 
2214 	retval = 0;
2215 
2216 	for (; *str; str++) {
2217 		switch (*str) {
2218 		case '&':
2219 			retval = sbuf_printf(sb, "&amp;");
2220 			break;
2221 		case '>':
2222 			retval = sbuf_printf(sb, "&gt;");
2223 			break;
2224 		case '<':
2225 			retval = sbuf_printf(sb, "&lt;");
2226 			break;
2227 		default:
2228 			retval = sbuf_putc(sb, *str);
2229 			break;
2230 		}
2231 
2232 		if (retval != 0)
2233 			break;
2234 
2235 	}
2236 
2237 	return (retval);
2238 }
2239 
2240 static int
2241 ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2242 	  struct thread *td)
2243 {
2244 	struct ctl_softc *softc;
2245 	int retval;
2246 
2247 	softc = control_softc;
2248 
2249 	retval = 0;
2250 
2251 	switch (cmd) {
2252 	case CTL_IO: {
2253 		union ctl_io *io;
2254 		void *pool_tmp;
2255 
2256 		/*
2257 		 * If we haven't been "enabled", don't allow any SCSI I/O
2258 		 * to this FETD.
2259 		 */
2260 		if ((softc->ioctl_info.flags & CTL_IOCTL_FLAG_ENABLED) == 0) {
2261 			retval = EPERM;
2262 			break;
2263 		}
2264 
2265 		io = ctl_alloc_io(softc->ioctl_info.port.ctl_pool_ref);
2266 		if (io == NULL) {
2267 			printf("ctl_ioctl: can't allocate ctl_io!\n");
2268 			retval = ENOSPC;
2269 			break;
2270 		}
2271 
2272 		/*
2273 		 * Need to save the pool reference so it doesn't get
2274 		 * spammed by the user's ctl_io.
2275 		 */
2276 		pool_tmp = io->io_hdr.pool;
2277 
2278 		memcpy(io, (void *)addr, sizeof(*io));
2279 
2280 		io->io_hdr.pool = pool_tmp;
2281 		/*
2282 		 * No status yet, so make sure the status is set properly.
2283 		 */
2284 		io->io_hdr.status = CTL_STATUS_NONE;
2285 
2286 		/*
2287 		 * The user sets the initiator ID, target and LUN IDs.
2288 		 */
2289 		io->io_hdr.nexus.targ_port = softc->ioctl_info.port.targ_port;
2290 		io->io_hdr.flags |= CTL_FLAG_USER_REQ;
2291 		if ((io->io_hdr.io_type == CTL_IO_SCSI)
2292 		 && (io->scsiio.tag_type != CTL_TAG_UNTAGGED))
2293 			io->scsiio.tag_num = softc->ioctl_info.cur_tag_num++;
2294 
2295 		retval = ctl_ioctl_submit_wait(io);
2296 
2297 		if (retval != 0) {
2298 			ctl_free_io(io);
2299 			break;
2300 		}
2301 
2302 		memcpy((void *)addr, io, sizeof(*io));
2303 
2304 		/* return this to our pool */
2305 		ctl_free_io(io);
2306 
2307 		break;
2308 	}
2309 	case CTL_ENABLE_PORT:
2310 	case CTL_DISABLE_PORT:
2311 	case CTL_SET_PORT_WWNS: {
2312 		struct ctl_port *port;
2313 		struct ctl_port_entry *entry;
2314 
2315 		entry = (struct ctl_port_entry *)addr;
2316 
2317 		mtx_lock(&softc->ctl_lock);
2318 		STAILQ_FOREACH(port, &softc->port_list, links) {
2319 			int action, done;
2320 
2321 			action = 0;
2322 			done = 0;
2323 
2324 			if ((entry->port_type == CTL_PORT_NONE)
2325 			 && (entry->targ_port == port->targ_port)) {
2326 				/*
2327 				 * If the user only wants to enable or
2328 				 * disable or set WWNs on a specific port,
2329 				 * do the operation and we're done.
2330 				 */
2331 				action = 1;
2332 				done = 1;
2333 			} else if (entry->port_type & port->port_type) {
2334 				/*
2335 				 * Compare the user's type mask with the
2336 				 * particular frontend type to see if we
2337 				 * have a match.
2338 				 */
2339 				action = 1;
2340 				done = 0;
2341 
2342 				/*
2343 				 * Make sure the user isn't trying to set
2344 				 * WWNs on multiple ports at the same time.
2345 				 */
2346 				if (cmd == CTL_SET_PORT_WWNS) {
2347 					printf("%s: Can't set WWNs on "
2348 					       "multiple ports\n", __func__);
2349 					retval = EINVAL;
2350 					break;
2351 				}
2352 			}
2353 			if (action != 0) {
2354 				/*
2355 				 * XXX KDM we have to drop the lock here,
2356 				 * because the online/offline operations
2357 				 * can potentially block.  We need to
2358 				 * reference count the frontends so they
2359 				 * can't go away,
2360 				 */
2361 				mtx_unlock(&softc->ctl_lock);
2362 
2363 				if (cmd == CTL_ENABLE_PORT) {
2364 					struct ctl_lun *lun;
2365 
2366 					STAILQ_FOREACH(lun, &softc->lun_list,
2367 						       links) {
2368 						port->lun_enable(port->targ_lun_arg,
2369 						    lun->target,
2370 						    lun->lun);
2371 					}
2372 
2373 					ctl_port_online(port);
2374 				} else if (cmd == CTL_DISABLE_PORT) {
2375 					struct ctl_lun *lun;
2376 
2377 					ctl_port_offline(port);
2378 
2379 					STAILQ_FOREACH(lun, &softc->lun_list,
2380 						       links) {
2381 						port->lun_disable(
2382 						    port->targ_lun_arg,
2383 						    lun->target,
2384 						    lun->lun);
2385 					}
2386 				}
2387 
2388 				mtx_lock(&softc->ctl_lock);
2389 
2390 				if (cmd == CTL_SET_PORT_WWNS)
2391 					ctl_port_set_wwns(port,
2392 					    (entry->flags & CTL_PORT_WWNN_VALID) ?
2393 					    1 : 0, entry->wwnn,
2394 					    (entry->flags & CTL_PORT_WWPN_VALID) ?
2395 					    1 : 0, entry->wwpn);
2396 			}
2397 			if (done != 0)
2398 				break;
2399 		}
2400 		mtx_unlock(&softc->ctl_lock);
2401 		break;
2402 	}
2403 	case CTL_GET_PORT_LIST: {
2404 		struct ctl_port *port;
2405 		struct ctl_port_list *list;
2406 		int i;
2407 
2408 		list = (struct ctl_port_list *)addr;
2409 
2410 		if (list->alloc_len != (list->alloc_num *
2411 		    sizeof(struct ctl_port_entry))) {
2412 			printf("%s: CTL_GET_PORT_LIST: alloc_len %u != "
2413 			       "alloc_num %u * sizeof(struct ctl_port_entry) "
2414 			       "%zu\n", __func__, list->alloc_len,
2415 			       list->alloc_num, sizeof(struct ctl_port_entry));
2416 			retval = EINVAL;
2417 			break;
2418 		}
2419 		list->fill_len = 0;
2420 		list->fill_num = 0;
2421 		list->dropped_num = 0;
2422 		i = 0;
2423 		mtx_lock(&softc->ctl_lock);
2424 		STAILQ_FOREACH(port, &softc->port_list, links) {
2425 			struct ctl_port_entry entry, *list_entry;
2426 
2427 			if (list->fill_num >= list->alloc_num) {
2428 				list->dropped_num++;
2429 				continue;
2430 			}
2431 
2432 			entry.port_type = port->port_type;
2433 			strlcpy(entry.port_name, port->port_name,
2434 				sizeof(entry.port_name));
2435 			entry.targ_port = port->targ_port;
2436 			entry.physical_port = port->physical_port;
2437 			entry.virtual_port = port->virtual_port;
2438 			entry.wwnn = port->wwnn;
2439 			entry.wwpn = port->wwpn;
2440 			if (port->status & CTL_PORT_STATUS_ONLINE)
2441 				entry.online = 1;
2442 			else
2443 				entry.online = 0;
2444 
2445 			list_entry = &list->entries[i];
2446 
2447 			retval = copyout(&entry, list_entry, sizeof(entry));
2448 			if (retval != 0) {
2449 				printf("%s: CTL_GET_PORT_LIST: copyout "
2450 				       "returned %d\n", __func__, retval);
2451 				break;
2452 			}
2453 			i++;
2454 			list->fill_num++;
2455 			list->fill_len += sizeof(entry);
2456 		}
2457 		mtx_unlock(&softc->ctl_lock);
2458 
2459 		/*
2460 		 * If this is non-zero, we had a copyout fault, so there's
2461 		 * probably no point in attempting to set the status inside
2462 		 * the structure.
2463 		 */
2464 		if (retval != 0)
2465 			break;
2466 
2467 		if (list->dropped_num > 0)
2468 			list->status = CTL_PORT_LIST_NEED_MORE_SPACE;
2469 		else
2470 			list->status = CTL_PORT_LIST_OK;
2471 		break;
2472 	}
2473 	case CTL_DUMP_OOA: {
2474 		struct ctl_lun *lun;
2475 		union ctl_io *io;
2476 		char printbuf[128];
2477 		struct sbuf sb;
2478 
2479 		mtx_lock(&softc->ctl_lock);
2480 		printf("Dumping OOA queues:\n");
2481 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
2482 			mtx_lock(&lun->lun_lock);
2483 			for (io = (union ctl_io *)TAILQ_FIRST(
2484 			     &lun->ooa_queue); io != NULL;
2485 			     io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2486 			     ooa_links)) {
2487 				sbuf_new(&sb, printbuf, sizeof(printbuf),
2488 					 SBUF_FIXEDLEN);
2489 				sbuf_printf(&sb, "LUN %jd tag 0x%04x%s%s%s%s: ",
2490 					    (intmax_t)lun->lun,
2491 					    io->scsiio.tag_num,
2492 					    (io->io_hdr.flags &
2493 					    CTL_FLAG_BLOCKED) ? "" : " BLOCKED",
2494 					    (io->io_hdr.flags &
2495 					    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
2496 					    (io->io_hdr.flags &
2497 					    CTL_FLAG_ABORT) ? " ABORT" : "",
2498 			                    (io->io_hdr.flags &
2499 		                        CTL_FLAG_IS_WAS_ON_RTR) ? " RTR" : "");
2500 				ctl_scsi_command_string(&io->scsiio, NULL, &sb);
2501 				sbuf_finish(&sb);
2502 				printf("%s\n", sbuf_data(&sb));
2503 			}
2504 			mtx_unlock(&lun->lun_lock);
2505 		}
2506 		printf("OOA queues dump done\n");
2507 		mtx_unlock(&softc->ctl_lock);
2508 		break;
2509 	}
2510 	case CTL_GET_OOA: {
2511 		struct ctl_lun *lun;
2512 		struct ctl_ooa *ooa_hdr;
2513 		struct ctl_ooa_entry *entries;
2514 		uint32_t cur_fill_num;
2515 
2516 		ooa_hdr = (struct ctl_ooa *)addr;
2517 
2518 		if ((ooa_hdr->alloc_len == 0)
2519 		 || (ooa_hdr->alloc_num == 0)) {
2520 			printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2521 			       "must be non-zero\n", __func__,
2522 			       ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2523 			retval = EINVAL;
2524 			break;
2525 		}
2526 
2527 		if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2528 		    sizeof(struct ctl_ooa_entry))) {
2529 			printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2530 			       "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2531 			       __func__, ooa_hdr->alloc_len,
2532 			       ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2533 			retval = EINVAL;
2534 			break;
2535 		}
2536 
2537 		entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2538 		if (entries == NULL) {
2539 			printf("%s: could not allocate %d bytes for OOA "
2540 			       "dump\n", __func__, ooa_hdr->alloc_len);
2541 			retval = ENOMEM;
2542 			break;
2543 		}
2544 
2545 		mtx_lock(&softc->ctl_lock);
2546 		if (((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0)
2547 		 && ((ooa_hdr->lun_num >= CTL_MAX_LUNS)
2548 		  || (softc->ctl_luns[ooa_hdr->lun_num] == NULL))) {
2549 			mtx_unlock(&softc->ctl_lock);
2550 			free(entries, M_CTL);
2551 			printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2552 			       __func__, (uintmax_t)ooa_hdr->lun_num);
2553 			retval = EINVAL;
2554 			break;
2555 		}
2556 
2557 		cur_fill_num = 0;
2558 
2559 		if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2560 			STAILQ_FOREACH(lun, &softc->lun_list, links) {
2561 				retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2562 					ooa_hdr, entries);
2563 				if (retval != 0)
2564 					break;
2565 			}
2566 			if (retval != 0) {
2567 				mtx_unlock(&softc->ctl_lock);
2568 				free(entries, M_CTL);
2569 				break;
2570 			}
2571 		} else {
2572 			lun = softc->ctl_luns[ooa_hdr->lun_num];
2573 
2574 			retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,ooa_hdr,
2575 						    entries);
2576 		}
2577 		mtx_unlock(&softc->ctl_lock);
2578 
2579 		ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2580 		ooa_hdr->fill_len = ooa_hdr->fill_num *
2581 			sizeof(struct ctl_ooa_entry);
2582 		retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2583 		if (retval != 0) {
2584 			printf("%s: error copying out %d bytes for OOA dump\n",
2585 			       __func__, ooa_hdr->fill_len);
2586 		}
2587 
2588 		getbintime(&ooa_hdr->cur_bt);
2589 
2590 		if (cur_fill_num > ooa_hdr->alloc_num) {
2591 			ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2592 			ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2593 		} else {
2594 			ooa_hdr->dropped_num = 0;
2595 			ooa_hdr->status = CTL_OOA_OK;
2596 		}
2597 
2598 		free(entries, M_CTL);
2599 		break;
2600 	}
2601 	case CTL_CHECK_OOA: {
2602 		union ctl_io *io;
2603 		struct ctl_lun *lun;
2604 		struct ctl_ooa_info *ooa_info;
2605 
2606 
2607 		ooa_info = (struct ctl_ooa_info *)addr;
2608 
2609 		if (ooa_info->lun_id >= CTL_MAX_LUNS) {
2610 			ooa_info->status = CTL_OOA_INVALID_LUN;
2611 			break;
2612 		}
2613 		mtx_lock(&softc->ctl_lock);
2614 		lun = softc->ctl_luns[ooa_info->lun_id];
2615 		if (lun == NULL) {
2616 			mtx_unlock(&softc->ctl_lock);
2617 			ooa_info->status = CTL_OOA_INVALID_LUN;
2618 			break;
2619 		}
2620 		mtx_lock(&lun->lun_lock);
2621 		mtx_unlock(&softc->ctl_lock);
2622 		ooa_info->num_entries = 0;
2623 		for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
2624 		     io != NULL; io = (union ctl_io *)TAILQ_NEXT(
2625 		     &io->io_hdr, ooa_links)) {
2626 			ooa_info->num_entries++;
2627 		}
2628 		mtx_unlock(&lun->lun_lock);
2629 
2630 		ooa_info->status = CTL_OOA_SUCCESS;
2631 
2632 		break;
2633 	}
2634 	case CTL_HARD_START:
2635 	case CTL_HARD_STOP: {
2636 		struct ctl_fe_ioctl_startstop_info ss_info;
2637 		struct cfi_metatask *metatask;
2638 		struct mtx hs_mtx;
2639 
2640 		mtx_init(&hs_mtx, "HS Mutex", NULL, MTX_DEF);
2641 
2642 		cv_init(&ss_info.sem, "hard start/stop cv" );
2643 
2644 		metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2645 		if (metatask == NULL) {
2646 			retval = ENOMEM;
2647 			mtx_destroy(&hs_mtx);
2648 			break;
2649 		}
2650 
2651 		if (cmd == CTL_HARD_START)
2652 			metatask->tasktype = CFI_TASK_STARTUP;
2653 		else
2654 			metatask->tasktype = CFI_TASK_SHUTDOWN;
2655 
2656 		metatask->callback = ctl_ioctl_hard_startstop_callback;
2657 		metatask->callback_arg = &ss_info;
2658 
2659 		cfi_action(metatask);
2660 
2661 		/* Wait for the callback */
2662 		mtx_lock(&hs_mtx);
2663 		cv_wait_sig(&ss_info.sem, &hs_mtx);
2664 		mtx_unlock(&hs_mtx);
2665 
2666 		/*
2667 		 * All information has been copied from the metatask by the
2668 		 * time cv_broadcast() is called, so we free the metatask here.
2669 		 */
2670 		cfi_free_metatask(metatask);
2671 
2672 		memcpy((void *)addr, &ss_info.hs_info, sizeof(ss_info.hs_info));
2673 
2674 		mtx_destroy(&hs_mtx);
2675 		break;
2676 	}
2677 	case CTL_BBRREAD: {
2678 		struct ctl_bbrread_info *bbr_info;
2679 		struct ctl_fe_ioctl_bbrread_info fe_bbr_info;
2680 		struct mtx bbr_mtx;
2681 		struct cfi_metatask *metatask;
2682 
2683 		bbr_info = (struct ctl_bbrread_info *)addr;
2684 
2685 		bzero(&fe_bbr_info, sizeof(fe_bbr_info));
2686 
2687 		bzero(&bbr_mtx, sizeof(bbr_mtx));
2688 		mtx_init(&bbr_mtx, "BBR Mutex", NULL, MTX_DEF);
2689 
2690 		fe_bbr_info.bbr_info = bbr_info;
2691 		fe_bbr_info.lock = &bbr_mtx;
2692 
2693 		cv_init(&fe_bbr_info.sem, "BBR read cv");
2694 		metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2695 
2696 		if (metatask == NULL) {
2697 			mtx_destroy(&bbr_mtx);
2698 			cv_destroy(&fe_bbr_info.sem);
2699 			retval = ENOMEM;
2700 			break;
2701 		}
2702 		metatask->tasktype = CFI_TASK_BBRREAD;
2703 		metatask->callback = ctl_ioctl_bbrread_callback;
2704 		metatask->callback_arg = &fe_bbr_info;
2705 		metatask->taskinfo.bbrread.lun_num = bbr_info->lun_num;
2706 		metatask->taskinfo.bbrread.lba = bbr_info->lba;
2707 		metatask->taskinfo.bbrread.len = bbr_info->len;
2708 
2709 		cfi_action(metatask);
2710 
2711 		mtx_lock(&bbr_mtx);
2712 		while (fe_bbr_info.wakeup_done == 0)
2713 			cv_wait_sig(&fe_bbr_info.sem, &bbr_mtx);
2714 		mtx_unlock(&bbr_mtx);
2715 
2716 		bbr_info->status = metatask->status;
2717 		bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2718 		bbr_info->scsi_status = metatask->taskinfo.bbrread.scsi_status;
2719 		memcpy(&bbr_info->sense_data,
2720 		       &metatask->taskinfo.bbrread.sense_data,
2721 		       ctl_min(sizeof(bbr_info->sense_data),
2722 			       sizeof(metatask->taskinfo.bbrread.sense_data)));
2723 
2724 		cfi_free_metatask(metatask);
2725 
2726 		mtx_destroy(&bbr_mtx);
2727 		cv_destroy(&fe_bbr_info.sem);
2728 
2729 		break;
2730 	}
2731 	case CTL_DELAY_IO: {
2732 		struct ctl_io_delay_info *delay_info;
2733 #ifdef CTL_IO_DELAY
2734 		struct ctl_lun *lun;
2735 #endif /* CTL_IO_DELAY */
2736 
2737 		delay_info = (struct ctl_io_delay_info *)addr;
2738 
2739 #ifdef CTL_IO_DELAY
2740 		mtx_lock(&softc->ctl_lock);
2741 
2742 		if ((delay_info->lun_id >= CTL_MAX_LUNS)
2743 		 || (softc->ctl_luns[delay_info->lun_id] == NULL)) {
2744 			delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2745 		} else {
2746 			lun = softc->ctl_luns[delay_info->lun_id];
2747 			mtx_lock(&lun->lun_lock);
2748 
2749 			delay_info->status = CTL_DELAY_STATUS_OK;
2750 
2751 			switch (delay_info->delay_type) {
2752 			case CTL_DELAY_TYPE_CONT:
2753 				break;
2754 			case CTL_DELAY_TYPE_ONESHOT:
2755 				break;
2756 			default:
2757 				delay_info->status =
2758 					CTL_DELAY_STATUS_INVALID_TYPE;
2759 				break;
2760 			}
2761 
2762 			switch (delay_info->delay_loc) {
2763 			case CTL_DELAY_LOC_DATAMOVE:
2764 				lun->delay_info.datamove_type =
2765 					delay_info->delay_type;
2766 				lun->delay_info.datamove_delay =
2767 					delay_info->delay_secs;
2768 				break;
2769 			case CTL_DELAY_LOC_DONE:
2770 				lun->delay_info.done_type =
2771 					delay_info->delay_type;
2772 				lun->delay_info.done_delay =
2773 					delay_info->delay_secs;
2774 				break;
2775 			default:
2776 				delay_info->status =
2777 					CTL_DELAY_STATUS_INVALID_LOC;
2778 				break;
2779 			}
2780 			mtx_unlock(&lun->lun_lock);
2781 		}
2782 
2783 		mtx_unlock(&softc->ctl_lock);
2784 #else
2785 		delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2786 #endif /* CTL_IO_DELAY */
2787 		break;
2788 	}
2789 	case CTL_REALSYNC_SET: {
2790 		int *syncstate;
2791 
2792 		syncstate = (int *)addr;
2793 
2794 		mtx_lock(&softc->ctl_lock);
2795 		switch (*syncstate) {
2796 		case 0:
2797 			softc->flags &= ~CTL_FLAG_REAL_SYNC;
2798 			break;
2799 		case 1:
2800 			softc->flags |= CTL_FLAG_REAL_SYNC;
2801 			break;
2802 		default:
2803 			retval = EINVAL;
2804 			break;
2805 		}
2806 		mtx_unlock(&softc->ctl_lock);
2807 		break;
2808 	}
2809 	case CTL_REALSYNC_GET: {
2810 		int *syncstate;
2811 
2812 		syncstate = (int*)addr;
2813 
2814 		mtx_lock(&softc->ctl_lock);
2815 		if (softc->flags & CTL_FLAG_REAL_SYNC)
2816 			*syncstate = 1;
2817 		else
2818 			*syncstate = 0;
2819 		mtx_unlock(&softc->ctl_lock);
2820 
2821 		break;
2822 	}
2823 	case CTL_SETSYNC:
2824 	case CTL_GETSYNC: {
2825 		struct ctl_sync_info *sync_info;
2826 		struct ctl_lun *lun;
2827 
2828 		sync_info = (struct ctl_sync_info *)addr;
2829 
2830 		mtx_lock(&softc->ctl_lock);
2831 		lun = softc->ctl_luns[sync_info->lun_id];
2832 		if (lun == NULL) {
2833 			mtx_unlock(&softc->ctl_lock);
2834 			sync_info->status = CTL_GS_SYNC_NO_LUN;
2835 		}
2836 		/*
2837 		 * Get or set the sync interval.  We're not bounds checking
2838 		 * in the set case, hopefully the user won't do something
2839 		 * silly.
2840 		 */
2841 		mtx_lock(&lun->lun_lock);
2842 		mtx_unlock(&softc->ctl_lock);
2843 		if (cmd == CTL_GETSYNC)
2844 			sync_info->sync_interval = lun->sync_interval;
2845 		else
2846 			lun->sync_interval = sync_info->sync_interval;
2847 		mtx_unlock(&lun->lun_lock);
2848 
2849 		sync_info->status = CTL_GS_SYNC_OK;
2850 
2851 		break;
2852 	}
2853 	case CTL_GETSTATS: {
2854 		struct ctl_stats *stats;
2855 		struct ctl_lun *lun;
2856 		int i;
2857 
2858 		stats = (struct ctl_stats *)addr;
2859 
2860 		if ((sizeof(struct ctl_lun_io_stats) * softc->num_luns) >
2861 		     stats->alloc_len) {
2862 			stats->status = CTL_SS_NEED_MORE_SPACE;
2863 			stats->num_luns = softc->num_luns;
2864 			break;
2865 		}
2866 		/*
2867 		 * XXX KDM no locking here.  If the LUN list changes,
2868 		 * things can blow up.
2869 		 */
2870 		for (i = 0, lun = STAILQ_FIRST(&softc->lun_list); lun != NULL;
2871 		     i++, lun = STAILQ_NEXT(lun, links)) {
2872 			retval = copyout(&lun->stats, &stats->lun_stats[i],
2873 					 sizeof(lun->stats));
2874 			if (retval != 0)
2875 				break;
2876 		}
2877 		stats->num_luns = softc->num_luns;
2878 		stats->fill_len = sizeof(struct ctl_lun_io_stats) *
2879 				 softc->num_luns;
2880 		stats->status = CTL_SS_OK;
2881 #ifdef CTL_TIME_IO
2882 		stats->flags = CTL_STATS_FLAG_TIME_VALID;
2883 #else
2884 		stats->flags = CTL_STATS_FLAG_NONE;
2885 #endif
2886 		getnanouptime(&stats->timestamp);
2887 		break;
2888 	}
2889 	case CTL_ERROR_INJECT: {
2890 		struct ctl_error_desc *err_desc, *new_err_desc;
2891 		struct ctl_lun *lun;
2892 
2893 		err_desc = (struct ctl_error_desc *)addr;
2894 
2895 		new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2896 				      M_WAITOK | M_ZERO);
2897 		bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2898 
2899 		mtx_lock(&softc->ctl_lock);
2900 		lun = softc->ctl_luns[err_desc->lun_id];
2901 		if (lun == NULL) {
2902 			mtx_unlock(&softc->ctl_lock);
2903 			free(new_err_desc, M_CTL);
2904 			printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
2905 			       __func__, (uintmax_t)err_desc->lun_id);
2906 			retval = EINVAL;
2907 			break;
2908 		}
2909 		mtx_lock(&lun->lun_lock);
2910 		mtx_unlock(&softc->ctl_lock);
2911 
2912 		/*
2913 		 * We could do some checking here to verify the validity
2914 		 * of the request, but given the complexity of error
2915 		 * injection requests, the checking logic would be fairly
2916 		 * complex.
2917 		 *
2918 		 * For now, if the request is invalid, it just won't get
2919 		 * executed and might get deleted.
2920 		 */
2921 		STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
2922 
2923 		/*
2924 		 * XXX KDM check to make sure the serial number is unique,
2925 		 * in case we somehow manage to wrap.  That shouldn't
2926 		 * happen for a very long time, but it's the right thing to
2927 		 * do.
2928 		 */
2929 		new_err_desc->serial = lun->error_serial;
2930 		err_desc->serial = lun->error_serial;
2931 		lun->error_serial++;
2932 
2933 		mtx_unlock(&lun->lun_lock);
2934 		break;
2935 	}
2936 	case CTL_ERROR_INJECT_DELETE: {
2937 		struct ctl_error_desc *delete_desc, *desc, *desc2;
2938 		struct ctl_lun *lun;
2939 		int delete_done;
2940 
2941 		delete_desc = (struct ctl_error_desc *)addr;
2942 		delete_done = 0;
2943 
2944 		mtx_lock(&softc->ctl_lock);
2945 		lun = softc->ctl_luns[delete_desc->lun_id];
2946 		if (lun == NULL) {
2947 			mtx_unlock(&softc->ctl_lock);
2948 			printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
2949 			       __func__, (uintmax_t)delete_desc->lun_id);
2950 			retval = EINVAL;
2951 			break;
2952 		}
2953 		mtx_lock(&lun->lun_lock);
2954 		mtx_unlock(&softc->ctl_lock);
2955 		STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
2956 			if (desc->serial != delete_desc->serial)
2957 				continue;
2958 
2959 			STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
2960 				      links);
2961 			free(desc, M_CTL);
2962 			delete_done = 1;
2963 		}
2964 		mtx_unlock(&lun->lun_lock);
2965 		if (delete_done == 0) {
2966 			printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
2967 			       "error serial %ju on LUN %u\n", __func__,
2968 			       delete_desc->serial, delete_desc->lun_id);
2969 			retval = EINVAL;
2970 			break;
2971 		}
2972 		break;
2973 	}
2974 	case CTL_DUMP_STRUCTS: {
2975 		int i, j, k, idx;
2976 		struct ctl_port *port;
2977 		struct ctl_frontend *fe;
2978 
2979 		mtx_lock(&softc->ctl_lock);
2980 		printf("CTL Persistent Reservation information start:\n");
2981 		for (i = 0; i < CTL_MAX_LUNS; i++) {
2982 			struct ctl_lun *lun;
2983 
2984 			lun = softc->ctl_luns[i];
2985 
2986 			if ((lun == NULL)
2987 			 || ((lun->flags & CTL_LUN_DISABLED) != 0))
2988 				continue;
2989 
2990 			for (j = 0; j < (CTL_MAX_PORTS * 2); j++) {
2991 				for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
2992 					idx = j * CTL_MAX_INIT_PER_PORT + k;
2993 					if (lun->per_res[idx].registered == 0)
2994 						continue;
2995 					printf("  LUN %d port %d iid %d key "
2996 					       "%#jx\n", i, j, k,
2997 					       (uintmax_t)scsi_8btou64(
2998 					       lun->per_res[idx].res_key.key));
2999 				}
3000 			}
3001 		}
3002 		printf("CTL Persistent Reservation information end\n");
3003 		printf("CTL Ports:\n");
3004 		STAILQ_FOREACH(port, &softc->port_list, links) {
3005 			printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
3006 			       "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
3007 			       port->frontend->name, port->port_type,
3008 			       port->physical_port, port->virtual_port,
3009 			       (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
3010 			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3011 				if (port->wwpn_iid[j].in_use == 0 &&
3012 				    port->wwpn_iid[j].wwpn == 0 &&
3013 				    port->wwpn_iid[j].name == NULL)
3014 					continue;
3015 
3016 				printf("    iid %u use %d WWPN %#jx '%s'\n",
3017 				    j, port->wwpn_iid[j].in_use,
3018 				    (uintmax_t)port->wwpn_iid[j].wwpn,
3019 				    port->wwpn_iid[j].name);
3020 			}
3021 		}
3022 		printf("CTL Port information end\n");
3023 		mtx_unlock(&softc->ctl_lock);
3024 		/*
3025 		 * XXX KDM calling this without a lock.  We'd likely want
3026 		 * to drop the lock before calling the frontend's dump
3027 		 * routine anyway.
3028 		 */
3029 		printf("CTL Frontends:\n");
3030 		STAILQ_FOREACH(fe, &softc->fe_list, links) {
3031 			printf("  Frontend '%s'\n", fe->name);
3032 			if (fe->fe_dump != NULL)
3033 				fe->fe_dump();
3034 		}
3035 		printf("CTL Frontend information end\n");
3036 		break;
3037 	}
3038 	case CTL_LUN_REQ: {
3039 		struct ctl_lun_req *lun_req;
3040 		struct ctl_backend_driver *backend;
3041 
3042 		lun_req = (struct ctl_lun_req *)addr;
3043 
3044 		backend = ctl_backend_find(lun_req->backend);
3045 		if (backend == NULL) {
3046 			lun_req->status = CTL_LUN_ERROR;
3047 			snprintf(lun_req->error_str,
3048 				 sizeof(lun_req->error_str),
3049 				 "Backend \"%s\" not found.",
3050 				 lun_req->backend);
3051 			break;
3052 		}
3053 		if (lun_req->num_be_args > 0) {
3054 			lun_req->kern_be_args = ctl_copyin_args(
3055 				lun_req->num_be_args,
3056 				lun_req->be_args,
3057 				lun_req->error_str,
3058 				sizeof(lun_req->error_str));
3059 			if (lun_req->kern_be_args == NULL) {
3060 				lun_req->status = CTL_LUN_ERROR;
3061 				break;
3062 			}
3063 		}
3064 
3065 		retval = backend->ioctl(dev, cmd, addr, flag, td);
3066 
3067 		if (lun_req->num_be_args > 0) {
3068 			ctl_copyout_args(lun_req->num_be_args,
3069 				      lun_req->kern_be_args);
3070 			ctl_free_args(lun_req->num_be_args,
3071 				      lun_req->kern_be_args);
3072 		}
3073 		break;
3074 	}
3075 	case CTL_LUN_LIST: {
3076 		struct sbuf *sb;
3077 		struct ctl_lun *lun;
3078 		struct ctl_lun_list *list;
3079 		struct ctl_option *opt;
3080 
3081 		list = (struct ctl_lun_list *)addr;
3082 
3083 		/*
3084 		 * Allocate a fixed length sbuf here, based on the length
3085 		 * of the user's buffer.  We could allocate an auto-extending
3086 		 * buffer, and then tell the user how much larger our
3087 		 * amount of data is than his buffer, but that presents
3088 		 * some problems:
3089 		 *
3090 		 * 1.  The sbuf(9) routines use a blocking malloc, and so
3091 		 *     we can't hold a lock while calling them with an
3092 		 *     auto-extending buffer.
3093  		 *
3094 		 * 2.  There is not currently a LUN reference counting
3095 		 *     mechanism, outside of outstanding transactions on
3096 		 *     the LUN's OOA queue.  So a LUN could go away on us
3097 		 *     while we're getting the LUN number, backend-specific
3098 		 *     information, etc.  Thus, given the way things
3099 		 *     currently work, we need to hold the CTL lock while
3100 		 *     grabbing LUN information.
3101 		 *
3102 		 * So, from the user's standpoint, the best thing to do is
3103 		 * allocate what he thinks is a reasonable buffer length,
3104 		 * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
3105 		 * double the buffer length and try again.  (And repeat
3106 		 * that until he succeeds.)
3107 		 */
3108 		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3109 		if (sb == NULL) {
3110 			list->status = CTL_LUN_LIST_ERROR;
3111 			snprintf(list->error_str, sizeof(list->error_str),
3112 				 "Unable to allocate %d bytes for LUN list",
3113 				 list->alloc_len);
3114 			break;
3115 		}
3116 
3117 		sbuf_printf(sb, "<ctllunlist>\n");
3118 
3119 		mtx_lock(&softc->ctl_lock);
3120 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
3121 			mtx_lock(&lun->lun_lock);
3122 			retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3123 					     (uintmax_t)lun->lun);
3124 
3125 			/*
3126 			 * Bail out as soon as we see that we've overfilled
3127 			 * the buffer.
3128 			 */
3129 			if (retval != 0)
3130 				break;
3131 
3132 			retval = sbuf_printf(sb, "\t<backend_type>%s"
3133 					     "</backend_type>\n",
3134 					     (lun->backend == NULL) ?  "none" :
3135 					     lun->backend->name);
3136 
3137 			if (retval != 0)
3138 				break;
3139 
3140 			retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3141 					     lun->be_lun->lun_type);
3142 
3143 			if (retval != 0)
3144 				break;
3145 
3146 			if (lun->backend == NULL) {
3147 				retval = sbuf_printf(sb, "</lun>\n");
3148 				if (retval != 0)
3149 					break;
3150 				continue;
3151 			}
3152 
3153 			retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3154 					     (lun->be_lun->maxlba > 0) ?
3155 					     lun->be_lun->maxlba + 1 : 0);
3156 
3157 			if (retval != 0)
3158 				break;
3159 
3160 			retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3161 					     lun->be_lun->blocksize);
3162 
3163 			if (retval != 0)
3164 				break;
3165 
3166 			retval = sbuf_printf(sb, "\t<serial_number>");
3167 
3168 			if (retval != 0)
3169 				break;
3170 
3171 			retval = ctl_sbuf_printf_esc(sb,
3172 						     lun->be_lun->serial_num);
3173 
3174 			if (retval != 0)
3175 				break;
3176 
3177 			retval = sbuf_printf(sb, "</serial_number>\n");
3178 
3179 			if (retval != 0)
3180 				break;
3181 
3182 			retval = sbuf_printf(sb, "\t<device_id>");
3183 
3184 			if (retval != 0)
3185 				break;
3186 
3187 			retval = ctl_sbuf_printf_esc(sb,lun->be_lun->device_id);
3188 
3189 			if (retval != 0)
3190 				break;
3191 
3192 			retval = sbuf_printf(sb, "</device_id>\n");
3193 
3194 			if (retval != 0)
3195 				break;
3196 
3197 			if (lun->backend->lun_info != NULL) {
3198 				retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
3199 				if (retval != 0)
3200 					break;
3201 			}
3202 			STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
3203 				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3204 				    opt->name, opt->value, opt->name);
3205 				if (retval != 0)
3206 					break;
3207 			}
3208 
3209 			retval = sbuf_printf(sb, "</lun>\n");
3210 
3211 			if (retval != 0)
3212 				break;
3213 			mtx_unlock(&lun->lun_lock);
3214 		}
3215 		if (lun != NULL)
3216 			mtx_unlock(&lun->lun_lock);
3217 		mtx_unlock(&softc->ctl_lock);
3218 
3219 		if ((retval != 0)
3220 		 || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3221 			retval = 0;
3222 			sbuf_delete(sb);
3223 			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3224 			snprintf(list->error_str, sizeof(list->error_str),
3225 				 "Out of space, %d bytes is too small",
3226 				 list->alloc_len);
3227 			break;
3228 		}
3229 
3230 		sbuf_finish(sb);
3231 
3232 		retval = copyout(sbuf_data(sb), list->lun_xml,
3233 				 sbuf_len(sb) + 1);
3234 
3235 		list->fill_len = sbuf_len(sb) + 1;
3236 		list->status = CTL_LUN_LIST_OK;
3237 		sbuf_delete(sb);
3238 		break;
3239 	}
3240 	case CTL_ISCSI: {
3241 		struct ctl_iscsi *ci;
3242 		struct ctl_frontend *fe;
3243 
3244 		ci = (struct ctl_iscsi *)addr;
3245 
3246 		fe = ctl_frontend_find("iscsi");
3247 		if (fe == NULL) {
3248 			ci->status = CTL_ISCSI_ERROR;
3249 			snprintf(ci->error_str, sizeof(ci->error_str),
3250 			    "Frontend \"iscsi\" not found.");
3251 			break;
3252 		}
3253 
3254 		retval = fe->ioctl(dev, cmd, addr, flag, td);
3255 		break;
3256 	}
3257 	case CTL_PORT_REQ: {
3258 		struct ctl_req *req;
3259 		struct ctl_frontend *fe;
3260 
3261 		req = (struct ctl_req *)addr;
3262 
3263 		fe = ctl_frontend_find(req->driver);
3264 		if (fe == NULL) {
3265 			req->status = CTL_LUN_ERROR;
3266 			snprintf(req->error_str, sizeof(req->error_str),
3267 			    "Frontend \"%s\" not found.", req->driver);
3268 			break;
3269 		}
3270 		if (req->num_args > 0) {
3271 			req->kern_args = ctl_copyin_args(req->num_args,
3272 			    req->args, req->error_str, sizeof(req->error_str));
3273 			if (req->kern_args == NULL) {
3274 				req->status = CTL_LUN_ERROR;
3275 				break;
3276 			}
3277 		}
3278 
3279 		retval = fe->ioctl(dev, cmd, addr, flag, td);
3280 
3281 		if (req->num_args > 0) {
3282 			ctl_copyout_args(req->num_args, req->kern_args);
3283 			ctl_free_args(req->num_args, req->kern_args);
3284 		}
3285 		break;
3286 	}
3287 	case CTL_PORT_LIST: {
3288 		struct sbuf *sb;
3289 		struct ctl_port *port;
3290 		struct ctl_lun_list *list;
3291 		struct ctl_option *opt;
3292 
3293 		list = (struct ctl_lun_list *)addr;
3294 
3295 		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3296 		if (sb == NULL) {
3297 			list->status = CTL_LUN_LIST_ERROR;
3298 			snprintf(list->error_str, sizeof(list->error_str),
3299 				 "Unable to allocate %d bytes for LUN list",
3300 				 list->alloc_len);
3301 			break;
3302 		}
3303 
3304 		sbuf_printf(sb, "<ctlportlist>\n");
3305 
3306 		mtx_lock(&softc->ctl_lock);
3307 		STAILQ_FOREACH(port, &softc->port_list, links) {
3308 			retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3309 					     (uintmax_t)port->targ_port);
3310 
3311 			/*
3312 			 * Bail out as soon as we see that we've overfilled
3313 			 * the buffer.
3314 			 */
3315 			if (retval != 0)
3316 				break;
3317 
3318 			retval = sbuf_printf(sb, "\t<frontend_type>%s"
3319 			    "</frontend_type>\n", port->frontend->name);
3320 			if (retval != 0)
3321 				break;
3322 
3323 			retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3324 					     port->port_type);
3325 			if (retval != 0)
3326 				break;
3327 
3328 			retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3329 			    (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3330 			if (retval != 0)
3331 				break;
3332 
3333 			retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3334 			    port->port_name);
3335 			if (retval != 0)
3336 				break;
3337 
3338 			retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3339 			    port->physical_port);
3340 			if (retval != 0)
3341 				break;
3342 
3343 			retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3344 			    port->virtual_port);
3345 			if (retval != 0)
3346 				break;
3347 
3348 			retval = sbuf_printf(sb, "\t<wwnn>%#jx</wwnn>\n",
3349 			    (uintmax_t)port->wwnn);
3350 			if (retval != 0)
3351 				break;
3352 
3353 			retval = sbuf_printf(sb, "\t<wwpn>%#jx</wwpn>\n",
3354 			    (uintmax_t)port->wwpn);
3355 			if (retval != 0)
3356 				break;
3357 
3358 			if (port->port_info != NULL) {
3359 				retval = port->port_info(port->onoff_arg, sb);
3360 				if (retval != 0)
3361 					break;
3362 			}
3363 			STAILQ_FOREACH(opt, &port->options, links) {
3364 				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3365 				    opt->name, opt->value, opt->name);
3366 				if (retval != 0)
3367 					break;
3368 			}
3369 
3370 			retval = sbuf_printf(sb, "</targ_port>\n");
3371 			if (retval != 0)
3372 				break;
3373 		}
3374 		mtx_unlock(&softc->ctl_lock);
3375 
3376 		if ((retval != 0)
3377 		 || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3378 			retval = 0;
3379 			sbuf_delete(sb);
3380 			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3381 			snprintf(list->error_str, sizeof(list->error_str),
3382 				 "Out of space, %d bytes is too small",
3383 				 list->alloc_len);
3384 			break;
3385 		}
3386 
3387 		sbuf_finish(sb);
3388 
3389 		retval = copyout(sbuf_data(sb), list->lun_xml,
3390 				 sbuf_len(sb) + 1);
3391 
3392 		list->fill_len = sbuf_len(sb) + 1;
3393 		list->status = CTL_LUN_LIST_OK;
3394 		sbuf_delete(sb);
3395 		break;
3396 	}
3397 	default: {
3398 		/* XXX KDM should we fix this? */
3399 #if 0
3400 		struct ctl_backend_driver *backend;
3401 		unsigned int type;
3402 		int found;
3403 
3404 		found = 0;
3405 
3406 		/*
3407 		 * We encode the backend type as the ioctl type for backend
3408 		 * ioctls.  So parse it out here, and then search for a
3409 		 * backend of this type.
3410 		 */
3411 		type = _IOC_TYPE(cmd);
3412 
3413 		STAILQ_FOREACH(backend, &softc->be_list, links) {
3414 			if (backend->type == type) {
3415 				found = 1;
3416 				break;
3417 			}
3418 		}
3419 		if (found == 0) {
3420 			printf("ctl: unknown ioctl command %#lx or backend "
3421 			       "%d\n", cmd, type);
3422 			retval = EINVAL;
3423 			break;
3424 		}
3425 		retval = backend->ioctl(dev, cmd, addr, flag, td);
3426 #endif
3427 		retval = ENOTTY;
3428 		break;
3429 	}
3430 	}
3431 	return (retval);
3432 }
3433 
3434 uint32_t
3435 ctl_get_initindex(struct ctl_nexus *nexus)
3436 {
3437 	if (nexus->targ_port < CTL_MAX_PORTS)
3438 		return (nexus->initid.id +
3439 			(nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3440 	else
3441 		return (nexus->initid.id +
3442 		       ((nexus->targ_port - CTL_MAX_PORTS) *
3443 			CTL_MAX_INIT_PER_PORT));
3444 }
3445 
3446 uint32_t
3447 ctl_get_resindex(struct ctl_nexus *nexus)
3448 {
3449 	return (nexus->initid.id + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3450 }
3451 
3452 uint32_t
3453 ctl_port_idx(int port_num)
3454 {
3455 	if (port_num < CTL_MAX_PORTS)
3456 		return(port_num);
3457 	else
3458 		return(port_num - CTL_MAX_PORTS);
3459 }
3460 
3461 static uint32_t
3462 ctl_map_lun(int port_num, uint32_t lun_id)
3463 {
3464 	struct ctl_port *port;
3465 
3466 	port = control_softc->ctl_ports[ctl_port_idx(port_num)];
3467 	if (port == NULL)
3468 		return (UINT32_MAX);
3469 	if (port->lun_map == NULL)
3470 		return (lun_id);
3471 	return (port->lun_map(port->targ_lun_arg, lun_id));
3472 }
3473 
3474 static uint32_t
3475 ctl_map_lun_back(int port_num, uint32_t lun_id)
3476 {
3477 	struct ctl_port *port;
3478 	uint32_t i;
3479 
3480 	port = control_softc->ctl_ports[ctl_port_idx(port_num)];
3481 	if (port->lun_map == NULL)
3482 		return (lun_id);
3483 	for (i = 0; i < CTL_MAX_LUNS; i++) {
3484 		if (port->lun_map(port->targ_lun_arg, i) == lun_id)
3485 			return (i);
3486 	}
3487 	return (UINT32_MAX);
3488 }
3489 
3490 /*
3491  * Note:  This only works for bitmask sizes that are at least 32 bits, and
3492  * that are a power of 2.
3493  */
3494 int
3495 ctl_ffz(uint32_t *mask, uint32_t size)
3496 {
3497 	uint32_t num_chunks, num_pieces;
3498 	int i, j;
3499 
3500 	num_chunks = (size >> 5);
3501 	if (num_chunks == 0)
3502 		num_chunks++;
3503 	num_pieces = ctl_min((sizeof(uint32_t) * 8), size);
3504 
3505 	for (i = 0; i < num_chunks; i++) {
3506 		for (j = 0; j < num_pieces; j++) {
3507 			if ((mask[i] & (1 << j)) == 0)
3508 				return ((i << 5) + j);
3509 		}
3510 	}
3511 
3512 	return (-1);
3513 }
3514 
3515 int
3516 ctl_set_mask(uint32_t *mask, uint32_t bit)
3517 {
3518 	uint32_t chunk, piece;
3519 
3520 	chunk = bit >> 5;
3521 	piece = bit % (sizeof(uint32_t) * 8);
3522 
3523 	if ((mask[chunk] & (1 << piece)) != 0)
3524 		return (-1);
3525 	else
3526 		mask[chunk] |= (1 << piece);
3527 
3528 	return (0);
3529 }
3530 
3531 int
3532 ctl_clear_mask(uint32_t *mask, uint32_t bit)
3533 {
3534 	uint32_t chunk, piece;
3535 
3536 	chunk = bit >> 5;
3537 	piece = bit % (sizeof(uint32_t) * 8);
3538 
3539 	if ((mask[chunk] & (1 << piece)) == 0)
3540 		return (-1);
3541 	else
3542 		mask[chunk] &= ~(1 << piece);
3543 
3544 	return (0);
3545 }
3546 
3547 int
3548 ctl_is_set(uint32_t *mask, uint32_t bit)
3549 {
3550 	uint32_t chunk, piece;
3551 
3552 	chunk = bit >> 5;
3553 	piece = bit % (sizeof(uint32_t) * 8);
3554 
3555 	if ((mask[chunk] & (1 << piece)) == 0)
3556 		return (0);
3557 	else
3558 		return (1);
3559 }
3560 
3561 #ifdef unused
3562 /*
3563  * The bus, target and lun are optional, they can be filled in later.
3564  * can_wait is used to determine whether we can wait on the malloc or not.
3565  */
3566 union ctl_io*
3567 ctl_malloc_io(ctl_io_type io_type, uint32_t targ_port, uint32_t targ_target,
3568 	      uint32_t targ_lun, int can_wait)
3569 {
3570 	union ctl_io *io;
3571 
3572 	if (can_wait)
3573 		io = (union ctl_io *)malloc(sizeof(*io), M_CTL, M_WAITOK);
3574 	else
3575 		io = (union ctl_io *)malloc(sizeof(*io), M_CTL, M_NOWAIT);
3576 
3577 	if (io != NULL) {
3578 		io->io_hdr.io_type = io_type;
3579 		io->io_hdr.targ_port = targ_port;
3580 		/*
3581 		 * XXX KDM this needs to change/go away.  We need to move
3582 		 * to a preallocated pool of ctl_scsiio structures.
3583 		 */
3584 		io->io_hdr.nexus.targ_target.id = targ_target;
3585 		io->io_hdr.nexus.targ_lun = targ_lun;
3586 	}
3587 
3588 	return (io);
3589 }
3590 
3591 void
3592 ctl_kfree_io(union ctl_io *io)
3593 {
3594 	free(io, M_CTL);
3595 }
3596 #endif /* unused */
3597 
3598 /*
3599  * ctl_softc, pool_type, total_ctl_io are passed in.
3600  * npool is passed out.
3601  */
3602 int
3603 ctl_pool_create(struct ctl_softc *ctl_softc, ctl_pool_type pool_type,
3604 		uint32_t total_ctl_io, struct ctl_io_pool **npool)
3605 {
3606 	uint32_t i;
3607 	union ctl_io *cur_io, *next_io;
3608 	struct ctl_io_pool *pool;
3609 	int retval;
3610 
3611 	retval = 0;
3612 
3613 	pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3614 					    M_NOWAIT | M_ZERO);
3615 	if (pool == NULL) {
3616 		retval = ENOMEM;
3617 		goto bailout;
3618 	}
3619 
3620 	pool->type = pool_type;
3621 	pool->ctl_softc = ctl_softc;
3622 
3623 	mtx_lock(&ctl_softc->pool_lock);
3624 	pool->id = ctl_softc->cur_pool_id++;
3625 	mtx_unlock(&ctl_softc->pool_lock);
3626 
3627 	pool->flags = CTL_POOL_FLAG_NONE;
3628 	pool->refcount = 1;		/* Reference for validity. */
3629 	STAILQ_INIT(&pool->free_queue);
3630 
3631 	/*
3632 	 * XXX KDM other options here:
3633 	 * - allocate a page at a time
3634 	 * - allocate one big chunk of memory.
3635 	 * Page allocation might work well, but would take a little more
3636 	 * tracking.
3637 	 */
3638 	for (i = 0; i < total_ctl_io; i++) {
3639 		cur_io = (union ctl_io *)malloc(sizeof(*cur_io), M_CTLIO,
3640 						M_NOWAIT);
3641 		if (cur_io == NULL) {
3642 			retval = ENOMEM;
3643 			break;
3644 		}
3645 		cur_io->io_hdr.pool = pool;
3646 		STAILQ_INSERT_TAIL(&pool->free_queue, &cur_io->io_hdr, links);
3647 		pool->total_ctl_io++;
3648 		pool->free_ctl_io++;
3649 	}
3650 
3651 	if (retval != 0) {
3652 		for (cur_io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue);
3653 		     cur_io != NULL; cur_io = next_io) {
3654 			next_io = (union ctl_io *)STAILQ_NEXT(&cur_io->io_hdr,
3655 							      links);
3656 			STAILQ_REMOVE(&pool->free_queue, &cur_io->io_hdr,
3657 				      ctl_io_hdr, links);
3658 			free(cur_io, M_CTLIO);
3659 		}
3660 
3661 		free(pool, M_CTL);
3662 		goto bailout;
3663 	}
3664 	mtx_lock(&ctl_softc->pool_lock);
3665 	ctl_softc->num_pools++;
3666 	STAILQ_INSERT_TAIL(&ctl_softc->io_pools, pool, links);
3667 	/*
3668 	 * Increment our usage count if this is an external consumer, so we
3669 	 * can't get unloaded until the external consumer (most likely a
3670 	 * FETD) unloads and frees his pool.
3671 	 *
3672 	 * XXX KDM will this increment the caller's module use count, or
3673 	 * mine?
3674 	 */
3675 #if 0
3676 	if ((pool_type != CTL_POOL_EMERGENCY)
3677 	 && (pool_type != CTL_POOL_INTERNAL)
3678 	 && (pool_type != CTL_POOL_4OTHERSC))
3679 		MOD_INC_USE_COUNT;
3680 #endif
3681 
3682 	mtx_unlock(&ctl_softc->pool_lock);
3683 
3684 	*npool = pool;
3685 
3686 bailout:
3687 
3688 	return (retval);
3689 }
3690 
3691 static int
3692 ctl_pool_acquire(struct ctl_io_pool *pool)
3693 {
3694 
3695 	mtx_assert(&pool->ctl_softc->pool_lock, MA_OWNED);
3696 
3697 	if (pool->flags & CTL_POOL_FLAG_INVALID)
3698 		return (EINVAL);
3699 
3700 	pool->refcount++;
3701 
3702 	return (0);
3703 }
3704 
3705 static void
3706 ctl_pool_release(struct ctl_io_pool *pool)
3707 {
3708 	struct ctl_softc *ctl_softc = pool->ctl_softc;
3709 	union ctl_io *io;
3710 
3711 	mtx_assert(&ctl_softc->pool_lock, MA_OWNED);
3712 
3713 	if (--pool->refcount != 0)
3714 		return;
3715 
3716 	while ((io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue)) != NULL) {
3717 		STAILQ_REMOVE(&pool->free_queue, &io->io_hdr, ctl_io_hdr,
3718 			      links);
3719 		free(io, M_CTLIO);
3720 	}
3721 
3722 	STAILQ_REMOVE(&ctl_softc->io_pools, pool, ctl_io_pool, links);
3723 	ctl_softc->num_pools--;
3724 
3725 	/*
3726 	 * XXX KDM will this decrement the caller's usage count or mine?
3727 	 */
3728 #if 0
3729 	if ((pool->type != CTL_POOL_EMERGENCY)
3730 	 && (pool->type != CTL_POOL_INTERNAL)
3731 	 && (pool->type != CTL_POOL_4OTHERSC))
3732 		MOD_DEC_USE_COUNT;
3733 #endif
3734 
3735 	free(pool, M_CTL);
3736 }
3737 
3738 void
3739 ctl_pool_free(struct ctl_io_pool *pool)
3740 {
3741 	struct ctl_softc *ctl_softc;
3742 
3743 	if (pool == NULL)
3744 		return;
3745 
3746 	ctl_softc = pool->ctl_softc;
3747 	mtx_lock(&ctl_softc->pool_lock);
3748 	pool->flags |= CTL_POOL_FLAG_INVALID;
3749 	ctl_pool_release(pool);
3750 	mtx_unlock(&ctl_softc->pool_lock);
3751 }
3752 
3753 /*
3754  * This routine does not block (except for spinlocks of course).
3755  * It tries to allocate a ctl_io union from the caller's pool as quickly as
3756  * possible.
3757  */
3758 union ctl_io *
3759 ctl_alloc_io(void *pool_ref)
3760 {
3761 	union ctl_io *io;
3762 	struct ctl_softc *ctl_softc;
3763 	struct ctl_io_pool *pool, *npool;
3764 	struct ctl_io_pool *emergency_pool;
3765 
3766 	pool = (struct ctl_io_pool *)pool_ref;
3767 
3768 	if (pool == NULL) {
3769 		printf("%s: pool is NULL\n", __func__);
3770 		return (NULL);
3771 	}
3772 
3773 	emergency_pool = NULL;
3774 
3775 	ctl_softc = pool->ctl_softc;
3776 
3777 	mtx_lock(&ctl_softc->pool_lock);
3778 	/*
3779 	 * First, try to get the io structure from the user's pool.
3780 	 */
3781 	if (ctl_pool_acquire(pool) == 0) {
3782 		io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue);
3783 		if (io != NULL) {
3784 			STAILQ_REMOVE_HEAD(&pool->free_queue, links);
3785 			pool->total_allocated++;
3786 			pool->free_ctl_io--;
3787 			mtx_unlock(&ctl_softc->pool_lock);
3788 			return (io);
3789 		} else
3790 			ctl_pool_release(pool);
3791 	}
3792 	/*
3793 	 * If he doesn't have any io structures left, search for an
3794 	 * emergency pool and grab one from there.
3795 	 */
3796 	STAILQ_FOREACH(npool, &ctl_softc->io_pools, links) {
3797 		if (npool->type != CTL_POOL_EMERGENCY)
3798 			continue;
3799 
3800 		if (ctl_pool_acquire(npool) != 0)
3801 			continue;
3802 
3803 		emergency_pool = npool;
3804 
3805 		io = (union ctl_io *)STAILQ_FIRST(&npool->free_queue);
3806 		if (io != NULL) {
3807 			STAILQ_REMOVE_HEAD(&npool->free_queue, links);
3808 			npool->total_allocated++;
3809 			npool->free_ctl_io--;
3810 			mtx_unlock(&ctl_softc->pool_lock);
3811 			return (io);
3812 		} else
3813 			ctl_pool_release(npool);
3814 	}
3815 
3816 	/* Drop the spinlock before we malloc */
3817 	mtx_unlock(&ctl_softc->pool_lock);
3818 
3819 	/*
3820 	 * The emergency pool (if it exists) didn't have one, so try an
3821 	 * atomic (i.e. nonblocking) malloc and see if we get lucky.
3822 	 */
3823 	io = (union ctl_io *)malloc(sizeof(*io), M_CTLIO, M_NOWAIT);
3824 	if (io != NULL) {
3825 		/*
3826 		 * If the emergency pool exists but is empty, add this
3827 		 * ctl_io to its list when it gets freed.
3828 		 */
3829 		if (emergency_pool != NULL) {
3830 			mtx_lock(&ctl_softc->pool_lock);
3831 			if (ctl_pool_acquire(emergency_pool) == 0) {
3832 				io->io_hdr.pool = emergency_pool;
3833 				emergency_pool->total_ctl_io++;
3834 				/*
3835 				 * Need to bump this, otherwise
3836 				 * total_allocated and total_freed won't
3837 				 * match when we no longer have anything
3838 				 * outstanding.
3839 				 */
3840 				emergency_pool->total_allocated++;
3841 			}
3842 			mtx_unlock(&ctl_softc->pool_lock);
3843 		} else
3844 			io->io_hdr.pool = NULL;
3845 	}
3846 
3847 	return (io);
3848 }
3849 
3850 void
3851 ctl_free_io(union ctl_io *io)
3852 {
3853 	if (io == NULL)
3854 		return;
3855 
3856 	/*
3857 	 * If this ctl_io has a pool, return it to that pool.
3858 	 */
3859 	if (io->io_hdr.pool != NULL) {
3860 		struct ctl_io_pool *pool;
3861 
3862 		pool = (struct ctl_io_pool *)io->io_hdr.pool;
3863 		mtx_lock(&pool->ctl_softc->pool_lock);
3864 		io->io_hdr.io_type = 0xff;
3865 		STAILQ_INSERT_TAIL(&pool->free_queue, &io->io_hdr, links);
3866 		pool->total_freed++;
3867 		pool->free_ctl_io++;
3868 		ctl_pool_release(pool);
3869 		mtx_unlock(&pool->ctl_softc->pool_lock);
3870 	} else {
3871 		/*
3872 		 * Otherwise, just free it.  We probably malloced it and
3873 		 * the emergency pool wasn't available.
3874 		 */
3875 		free(io, M_CTLIO);
3876 	}
3877 
3878 }
3879 
3880 void
3881 ctl_zero_io(union ctl_io *io)
3882 {
3883 	void *pool_ref;
3884 
3885 	if (io == NULL)
3886 		return;
3887 
3888 	/*
3889 	 * May need to preserve linked list pointers at some point too.
3890 	 */
3891 	pool_ref = io->io_hdr.pool;
3892 
3893 	memset(io, 0, sizeof(*io));
3894 
3895 	io->io_hdr.pool = pool_ref;
3896 }
3897 
3898 /*
3899  * This routine is currently used for internal copies of ctl_ios that need
3900  * to persist for some reason after we've already returned status to the
3901  * FETD.  (Thus the flag set.)
3902  *
3903  * XXX XXX
3904  * Note that this makes a blind copy of all fields in the ctl_io, except
3905  * for the pool reference.  This includes any memory that has been
3906  * allocated!  That memory will no longer be valid after done has been
3907  * called, so this would be VERY DANGEROUS for command that actually does
3908  * any reads or writes.  Right now (11/7/2005), this is only used for immediate
3909  * start and stop commands, which don't transfer any data, so this is not a
3910  * problem.  If it is used for anything else, the caller would also need to
3911  * allocate data buffer space and this routine would need to be modified to
3912  * copy the data buffer(s) as well.
3913  */
3914 void
3915 ctl_copy_io(union ctl_io *src, union ctl_io *dest)
3916 {
3917 	void *pool_ref;
3918 
3919 	if ((src == NULL)
3920 	 || (dest == NULL))
3921 		return;
3922 
3923 	/*
3924 	 * May need to preserve linked list pointers at some point too.
3925 	 */
3926 	pool_ref = dest->io_hdr.pool;
3927 
3928 	memcpy(dest, src, ctl_min(sizeof(*src), sizeof(*dest)));
3929 
3930 	dest->io_hdr.pool = pool_ref;
3931 	/*
3932 	 * We need to know that this is an internal copy, and doesn't need
3933 	 * to get passed back to the FETD that allocated it.
3934 	 */
3935 	dest->io_hdr.flags |= CTL_FLAG_INT_COPY;
3936 }
3937 
3938 #ifdef NEEDTOPORT
3939 static void
3940 ctl_update_power_subpage(struct copan_power_subpage *page)
3941 {
3942 	int num_luns, num_partitions, config_type;
3943 	struct ctl_softc *softc;
3944 	cs_BOOL_t aor_present, shelf_50pct_power;
3945 	cs_raidset_personality_t rs_type;
3946 	int max_active_luns;
3947 
3948 	softc = control_softc;
3949 
3950 	/* subtract out the processor LUN */
3951 	num_luns = softc->num_luns - 1;
3952 	/*
3953 	 * Default to 7 LUNs active, which was the only number we allowed
3954 	 * in the past.
3955 	 */
3956 	max_active_luns = 7;
3957 
3958 	num_partitions = config_GetRsPartitionInfo();
3959 	config_type = config_GetConfigType();
3960 	shelf_50pct_power = config_GetShelfPowerMode();
3961 	aor_present = config_IsAorRsPresent();
3962 
3963 	rs_type = ddb_GetRsRaidType(1);
3964 	if ((rs_type != CS_RAIDSET_PERSONALITY_RAID5)
3965 	 && (rs_type != CS_RAIDSET_PERSONALITY_RAID1)) {
3966 		EPRINT(0, "Unsupported RS type %d!", rs_type);
3967 	}
3968 
3969 
3970 	page->total_luns = num_luns;
3971 
3972 	switch (config_type) {
3973 	case 40:
3974 		/*
3975 		 * In a 40 drive configuration, it doesn't matter what DC
3976 		 * cards we have, whether we have AOR enabled or not,
3977 		 * partitioning or not, or what type of RAIDset we have.
3978 		 * In that scenario, we can power up every LUN we present
3979 		 * to the user.
3980 		 */
3981 		max_active_luns = num_luns;
3982 
3983 		break;
3984 	case 64:
3985 		if (shelf_50pct_power == CS_FALSE) {
3986 			/* 25% power */
3987 			if (aor_present == CS_TRUE) {
3988 				if (rs_type ==
3989 				     CS_RAIDSET_PERSONALITY_RAID5) {
3990 					max_active_luns = 7;
3991 				} else if (rs_type ==
3992 					 CS_RAIDSET_PERSONALITY_RAID1){
3993 					max_active_luns = 14;
3994 				} else {
3995 					/* XXX KDM now what?? */
3996 				}
3997 			} else {
3998 				if (rs_type ==
3999 				     CS_RAIDSET_PERSONALITY_RAID5) {
4000 					max_active_luns = 8;
4001 				} else if (rs_type ==
4002 					 CS_RAIDSET_PERSONALITY_RAID1){
4003 					max_active_luns = 16;
4004 				} else {
4005 					/* XXX KDM now what?? */
4006 				}
4007 			}
4008 		} else {
4009 			/* 50% power */
4010 			/*
4011 			 * With 50% power in a 64 drive configuration, we
4012 			 * can power all LUNs we present.
4013 			 */
4014 			max_active_luns = num_luns;
4015 		}
4016 		break;
4017 	case 112:
4018 		if (shelf_50pct_power == CS_FALSE) {
4019 			/* 25% power */
4020 			if (aor_present == CS_TRUE) {
4021 				if (rs_type ==
4022 				     CS_RAIDSET_PERSONALITY_RAID5) {
4023 					max_active_luns = 7;
4024 				} else if (rs_type ==
4025 					 CS_RAIDSET_PERSONALITY_RAID1){
4026 					max_active_luns = 14;
4027 				} else {
4028 					/* XXX KDM now what?? */
4029 				}
4030 			} else {
4031 				if (rs_type ==
4032 				     CS_RAIDSET_PERSONALITY_RAID5) {
4033 					max_active_luns = 8;
4034 				} else if (rs_type ==
4035 					 CS_RAIDSET_PERSONALITY_RAID1){
4036 					max_active_luns = 16;
4037 				} else {
4038 					/* XXX KDM now what?? */
4039 				}
4040 			}
4041 		} else {
4042 			/* 50% power */
4043 			if (aor_present == CS_TRUE) {
4044 				if (rs_type ==
4045 				     CS_RAIDSET_PERSONALITY_RAID5) {
4046 					max_active_luns = 14;
4047 				} else if (rs_type ==
4048 					 CS_RAIDSET_PERSONALITY_RAID1){
4049 					/*
4050 					 * We're assuming here that disk
4051 					 * caching is enabled, and so we're
4052 					 * able to power up half of each
4053 					 * LUN, and cache all writes.
4054 					 */
4055 					max_active_luns = num_luns;
4056 				} else {
4057 					/* XXX KDM now what?? */
4058 				}
4059 			} else {
4060 				if (rs_type ==
4061 				     CS_RAIDSET_PERSONALITY_RAID5) {
4062 					max_active_luns = 15;
4063 				} else if (rs_type ==
4064 					 CS_RAIDSET_PERSONALITY_RAID1){
4065 					max_active_luns = 30;
4066 				} else {
4067 					/* XXX KDM now what?? */
4068 				}
4069 			}
4070 		}
4071 		break;
4072 	default:
4073 		/*
4074 		 * In this case, we have an unknown configuration, so we
4075 		 * just use the default from above.
4076 		 */
4077 		break;
4078 	}
4079 
4080 	page->max_active_luns = max_active_luns;
4081 #if 0
4082 	printk("%s: total_luns = %d, max_active_luns = %d\n", __func__,
4083 	       page->total_luns, page->max_active_luns);
4084 #endif
4085 }
4086 #endif /* NEEDTOPORT */
4087 
4088 /*
4089  * This routine could be used in the future to load default and/or saved
4090  * mode page parameters for a particuar lun.
4091  */
4092 static int
4093 ctl_init_page_index(struct ctl_lun *lun)
4094 {
4095 	int i;
4096 	struct ctl_page_index *page_index;
4097 	struct ctl_softc *softc;
4098 
4099 	memcpy(&lun->mode_pages.index, page_index_template,
4100 	       sizeof(page_index_template));
4101 
4102 	softc = lun->ctl_softc;
4103 
4104 	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
4105 
4106 		page_index = &lun->mode_pages.index[i];
4107 		/*
4108 		 * If this is a disk-only mode page, there's no point in
4109 		 * setting it up.  For some pages, we have to have some
4110 		 * basic information about the disk in order to calculate the
4111 		 * mode page data.
4112 		 */
4113 		if ((lun->be_lun->lun_type != T_DIRECT)
4114 		 && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
4115 			continue;
4116 
4117 		switch (page_index->page_code & SMPH_PC_MASK) {
4118 		case SMS_FORMAT_DEVICE_PAGE: {
4119 			struct scsi_format_page *format_page;
4120 
4121 			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4122 				panic("subpage is incorrect!");
4123 
4124 			/*
4125 			 * Sectors per track are set above.  Bytes per
4126 			 * sector need to be set here on a per-LUN basis.
4127 			 */
4128 			memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
4129 			       &format_page_default,
4130 			       sizeof(format_page_default));
4131 			memcpy(&lun->mode_pages.format_page[
4132 			       CTL_PAGE_CHANGEABLE], &format_page_changeable,
4133 			       sizeof(format_page_changeable));
4134 			memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
4135 			       &format_page_default,
4136 			       sizeof(format_page_default));
4137 			memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
4138 			       &format_page_default,
4139 			       sizeof(format_page_default));
4140 
4141 			format_page = &lun->mode_pages.format_page[
4142 				CTL_PAGE_CURRENT];
4143 			scsi_ulto2b(lun->be_lun->blocksize,
4144 				    format_page->bytes_per_sector);
4145 
4146 			format_page = &lun->mode_pages.format_page[
4147 				CTL_PAGE_DEFAULT];
4148 			scsi_ulto2b(lun->be_lun->blocksize,
4149 				    format_page->bytes_per_sector);
4150 
4151 			format_page = &lun->mode_pages.format_page[
4152 				CTL_PAGE_SAVED];
4153 			scsi_ulto2b(lun->be_lun->blocksize,
4154 				    format_page->bytes_per_sector);
4155 
4156 			page_index->page_data =
4157 				(uint8_t *)lun->mode_pages.format_page;
4158 			break;
4159 		}
4160 		case SMS_RIGID_DISK_PAGE: {
4161 			struct scsi_rigid_disk_page *rigid_disk_page;
4162 			uint32_t sectors_per_cylinder;
4163 			uint64_t cylinders;
4164 #ifndef	__XSCALE__
4165 			int shift;
4166 #endif /* !__XSCALE__ */
4167 
4168 			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4169 				panic("invalid subpage value %d",
4170 				      page_index->subpage);
4171 
4172 			/*
4173 			 * Rotation rate and sectors per track are set
4174 			 * above.  We calculate the cylinders here based on
4175 			 * capacity.  Due to the number of heads and
4176 			 * sectors per track we're using, smaller arrays
4177 			 * may turn out to have 0 cylinders.  Linux and
4178 			 * FreeBSD don't pay attention to these mode pages
4179 			 * to figure out capacity, but Solaris does.  It
4180 			 * seems to deal with 0 cylinders just fine, and
4181 			 * works out a fake geometry based on the capacity.
4182 			 */
4183 			memcpy(&lun->mode_pages.rigid_disk_page[
4184 			       CTL_PAGE_CURRENT], &rigid_disk_page_default,
4185 			       sizeof(rigid_disk_page_default));
4186 			memcpy(&lun->mode_pages.rigid_disk_page[
4187 			       CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
4188 			       sizeof(rigid_disk_page_changeable));
4189 			memcpy(&lun->mode_pages.rigid_disk_page[
4190 			       CTL_PAGE_DEFAULT], &rigid_disk_page_default,
4191 			       sizeof(rigid_disk_page_default));
4192 			memcpy(&lun->mode_pages.rigid_disk_page[
4193 			       CTL_PAGE_SAVED], &rigid_disk_page_default,
4194 			       sizeof(rigid_disk_page_default));
4195 
4196 			sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
4197 				CTL_DEFAULT_HEADS;
4198 
4199 			/*
4200 			 * The divide method here will be more accurate,
4201 			 * probably, but results in floating point being
4202 			 * used in the kernel on i386 (__udivdi3()).  On the
4203 			 * XScale, though, __udivdi3() is implemented in
4204 			 * software.
4205 			 *
4206 			 * The shift method for cylinder calculation is
4207 			 * accurate if sectors_per_cylinder is a power of
4208 			 * 2.  Otherwise it might be slightly off -- you
4209 			 * might have a bit of a truncation problem.
4210 			 */
4211 #ifdef	__XSCALE__
4212 			cylinders = (lun->be_lun->maxlba + 1) /
4213 				sectors_per_cylinder;
4214 #else
4215 			for (shift = 31; shift > 0; shift--) {
4216 				if (sectors_per_cylinder & (1 << shift))
4217 					break;
4218 			}
4219 			cylinders = (lun->be_lun->maxlba + 1) >> shift;
4220 #endif
4221 
4222 			/*
4223 			 * We've basically got 3 bytes, or 24 bits for the
4224 			 * cylinder size in the mode page.  If we're over,
4225 			 * just round down to 2^24.
4226 			 */
4227 			if (cylinders > 0xffffff)
4228 				cylinders = 0xffffff;
4229 
4230 			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4231 				CTL_PAGE_CURRENT];
4232 			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4233 
4234 			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4235 				CTL_PAGE_DEFAULT];
4236 			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4237 
4238 			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4239 				CTL_PAGE_SAVED];
4240 			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4241 
4242 			page_index->page_data =
4243 				(uint8_t *)lun->mode_pages.rigid_disk_page;
4244 			break;
4245 		}
4246 		case SMS_CACHING_PAGE: {
4247 
4248 			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4249 				panic("invalid subpage value %d",
4250 				      page_index->subpage);
4251 			/*
4252 			 * Defaults should be okay here, no calculations
4253 			 * needed.
4254 			 */
4255 			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4256 			       &caching_page_default,
4257 			       sizeof(caching_page_default));
4258 			memcpy(&lun->mode_pages.caching_page[
4259 			       CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4260 			       sizeof(caching_page_changeable));
4261 			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4262 			       &caching_page_default,
4263 			       sizeof(caching_page_default));
4264 			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4265 			       &caching_page_default,
4266 			       sizeof(caching_page_default));
4267 			page_index->page_data =
4268 				(uint8_t *)lun->mode_pages.caching_page;
4269 			break;
4270 		}
4271 		case SMS_CONTROL_MODE_PAGE: {
4272 
4273 			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4274 				panic("invalid subpage value %d",
4275 				      page_index->subpage);
4276 
4277 			/*
4278 			 * Defaults should be okay here, no calculations
4279 			 * needed.
4280 			 */
4281 			memcpy(&lun->mode_pages.control_page[CTL_PAGE_CURRENT],
4282 			       &control_page_default,
4283 			       sizeof(control_page_default));
4284 			memcpy(&lun->mode_pages.control_page[
4285 			       CTL_PAGE_CHANGEABLE], &control_page_changeable,
4286 			       sizeof(control_page_changeable));
4287 			memcpy(&lun->mode_pages.control_page[CTL_PAGE_DEFAULT],
4288 			       &control_page_default,
4289 			       sizeof(control_page_default));
4290 			memcpy(&lun->mode_pages.control_page[CTL_PAGE_SAVED],
4291 			       &control_page_default,
4292 			       sizeof(control_page_default));
4293 			page_index->page_data =
4294 				(uint8_t *)lun->mode_pages.control_page;
4295 			break;
4296 
4297 		}
4298 		case SMS_VENDOR_SPECIFIC_PAGE:{
4299 			switch (page_index->subpage) {
4300 			case PWR_SUBPAGE_CODE: {
4301 				struct copan_power_subpage *current_page,
4302 							   *saved_page;
4303 
4304 				memcpy(&lun->mode_pages.power_subpage[
4305 				       CTL_PAGE_CURRENT],
4306 				       &power_page_default,
4307 				       sizeof(power_page_default));
4308 				memcpy(&lun->mode_pages.power_subpage[
4309 				       CTL_PAGE_CHANGEABLE],
4310 				       &power_page_changeable,
4311 				       sizeof(power_page_changeable));
4312 				memcpy(&lun->mode_pages.power_subpage[
4313 				       CTL_PAGE_DEFAULT],
4314 				       &power_page_default,
4315 				       sizeof(power_page_default));
4316 				memcpy(&lun->mode_pages.power_subpage[
4317 				       CTL_PAGE_SAVED],
4318 				       &power_page_default,
4319 				       sizeof(power_page_default));
4320 				page_index->page_data =
4321 				    (uint8_t *)lun->mode_pages.power_subpage;
4322 
4323 				current_page = (struct copan_power_subpage *)
4324 					(page_index->page_data +
4325 					 (page_index->page_len *
4326 					  CTL_PAGE_CURRENT));
4327 			        saved_page = (struct copan_power_subpage *)
4328 				        (page_index->page_data +
4329 					 (page_index->page_len *
4330 					  CTL_PAGE_SAVED));
4331 				break;
4332 			}
4333 			case APS_SUBPAGE_CODE: {
4334 				struct copan_aps_subpage *current_page,
4335 							 *saved_page;
4336 
4337 				// This gets set multiple times but
4338 				// it should always be the same. It's
4339 				// only done during init so who cares.
4340 				index_to_aps_page = i;
4341 
4342 				memcpy(&lun->mode_pages.aps_subpage[
4343 				       CTL_PAGE_CURRENT],
4344 				       &aps_page_default,
4345 				       sizeof(aps_page_default));
4346 				memcpy(&lun->mode_pages.aps_subpage[
4347 				       CTL_PAGE_CHANGEABLE],
4348 				       &aps_page_changeable,
4349 				       sizeof(aps_page_changeable));
4350 				memcpy(&lun->mode_pages.aps_subpage[
4351 				       CTL_PAGE_DEFAULT],
4352 				       &aps_page_default,
4353 				       sizeof(aps_page_default));
4354 				memcpy(&lun->mode_pages.aps_subpage[
4355 				       CTL_PAGE_SAVED],
4356 				       &aps_page_default,
4357 				       sizeof(aps_page_default));
4358 				page_index->page_data =
4359 					(uint8_t *)lun->mode_pages.aps_subpage;
4360 
4361 				current_page = (struct copan_aps_subpage *)
4362 					(page_index->page_data +
4363 					 (page_index->page_len *
4364 					  CTL_PAGE_CURRENT));
4365 				saved_page = (struct copan_aps_subpage *)
4366 					(page_index->page_data +
4367 					 (page_index->page_len *
4368 					  CTL_PAGE_SAVED));
4369 				break;
4370 			}
4371 			case DBGCNF_SUBPAGE_CODE: {
4372 				struct copan_debugconf_subpage *current_page,
4373 							       *saved_page;
4374 
4375 				memcpy(&lun->mode_pages.debugconf_subpage[
4376 				       CTL_PAGE_CURRENT],
4377 				       &debugconf_page_default,
4378 				       sizeof(debugconf_page_default));
4379 				memcpy(&lun->mode_pages.debugconf_subpage[
4380 				       CTL_PAGE_CHANGEABLE],
4381 				       &debugconf_page_changeable,
4382 				       sizeof(debugconf_page_changeable));
4383 				memcpy(&lun->mode_pages.debugconf_subpage[
4384 				       CTL_PAGE_DEFAULT],
4385 				       &debugconf_page_default,
4386 				       sizeof(debugconf_page_default));
4387 				memcpy(&lun->mode_pages.debugconf_subpage[
4388 				       CTL_PAGE_SAVED],
4389 				       &debugconf_page_default,
4390 				       sizeof(debugconf_page_default));
4391 				page_index->page_data =
4392 					(uint8_t *)lun->mode_pages.debugconf_subpage;
4393 
4394 				current_page = (struct copan_debugconf_subpage *)
4395 					(page_index->page_data +
4396 					 (page_index->page_len *
4397 					  CTL_PAGE_CURRENT));
4398 				saved_page = (struct copan_debugconf_subpage *)
4399 					(page_index->page_data +
4400 					 (page_index->page_len *
4401 					  CTL_PAGE_SAVED));
4402 				break;
4403 			}
4404 			default:
4405 				panic("invalid subpage value %d",
4406 				      page_index->subpage);
4407 				break;
4408 			}
4409    			break;
4410 		}
4411 		default:
4412 			panic("invalid page value %d",
4413 			      page_index->page_code & SMPH_PC_MASK);
4414 			break;
4415     	}
4416 	}
4417 
4418 	return (CTL_RETVAL_COMPLETE);
4419 }
4420 
4421 /*
4422  * LUN allocation.
4423  *
4424  * Requirements:
4425  * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4426  *   wants us to allocate the LUN and he can block.
4427  * - ctl_softc is always set
4428  * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4429  *
4430  * Returns 0 for success, non-zero (errno) for failure.
4431  */
4432 static int
4433 ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4434 	      struct ctl_be_lun *const be_lun, struct ctl_id target_id)
4435 {
4436 	struct ctl_lun *nlun, *lun;
4437 	struct ctl_port *port;
4438 	struct scsi_vpd_id_descriptor *desc;
4439 	struct scsi_vpd_id_t10 *t10id;
4440 	const char *eui, *naa, *scsiname, *vendor;
4441 	int lun_number, i, lun_malloced;
4442 	int devidlen, idlen1, idlen2 = 0, len;
4443 
4444 	if (be_lun == NULL)
4445 		return (EINVAL);
4446 
4447 	/*
4448 	 * We currently only support Direct Access or Processor LUN types.
4449 	 */
4450 	switch (be_lun->lun_type) {
4451 	case T_DIRECT:
4452 		break;
4453 	case T_PROCESSOR:
4454 		break;
4455 	case T_SEQUENTIAL:
4456 	case T_CHANGER:
4457 	default:
4458 		be_lun->lun_config_status(be_lun->be_lun,
4459 					  CTL_LUN_CONFIG_FAILURE);
4460 		break;
4461 	}
4462 	if (ctl_lun == NULL) {
4463 		lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4464 		lun_malloced = 1;
4465 	} else {
4466 		lun_malloced = 0;
4467 		lun = ctl_lun;
4468 	}
4469 
4470 	memset(lun, 0, sizeof(*lun));
4471 	if (lun_malloced)
4472 		lun->flags = CTL_LUN_MALLOCED;
4473 
4474 	/* Generate LUN ID. */
4475 	devidlen = max(CTL_DEVID_MIN_LEN,
4476 	    strnlen(be_lun->device_id, CTL_DEVID_LEN));
4477 	idlen1 = sizeof(*t10id) + devidlen;
4478 	len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4479 	scsiname = ctl_get_opt(&be_lun->options, "scsiname");
4480 	if (scsiname != NULL) {
4481 		idlen2 = roundup2(strlen(scsiname) + 1, 4);
4482 		len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4483 	}
4484 	eui = ctl_get_opt(&be_lun->options, "eui");
4485 	if (eui != NULL) {
4486 		len += sizeof(struct scsi_vpd_id_descriptor) + 8;
4487 	}
4488 	naa = ctl_get_opt(&be_lun->options, "naa");
4489 	if (naa != NULL) {
4490 		len += sizeof(struct scsi_vpd_id_descriptor) + 8;
4491 	}
4492 	lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4493 	    M_CTL, M_WAITOK | M_ZERO);
4494 	lun->lun_devid->len = len;
4495 	desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4496 	desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4497 	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4498 	desc->length = idlen1;
4499 	t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4500 	memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4501 	if ((vendor = ctl_get_opt(&be_lun->options, "vendor")) == NULL) {
4502 		strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4503 	} else {
4504 		strncpy(t10id->vendor, vendor,
4505 		    min(sizeof(t10id->vendor), strlen(vendor)));
4506 	}
4507 	strncpy((char *)t10id->vendor_spec_id,
4508 	    (char *)be_lun->device_id, devidlen);
4509 	if (scsiname != NULL) {
4510 		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4511 		    desc->length);
4512 		desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4513 		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4514 		    SVPD_ID_TYPE_SCSI_NAME;
4515 		desc->length = idlen2;
4516 		strlcpy(desc->identifier, scsiname, idlen2);
4517 	}
4518 	if (eui != NULL) {
4519 		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4520 		    desc->length);
4521 		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4522 		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4523 		    SVPD_ID_TYPE_EUI64;
4524 		desc->length = 8;
4525 		scsi_u64to8b(strtouq(eui, NULL, 0), desc->identifier);
4526 	}
4527 	if (naa != NULL) {
4528 		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4529 		    desc->length);
4530 		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4531 		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4532 		    SVPD_ID_TYPE_NAA;
4533 		desc->length = 8;
4534 		scsi_u64to8b(strtouq(naa, NULL, 0), desc->identifier);
4535 	}
4536 
4537 	mtx_lock(&ctl_softc->ctl_lock);
4538 	/*
4539 	 * See if the caller requested a particular LUN number.  If so, see
4540 	 * if it is available.  Otherwise, allocate the first available LUN.
4541 	 */
4542 	if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4543 		if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4544 		 || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4545 			mtx_unlock(&ctl_softc->ctl_lock);
4546 			if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4547 				printf("ctl: requested LUN ID %d is higher "
4548 				       "than CTL_MAX_LUNS - 1 (%d)\n",
4549 				       be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4550 			} else {
4551 				/*
4552 				 * XXX KDM return an error, or just assign
4553 				 * another LUN ID in this case??
4554 				 */
4555 				printf("ctl: requested LUN ID %d is already "
4556 				       "in use\n", be_lun->req_lun_id);
4557 			}
4558 			if (lun->flags & CTL_LUN_MALLOCED)
4559 				free(lun, M_CTL);
4560 			be_lun->lun_config_status(be_lun->be_lun,
4561 						  CTL_LUN_CONFIG_FAILURE);
4562 			return (ENOSPC);
4563 		}
4564 		lun_number = be_lun->req_lun_id;
4565 	} else {
4566 		lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, CTL_MAX_LUNS);
4567 		if (lun_number == -1) {
4568 			mtx_unlock(&ctl_softc->ctl_lock);
4569 			printf("ctl: can't allocate LUN on target %ju, out of "
4570 			       "LUNs\n", (uintmax_t)target_id.id);
4571 			if (lun->flags & CTL_LUN_MALLOCED)
4572 				free(lun, M_CTL);
4573 			be_lun->lun_config_status(be_lun->be_lun,
4574 						  CTL_LUN_CONFIG_FAILURE);
4575 			return (ENOSPC);
4576 		}
4577 	}
4578 	ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4579 
4580 	mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4581 	lun->target = target_id;
4582 	lun->lun = lun_number;
4583 	lun->be_lun = be_lun;
4584 	/*
4585 	 * The processor LUN is always enabled.  Disk LUNs come on line
4586 	 * disabled, and must be enabled by the backend.
4587 	 */
4588 	lun->flags |= CTL_LUN_DISABLED;
4589 	lun->backend = be_lun->be;
4590 	be_lun->ctl_lun = lun;
4591 	be_lun->lun_id = lun_number;
4592 	atomic_add_int(&be_lun->be->num_luns, 1);
4593 	if (be_lun->flags & CTL_LUN_FLAG_POWERED_OFF)
4594 		lun->flags |= CTL_LUN_STOPPED;
4595 
4596 	if (be_lun->flags & CTL_LUN_FLAG_INOPERABLE)
4597 		lun->flags |= CTL_LUN_INOPERABLE;
4598 
4599 	if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4600 		lun->flags |= CTL_LUN_PRIMARY_SC;
4601 
4602 	lun->ctl_softc = ctl_softc;
4603 	TAILQ_INIT(&lun->ooa_queue);
4604 	TAILQ_INIT(&lun->blocked_queue);
4605 	STAILQ_INIT(&lun->error_list);
4606 	ctl_tpc_lun_init(lun);
4607 
4608 	/*
4609 	 * Initialize the mode page index.
4610 	 */
4611 	ctl_init_page_index(lun);
4612 
4613 	/*
4614 	 * Set the poweron UA for all initiators on this LUN only.
4615 	 */
4616 	for (i = 0; i < CTL_MAX_INITIATORS; i++)
4617 		lun->pending_ua[i] = CTL_UA_POWERON;
4618 
4619 	/*
4620 	 * Now, before we insert this lun on the lun list, set the lun
4621 	 * inventory changed UA for all other luns.
4622 	 */
4623 	STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4624 		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
4625 			nlun->pending_ua[i] |= CTL_UA_LUN_CHANGE;
4626 		}
4627 	}
4628 
4629 	STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4630 
4631 	ctl_softc->ctl_luns[lun_number] = lun;
4632 
4633 	ctl_softc->num_luns++;
4634 
4635 	/* Setup statistics gathering */
4636 	lun->stats.device_type = be_lun->lun_type;
4637 	lun->stats.lun_number = lun_number;
4638 	if (lun->stats.device_type == T_DIRECT)
4639 		lun->stats.blocksize = be_lun->blocksize;
4640 	else
4641 		lun->stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4642 	for (i = 0;i < CTL_MAX_PORTS;i++)
4643 		lun->stats.ports[i].targ_port = i;
4644 
4645 	mtx_unlock(&ctl_softc->ctl_lock);
4646 
4647 	lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4648 
4649 	/*
4650 	 * Run through each registered FETD and bring it online if it isn't
4651 	 * already.  Enable the target ID if it hasn't been enabled, and
4652 	 * enable this particular LUN.
4653 	 */
4654 	STAILQ_FOREACH(port, &ctl_softc->port_list, links) {
4655 		int retval;
4656 
4657 		retval = port->lun_enable(port->targ_lun_arg, target_id,lun_number);
4658 		if (retval != 0) {
4659 			printf("ctl_alloc_lun: FETD %s port %d returned error "
4660 			       "%d for lun_enable on target %ju lun %d\n",
4661 			       port->port_name, port->targ_port, retval,
4662 			       (uintmax_t)target_id.id, lun_number);
4663 		} else
4664 			port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4665 	}
4666 	return (0);
4667 }
4668 
4669 /*
4670  * Delete a LUN.
4671  * Assumptions:
4672  * - LUN has already been marked invalid and any pending I/O has been taken
4673  *   care of.
4674  */
4675 static int
4676 ctl_free_lun(struct ctl_lun *lun)
4677 {
4678 	struct ctl_softc *softc;
4679 #if 0
4680 	struct ctl_port *port;
4681 #endif
4682 	struct ctl_lun *nlun;
4683 	int i;
4684 
4685 	softc = lun->ctl_softc;
4686 
4687 	mtx_assert(&softc->ctl_lock, MA_OWNED);
4688 
4689 	STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4690 
4691 	ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4692 
4693 	softc->ctl_luns[lun->lun] = NULL;
4694 
4695 	if (!TAILQ_EMPTY(&lun->ooa_queue))
4696 		panic("Freeing a LUN %p with outstanding I/O!!\n", lun);
4697 
4698 	softc->num_luns--;
4699 
4700 	/*
4701 	 * XXX KDM this scheme only works for a single target/multiple LUN
4702 	 * setup.  It needs to be revamped for a multiple target scheme.
4703 	 *
4704 	 * XXX KDM this results in port->lun_disable() getting called twice,
4705 	 * once when ctl_disable_lun() is called, and a second time here.
4706 	 * We really need to re-think the LUN disable semantics.  There
4707 	 * should probably be several steps/levels to LUN removal:
4708 	 *  - disable
4709 	 *  - invalidate
4710 	 *  - free
4711  	 *
4712 	 * Right now we only have a disable method when communicating to
4713 	 * the front end ports, at least for individual LUNs.
4714 	 */
4715 #if 0
4716 	STAILQ_FOREACH(port, &softc->port_list, links) {
4717 		int retval;
4718 
4719 		retval = port->lun_disable(port->targ_lun_arg, lun->target,
4720 					 lun->lun);
4721 		if (retval != 0) {
4722 			printf("ctl_free_lun: FETD %s port %d returned error "
4723 			       "%d for lun_disable on target %ju lun %jd\n",
4724 			       port->port_name, port->targ_port, retval,
4725 			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4726 		}
4727 
4728 		if (STAILQ_FIRST(&softc->lun_list) == NULL) {
4729 			port->status &= ~CTL_PORT_STATUS_LUN_ONLINE;
4730 
4731 			retval = port->targ_disable(port->targ_lun_arg,lun->target);
4732 			if (retval != 0) {
4733 				printf("ctl_free_lun: FETD %s port %d "
4734 				       "returned error %d for targ_disable on "
4735 				       "target %ju\n", port->port_name,
4736 				       port->targ_port, retval,
4737 				       (uintmax_t)lun->target.id);
4738 			} else
4739 				port->status &= ~CTL_PORT_STATUS_TARG_ONLINE;
4740 
4741 			if ((port->status & CTL_PORT_STATUS_TARG_ONLINE) != 0)
4742 				continue;
4743 
4744 #if 0
4745 			port->port_offline(port->onoff_arg);
4746 			port->status &= ~CTL_PORT_STATUS_ONLINE;
4747 #endif
4748 		}
4749 	}
4750 #endif
4751 
4752 	/*
4753 	 * Tell the backend to free resources, if this LUN has a backend.
4754 	 */
4755 	atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4756 	lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4757 
4758 	ctl_tpc_lun_shutdown(lun);
4759 	mtx_destroy(&lun->lun_lock);
4760 	free(lun->lun_devid, M_CTL);
4761 	if (lun->flags & CTL_LUN_MALLOCED)
4762 		free(lun, M_CTL);
4763 
4764 	STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4765 		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
4766 			nlun->pending_ua[i] |= CTL_UA_LUN_CHANGE;
4767 		}
4768 	}
4769 
4770 	return (0);
4771 }
4772 
4773 static void
4774 ctl_create_lun(struct ctl_be_lun *be_lun)
4775 {
4776 	struct ctl_softc *ctl_softc;
4777 
4778 	ctl_softc = control_softc;
4779 
4780 	/*
4781 	 * ctl_alloc_lun() should handle all potential failure cases.
4782 	 */
4783 	ctl_alloc_lun(ctl_softc, NULL, be_lun, ctl_softc->target);
4784 }
4785 
4786 int
4787 ctl_add_lun(struct ctl_be_lun *be_lun)
4788 {
4789 	struct ctl_softc *ctl_softc = control_softc;
4790 
4791 	mtx_lock(&ctl_softc->ctl_lock);
4792 	STAILQ_INSERT_TAIL(&ctl_softc->pending_lun_queue, be_lun, links);
4793 	mtx_unlock(&ctl_softc->ctl_lock);
4794 	wakeup(&ctl_softc->pending_lun_queue);
4795 
4796 	return (0);
4797 }
4798 
4799 int
4800 ctl_enable_lun(struct ctl_be_lun *be_lun)
4801 {
4802 	struct ctl_softc *ctl_softc;
4803 	struct ctl_port *port, *nport;
4804 	struct ctl_lun *lun;
4805 	int retval;
4806 
4807 	ctl_softc = control_softc;
4808 
4809 	lun = (struct ctl_lun *)be_lun->ctl_lun;
4810 
4811 	mtx_lock(&ctl_softc->ctl_lock);
4812 	mtx_lock(&lun->lun_lock);
4813 	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4814 		/*
4815 		 * eh?  Why did we get called if the LUN is already
4816 		 * enabled?
4817 		 */
4818 		mtx_unlock(&lun->lun_lock);
4819 		mtx_unlock(&ctl_softc->ctl_lock);
4820 		return (0);
4821 	}
4822 	lun->flags &= ~CTL_LUN_DISABLED;
4823 	mtx_unlock(&lun->lun_lock);
4824 
4825 	for (port = STAILQ_FIRST(&ctl_softc->port_list); port != NULL; port = nport) {
4826 		nport = STAILQ_NEXT(port, links);
4827 
4828 		/*
4829 		 * Drop the lock while we call the FETD's enable routine.
4830 		 * This can lead to a callback into CTL (at least in the
4831 		 * case of the internal initiator frontend.
4832 		 */
4833 		mtx_unlock(&ctl_softc->ctl_lock);
4834 		retval = port->lun_enable(port->targ_lun_arg, lun->target,lun->lun);
4835 		mtx_lock(&ctl_softc->ctl_lock);
4836 		if (retval != 0) {
4837 			printf("%s: FETD %s port %d returned error "
4838 			       "%d for lun_enable on target %ju lun %jd\n",
4839 			       __func__, port->port_name, port->targ_port, retval,
4840 			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4841 		}
4842 #if 0
4843 		 else {
4844             /* NOTE:  TODO:  why does lun enable affect port status? */
4845 			port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4846 		}
4847 #endif
4848 	}
4849 
4850 	mtx_unlock(&ctl_softc->ctl_lock);
4851 
4852 	return (0);
4853 }
4854 
4855 int
4856 ctl_disable_lun(struct ctl_be_lun *be_lun)
4857 {
4858 	struct ctl_softc *ctl_softc;
4859 	struct ctl_port *port;
4860 	struct ctl_lun *lun;
4861 	int retval;
4862 
4863 	ctl_softc = control_softc;
4864 
4865 	lun = (struct ctl_lun *)be_lun->ctl_lun;
4866 
4867 	mtx_lock(&ctl_softc->ctl_lock);
4868 	mtx_lock(&lun->lun_lock);
4869 	if (lun->flags & CTL_LUN_DISABLED) {
4870 		mtx_unlock(&lun->lun_lock);
4871 		mtx_unlock(&ctl_softc->ctl_lock);
4872 		return (0);
4873 	}
4874 	lun->flags |= CTL_LUN_DISABLED;
4875 	mtx_unlock(&lun->lun_lock);
4876 
4877 	STAILQ_FOREACH(port, &ctl_softc->port_list, links) {
4878 		mtx_unlock(&ctl_softc->ctl_lock);
4879 		/*
4880 		 * Drop the lock before we call the frontend's disable
4881 		 * routine, to avoid lock order reversals.
4882 		 *
4883 		 * XXX KDM what happens if the frontend list changes while
4884 		 * we're traversing it?  It's unlikely, but should be handled.
4885 		 */
4886 		retval = port->lun_disable(port->targ_lun_arg, lun->target,
4887 					 lun->lun);
4888 		mtx_lock(&ctl_softc->ctl_lock);
4889 		if (retval != 0) {
4890 			printf("ctl_alloc_lun: FETD %s port %d returned error "
4891 			       "%d for lun_disable on target %ju lun %jd\n",
4892 			       port->port_name, port->targ_port, retval,
4893 			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4894 		}
4895 	}
4896 
4897 	mtx_unlock(&ctl_softc->ctl_lock);
4898 
4899 	return (0);
4900 }
4901 
4902 int
4903 ctl_start_lun(struct ctl_be_lun *be_lun)
4904 {
4905 	struct ctl_softc *ctl_softc;
4906 	struct ctl_lun *lun;
4907 
4908 	ctl_softc = control_softc;
4909 
4910 	lun = (struct ctl_lun *)be_lun->ctl_lun;
4911 
4912 	mtx_lock(&lun->lun_lock);
4913 	lun->flags &= ~CTL_LUN_STOPPED;
4914 	mtx_unlock(&lun->lun_lock);
4915 
4916 	return (0);
4917 }
4918 
4919 int
4920 ctl_stop_lun(struct ctl_be_lun *be_lun)
4921 {
4922 	struct ctl_softc *ctl_softc;
4923 	struct ctl_lun *lun;
4924 
4925 	ctl_softc = control_softc;
4926 
4927 	lun = (struct ctl_lun *)be_lun->ctl_lun;
4928 
4929 	mtx_lock(&lun->lun_lock);
4930 	lun->flags |= CTL_LUN_STOPPED;
4931 	mtx_unlock(&lun->lun_lock);
4932 
4933 	return (0);
4934 }
4935 
4936 int
4937 ctl_lun_offline(struct ctl_be_lun *be_lun)
4938 {
4939 	struct ctl_softc *ctl_softc;
4940 	struct ctl_lun *lun;
4941 
4942 	ctl_softc = control_softc;
4943 
4944 	lun = (struct ctl_lun *)be_lun->ctl_lun;
4945 
4946 	mtx_lock(&lun->lun_lock);
4947 	lun->flags |= CTL_LUN_OFFLINE;
4948 	mtx_unlock(&lun->lun_lock);
4949 
4950 	return (0);
4951 }
4952 
4953 int
4954 ctl_lun_online(struct ctl_be_lun *be_lun)
4955 {
4956 	struct ctl_softc *ctl_softc;
4957 	struct ctl_lun *lun;
4958 
4959 	ctl_softc = control_softc;
4960 
4961 	lun = (struct ctl_lun *)be_lun->ctl_lun;
4962 
4963 	mtx_lock(&lun->lun_lock);
4964 	lun->flags &= ~CTL_LUN_OFFLINE;
4965 	mtx_unlock(&lun->lun_lock);
4966 
4967 	return (0);
4968 }
4969 
4970 int
4971 ctl_invalidate_lun(struct ctl_be_lun *be_lun)
4972 {
4973 	struct ctl_softc *ctl_softc;
4974 	struct ctl_lun *lun;
4975 
4976 	ctl_softc = control_softc;
4977 
4978 	lun = (struct ctl_lun *)be_lun->ctl_lun;
4979 
4980 	mtx_lock(&lun->lun_lock);
4981 
4982 	/*
4983 	 * The LUN needs to be disabled before it can be marked invalid.
4984 	 */
4985 	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4986 		mtx_unlock(&lun->lun_lock);
4987 		return (-1);
4988 	}
4989 	/*
4990 	 * Mark the LUN invalid.
4991 	 */
4992 	lun->flags |= CTL_LUN_INVALID;
4993 
4994 	/*
4995 	 * If there is nothing in the OOA queue, go ahead and free the LUN.
4996 	 * If we have something in the OOA queue, we'll free it when the
4997 	 * last I/O completes.
4998 	 */
4999 	if (TAILQ_EMPTY(&lun->ooa_queue)) {
5000 		mtx_unlock(&lun->lun_lock);
5001 		mtx_lock(&ctl_softc->ctl_lock);
5002 		ctl_free_lun(lun);
5003 		mtx_unlock(&ctl_softc->ctl_lock);
5004 	} else
5005 		mtx_unlock(&lun->lun_lock);
5006 
5007 	return (0);
5008 }
5009 
5010 int
5011 ctl_lun_inoperable(struct ctl_be_lun *be_lun)
5012 {
5013 	struct ctl_softc *ctl_softc;
5014 	struct ctl_lun *lun;
5015 
5016 	ctl_softc = control_softc;
5017 	lun = (struct ctl_lun *)be_lun->ctl_lun;
5018 
5019 	mtx_lock(&lun->lun_lock);
5020 	lun->flags |= CTL_LUN_INOPERABLE;
5021 	mtx_unlock(&lun->lun_lock);
5022 
5023 	return (0);
5024 }
5025 
5026 int
5027 ctl_lun_operable(struct ctl_be_lun *be_lun)
5028 {
5029 	struct ctl_softc *ctl_softc;
5030 	struct ctl_lun *lun;
5031 
5032 	ctl_softc = control_softc;
5033 	lun = (struct ctl_lun *)be_lun->ctl_lun;
5034 
5035 	mtx_lock(&lun->lun_lock);
5036 	lun->flags &= ~CTL_LUN_INOPERABLE;
5037 	mtx_unlock(&lun->lun_lock);
5038 
5039 	return (0);
5040 }
5041 
5042 int
5043 ctl_lun_power_lock(struct ctl_be_lun *be_lun, struct ctl_nexus *nexus,
5044 		   int lock)
5045 {
5046 	struct ctl_softc *softc;
5047 	struct ctl_lun *lun;
5048 	struct copan_aps_subpage *current_sp;
5049 	struct ctl_page_index *page_index;
5050 	int i;
5051 
5052 	softc = control_softc;
5053 
5054 	mtx_lock(&softc->ctl_lock);
5055 
5056 	lun = (struct ctl_lun *)be_lun->ctl_lun;
5057 	mtx_lock(&lun->lun_lock);
5058 
5059 	page_index = NULL;
5060 	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
5061 		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
5062 		     APS_PAGE_CODE)
5063 			continue;
5064 
5065 		if (lun->mode_pages.index[i].subpage != APS_SUBPAGE_CODE)
5066 			continue;
5067 		page_index = &lun->mode_pages.index[i];
5068 	}
5069 
5070 	if (page_index == NULL) {
5071 		mtx_unlock(&lun->lun_lock);
5072 		mtx_unlock(&softc->ctl_lock);
5073 		printf("%s: APS subpage not found for lun %ju!\n", __func__,
5074 		       (uintmax_t)lun->lun);
5075 		return (1);
5076 	}
5077 #if 0
5078 	if ((softc->aps_locked_lun != 0)
5079 	 && (softc->aps_locked_lun != lun->lun)) {
5080 		printf("%s: attempt to lock LUN %llu when %llu is already "
5081 		       "locked\n");
5082 		mtx_unlock(&lun->lun_lock);
5083 		mtx_unlock(&softc->ctl_lock);
5084 		return (1);
5085 	}
5086 #endif
5087 
5088 	current_sp = (struct copan_aps_subpage *)(page_index->page_data +
5089 		(page_index->page_len * CTL_PAGE_CURRENT));
5090 
5091 	if (lock != 0) {
5092 		current_sp->lock_active = APS_LOCK_ACTIVE;
5093 		softc->aps_locked_lun = lun->lun;
5094 	} else {
5095 		current_sp->lock_active = 0;
5096 		softc->aps_locked_lun = 0;
5097 	}
5098 
5099 
5100 	/*
5101 	 * If we're in HA mode, try to send the lock message to the other
5102 	 * side.
5103 	 */
5104 	if (ctl_is_single == 0) {
5105 		int isc_retval;
5106 		union ctl_ha_msg lock_msg;
5107 
5108 		lock_msg.hdr.nexus = *nexus;
5109 		lock_msg.hdr.msg_type = CTL_MSG_APS_LOCK;
5110 		if (lock != 0)
5111 			lock_msg.aps.lock_flag = 1;
5112 		else
5113 			lock_msg.aps.lock_flag = 0;
5114 		isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &lock_msg,
5115 					 sizeof(lock_msg), 0);
5116 		if (isc_retval > CTL_HA_STATUS_SUCCESS) {
5117 			printf("%s: APS (lock=%d) error returned from "
5118 			       "ctl_ha_msg_send: %d\n", __func__, lock, isc_retval);
5119 			mtx_unlock(&lun->lun_lock);
5120 			mtx_unlock(&softc->ctl_lock);
5121 			return (1);
5122 		}
5123 	}
5124 
5125 	mtx_unlock(&lun->lun_lock);
5126 	mtx_unlock(&softc->ctl_lock);
5127 
5128 	return (0);
5129 }
5130 
5131 void
5132 ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
5133 {
5134 	struct ctl_lun *lun;
5135 	struct ctl_softc *softc;
5136 	int i;
5137 
5138 	softc = control_softc;
5139 
5140 	lun = (struct ctl_lun *)be_lun->ctl_lun;
5141 
5142 	mtx_lock(&lun->lun_lock);
5143 
5144 	for (i = 0; i < CTL_MAX_INITIATORS; i++)
5145 		lun->pending_ua[i] |= CTL_UA_CAPACITY_CHANGED;
5146 
5147 	mtx_unlock(&lun->lun_lock);
5148 }
5149 
5150 /*
5151  * Backend "memory move is complete" callback for requests that never
5152  * make it down to say RAIDCore's configuration code.
5153  */
5154 int
5155 ctl_config_move_done(union ctl_io *io)
5156 {
5157 	int retval;
5158 
5159 	retval = CTL_RETVAL_COMPLETE;
5160 
5161 
5162 	CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
5163 	/*
5164 	 * XXX KDM this shouldn't happen, but what if it does?
5165 	 */
5166 	if (io->io_hdr.io_type != CTL_IO_SCSI)
5167 		panic("I/O type isn't CTL_IO_SCSI!");
5168 
5169 	if ((io->io_hdr.port_status == 0)
5170 	 && ((io->io_hdr.flags & CTL_FLAG_ABORT) == 0)
5171 	 && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE))
5172 		io->io_hdr.status = CTL_SUCCESS;
5173 	else if ((io->io_hdr.port_status != 0)
5174 	      && ((io->io_hdr.flags & CTL_FLAG_ABORT) == 0)
5175 	      && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE)){
5176 		/*
5177 		 * For hardware error sense keys, the sense key
5178 		 * specific value is defined to be a retry count,
5179 		 * but we use it to pass back an internal FETD
5180 		 * error code.  XXX KDM  Hopefully the FETD is only
5181 		 * using 16 bits for an error code, since that's
5182 		 * all the space we have in the sks field.
5183 		 */
5184 		ctl_set_internal_failure(&io->scsiio,
5185 					 /*sks_valid*/ 1,
5186 					 /*retry_count*/
5187 					 io->io_hdr.port_status);
5188 		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5189 			free(io->scsiio.kern_data_ptr, M_CTL);
5190 		ctl_done(io);
5191 		goto bailout;
5192 	}
5193 
5194 	if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
5195 	 || ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)
5196 	 || ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
5197 		/*
5198 		 * XXX KDM just assuming a single pointer here, and not a
5199 		 * S/G list.  If we start using S/G lists for config data,
5200 		 * we'll need to know how to clean them up here as well.
5201 		 */
5202 		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5203 			free(io->scsiio.kern_data_ptr, M_CTL);
5204 		/* Hopefully the user has already set the status... */
5205 		ctl_done(io);
5206 	} else {
5207 		/*
5208 		 * XXX KDM now we need to continue data movement.  Some
5209 		 * options:
5210 		 * - call ctl_scsiio() again?  We don't do this for data
5211 		 *   writes, because for those at least we know ahead of
5212 		 *   time where the write will go and how long it is.  For
5213 		 *   config writes, though, that information is largely
5214 		 *   contained within the write itself, thus we need to
5215 		 *   parse out the data again.
5216 		 *
5217 		 * - Call some other function once the data is in?
5218 		 */
5219 
5220 		/*
5221 		 * XXX KDM call ctl_scsiio() again for now, and check flag
5222 		 * bits to see whether we're allocated or not.
5223 		 */
5224 		retval = ctl_scsiio(&io->scsiio);
5225 	}
5226 bailout:
5227 	return (retval);
5228 }
5229 
5230 /*
5231  * This gets called by a backend driver when it is done with a
5232  * data_submit method.
5233  */
5234 void
5235 ctl_data_submit_done(union ctl_io *io)
5236 {
5237 	/*
5238 	 * If the IO_CONT flag is set, we need to call the supplied
5239 	 * function to continue processing the I/O, instead of completing
5240 	 * the I/O just yet.
5241 	 *
5242 	 * If there is an error, though, we don't want to keep processing.
5243 	 * Instead, just send status back to the initiator.
5244 	 */
5245 	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5246 	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5247 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5248 	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5249 		io->scsiio.io_cont(io);
5250 		return;
5251 	}
5252 	ctl_done(io);
5253 }
5254 
5255 /*
5256  * This gets called by a backend driver when it is done with a
5257  * configuration write.
5258  */
5259 void
5260 ctl_config_write_done(union ctl_io *io)
5261 {
5262 	/*
5263 	 * If the IO_CONT flag is set, we need to call the supplied
5264 	 * function to continue processing the I/O, instead of completing
5265 	 * the I/O just yet.
5266 	 *
5267 	 * If there is an error, though, we don't want to keep processing.
5268 	 * Instead, just send status back to the initiator.
5269 	 */
5270 	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT)
5271 	 && (((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE)
5272 	  || ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS))) {
5273 		io->scsiio.io_cont(io);
5274 		return;
5275 	}
5276 	/*
5277 	 * Since a configuration write can be done for commands that actually
5278 	 * have data allocated, like write buffer, and commands that have
5279 	 * no data, like start/stop unit, we need to check here.
5280 	 */
5281 	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT)
5282 		free(io->scsiio.kern_data_ptr, M_CTL);
5283 	ctl_done(io);
5284 }
5285 
5286 /*
5287  * SCSI release command.
5288  */
5289 int
5290 ctl_scsi_release(struct ctl_scsiio *ctsio)
5291 {
5292 	int length, longid, thirdparty_id, resv_id;
5293 	struct ctl_softc *ctl_softc;
5294 	struct ctl_lun *lun;
5295 
5296 	length = 0;
5297 	resv_id = 0;
5298 
5299 	CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5300 
5301 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5302 	ctl_softc = control_softc;
5303 
5304 	switch (ctsio->cdb[0]) {
5305 	case RELEASE_10: {
5306 		struct scsi_release_10 *cdb;
5307 
5308 		cdb = (struct scsi_release_10 *)ctsio->cdb;
5309 
5310 		if (cdb->byte2 & SR10_LONGID)
5311 			longid = 1;
5312 		else
5313 			thirdparty_id = cdb->thirdparty_id;
5314 
5315 		resv_id = cdb->resv_id;
5316 		length = scsi_2btoul(cdb->length);
5317 		break;
5318 	}
5319 	}
5320 
5321 
5322 	/*
5323 	 * XXX KDM right now, we only support LUN reservation.  We don't
5324 	 * support 3rd party reservations, or extent reservations, which
5325 	 * might actually need the parameter list.  If we've gotten this
5326 	 * far, we've got a LUN reservation.  Anything else got kicked out
5327 	 * above.  So, according to SPC, ignore the length.
5328 	 */
5329 	length = 0;
5330 
5331 	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5332 	 && (length > 0)) {
5333 		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5334 		ctsio->kern_data_len = length;
5335 		ctsio->kern_total_len = length;
5336 		ctsio->kern_data_resid = 0;
5337 		ctsio->kern_rel_offset = 0;
5338 		ctsio->kern_sg_entries = 0;
5339 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5340 		ctsio->be_move_done = ctl_config_move_done;
5341 		ctl_datamove((union ctl_io *)ctsio);
5342 
5343 		return (CTL_RETVAL_COMPLETE);
5344 	}
5345 
5346 	if (length > 0)
5347 		thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5348 
5349 	mtx_lock(&lun->lun_lock);
5350 
5351 	/*
5352 	 * According to SPC, it is not an error for an intiator to attempt
5353 	 * to release a reservation on a LUN that isn't reserved, or that
5354 	 * is reserved by another initiator.  The reservation can only be
5355 	 * released, though, by the initiator who made it or by one of
5356 	 * several reset type events.
5357 	 */
5358 	if (lun->flags & CTL_LUN_RESERVED) {
5359 		if ((ctsio->io_hdr.nexus.initid.id == lun->rsv_nexus.initid.id)
5360 		 && (ctsio->io_hdr.nexus.targ_port == lun->rsv_nexus.targ_port)
5361 		 && (ctsio->io_hdr.nexus.targ_target.id ==
5362 		     lun->rsv_nexus.targ_target.id)) {
5363 			lun->flags &= ~CTL_LUN_RESERVED;
5364 		}
5365 	}
5366 
5367 	mtx_unlock(&lun->lun_lock);
5368 
5369 	ctsio->scsi_status = SCSI_STATUS_OK;
5370 	ctsio->io_hdr.status = CTL_SUCCESS;
5371 
5372 	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5373 		free(ctsio->kern_data_ptr, M_CTL);
5374 		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5375 	}
5376 
5377 	ctl_done((union ctl_io *)ctsio);
5378 	return (CTL_RETVAL_COMPLETE);
5379 }
5380 
5381 int
5382 ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5383 {
5384 	int extent, thirdparty, longid;
5385 	int resv_id, length;
5386 	uint64_t thirdparty_id;
5387 	struct ctl_softc *ctl_softc;
5388 	struct ctl_lun *lun;
5389 
5390 	extent = 0;
5391 	thirdparty = 0;
5392 	longid = 0;
5393 	resv_id = 0;
5394 	length = 0;
5395 	thirdparty_id = 0;
5396 
5397 	CTL_DEBUG_PRINT(("ctl_reserve\n"));
5398 
5399 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5400 	ctl_softc = control_softc;
5401 
5402 	switch (ctsio->cdb[0]) {
5403 	case RESERVE_10: {
5404 		struct scsi_reserve_10 *cdb;
5405 
5406 		cdb = (struct scsi_reserve_10 *)ctsio->cdb;
5407 
5408 		if (cdb->byte2 & SR10_LONGID)
5409 			longid = 1;
5410 		else
5411 			thirdparty_id = cdb->thirdparty_id;
5412 
5413 		resv_id = cdb->resv_id;
5414 		length = scsi_2btoul(cdb->length);
5415 		break;
5416 	}
5417 	}
5418 
5419 	/*
5420 	 * XXX KDM right now, we only support LUN reservation.  We don't
5421 	 * support 3rd party reservations, or extent reservations, which
5422 	 * might actually need the parameter list.  If we've gotten this
5423 	 * far, we've got a LUN reservation.  Anything else got kicked out
5424 	 * above.  So, according to SPC, ignore the length.
5425 	 */
5426 	length = 0;
5427 
5428 	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5429 	 && (length > 0)) {
5430 		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5431 		ctsio->kern_data_len = length;
5432 		ctsio->kern_total_len = length;
5433 		ctsio->kern_data_resid = 0;
5434 		ctsio->kern_rel_offset = 0;
5435 		ctsio->kern_sg_entries = 0;
5436 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5437 		ctsio->be_move_done = ctl_config_move_done;
5438 		ctl_datamove((union ctl_io *)ctsio);
5439 
5440 		return (CTL_RETVAL_COMPLETE);
5441 	}
5442 
5443 	if (length > 0)
5444 		thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5445 
5446 	mtx_lock(&lun->lun_lock);
5447 	if (lun->flags & CTL_LUN_RESERVED) {
5448 		if ((ctsio->io_hdr.nexus.initid.id != lun->rsv_nexus.initid.id)
5449 		 || (ctsio->io_hdr.nexus.targ_port != lun->rsv_nexus.targ_port)
5450 		 || (ctsio->io_hdr.nexus.targ_target.id !=
5451 		     lun->rsv_nexus.targ_target.id)) {
5452 			ctsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
5453 			ctsio->io_hdr.status = CTL_SCSI_ERROR;
5454 			goto bailout;
5455 		}
5456 	}
5457 
5458 	lun->flags |= CTL_LUN_RESERVED;
5459 	lun->rsv_nexus = ctsio->io_hdr.nexus;
5460 
5461 	ctsio->scsi_status = SCSI_STATUS_OK;
5462 	ctsio->io_hdr.status = CTL_SUCCESS;
5463 
5464 bailout:
5465 	mtx_unlock(&lun->lun_lock);
5466 
5467 	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5468 		free(ctsio->kern_data_ptr, M_CTL);
5469 		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5470 	}
5471 
5472 	ctl_done((union ctl_io *)ctsio);
5473 	return (CTL_RETVAL_COMPLETE);
5474 }
5475 
5476 int
5477 ctl_start_stop(struct ctl_scsiio *ctsio)
5478 {
5479 	struct scsi_start_stop_unit *cdb;
5480 	struct ctl_lun *lun;
5481 	struct ctl_softc *ctl_softc;
5482 	int retval;
5483 
5484 	CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5485 
5486 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5487 	ctl_softc = control_softc;
5488 	retval = 0;
5489 
5490 	cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5491 
5492 	/*
5493 	 * XXX KDM
5494 	 * We don't support the immediate bit on a stop unit.  In order to
5495 	 * do that, we would need to code up a way to know that a stop is
5496 	 * pending, and hold off any new commands until it completes, one
5497 	 * way or another.  Then we could accept or reject those commands
5498 	 * depending on its status.  We would almost need to do the reverse
5499 	 * of what we do below for an immediate start -- return the copy of
5500 	 * the ctl_io to the FETD with status to send to the host (and to
5501 	 * free the copy!) and then free the original I/O once the stop
5502 	 * actually completes.  That way, the OOA queue mechanism can work
5503 	 * to block commands that shouldn't proceed.  Another alternative
5504 	 * would be to put the copy in the queue in place of the original,
5505 	 * and return the original back to the caller.  That could be
5506 	 * slightly safer..
5507 	 */
5508 	if ((cdb->byte2 & SSS_IMMED)
5509 	 && ((cdb->how & SSS_START) == 0)) {
5510 		ctl_set_invalid_field(ctsio,
5511 				      /*sks_valid*/ 1,
5512 				      /*command*/ 1,
5513 				      /*field*/ 1,
5514 				      /*bit_valid*/ 1,
5515 				      /*bit*/ 0);
5516 		ctl_done((union ctl_io *)ctsio);
5517 		return (CTL_RETVAL_COMPLETE);
5518 	}
5519 
5520 	if ((lun->flags & CTL_LUN_PR_RESERVED)
5521 	 && ((cdb->how & SSS_START)==0)) {
5522 		uint32_t residx;
5523 
5524 		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5525 		if (!lun->per_res[residx].registered
5526 		 || (lun->pr_res_idx!=residx && lun->res_type < 4)) {
5527 
5528 			ctl_set_reservation_conflict(ctsio);
5529 			ctl_done((union ctl_io *)ctsio);
5530 			return (CTL_RETVAL_COMPLETE);
5531 		}
5532 	}
5533 
5534 	/*
5535 	 * If there is no backend on this device, we can't start or stop
5536 	 * it.  In theory we shouldn't get any start/stop commands in the
5537 	 * first place at this level if the LUN doesn't have a backend.
5538 	 * That should get stopped by the command decode code.
5539 	 */
5540 	if (lun->backend == NULL) {
5541 		ctl_set_invalid_opcode(ctsio);
5542 		ctl_done((union ctl_io *)ctsio);
5543 		return (CTL_RETVAL_COMPLETE);
5544 	}
5545 
5546 	/*
5547 	 * XXX KDM Copan-specific offline behavior.
5548 	 * Figure out a reasonable way to port this?
5549 	 */
5550 #ifdef NEEDTOPORT
5551 	mtx_lock(&lun->lun_lock);
5552 
5553 	if (((cdb->byte2 & SSS_ONOFFLINE) == 0)
5554 	 && (lun->flags & CTL_LUN_OFFLINE)) {
5555 		/*
5556 		 * If the LUN is offline, and the on/offline bit isn't set,
5557 		 * reject the start or stop.  Otherwise, let it through.
5558 		 */
5559 		mtx_unlock(&lun->lun_lock);
5560 		ctl_set_lun_not_ready(ctsio);
5561 		ctl_done((union ctl_io *)ctsio);
5562 	} else {
5563 		mtx_unlock(&lun->lun_lock);
5564 #endif /* NEEDTOPORT */
5565 		/*
5566 		 * This could be a start or a stop when we're online,
5567 		 * or a stop/offline or start/online.  A start or stop when
5568 		 * we're offline is covered in the case above.
5569 		 */
5570 		/*
5571 		 * In the non-immediate case, we send the request to
5572 		 * the backend and return status to the user when
5573 		 * it is done.
5574 		 *
5575 		 * In the immediate case, we allocate a new ctl_io
5576 		 * to hold a copy of the request, and send that to
5577 		 * the backend.  We then set good status on the
5578 		 * user's request and return it immediately.
5579 		 */
5580 		if (cdb->byte2 & SSS_IMMED) {
5581 			union ctl_io *new_io;
5582 
5583 			new_io = ctl_alloc_io(ctsio->io_hdr.pool);
5584 			if (new_io == NULL) {
5585 				ctl_set_busy(ctsio);
5586 				ctl_done((union ctl_io *)ctsio);
5587 			} else {
5588 				ctl_copy_io((union ctl_io *)ctsio,
5589 					    new_io);
5590 				retval = lun->backend->config_write(new_io);
5591 				ctl_set_success(ctsio);
5592 				ctl_done((union ctl_io *)ctsio);
5593 			}
5594 		} else {
5595 			retval = lun->backend->config_write(
5596 				(union ctl_io *)ctsio);
5597 		}
5598 #ifdef NEEDTOPORT
5599 	}
5600 #endif
5601 	return (retval);
5602 }
5603 
5604 /*
5605  * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5606  * we don't really do anything with the LBA and length fields if the user
5607  * passes them in.  Instead we'll just flush out the cache for the entire
5608  * LUN.
5609  */
5610 int
5611 ctl_sync_cache(struct ctl_scsiio *ctsio)
5612 {
5613 	struct ctl_lun *lun;
5614 	struct ctl_softc *ctl_softc;
5615 	uint64_t starting_lba;
5616 	uint32_t block_count;
5617 	int retval;
5618 
5619 	CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5620 
5621 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5622 	ctl_softc = control_softc;
5623 	retval = 0;
5624 
5625 	switch (ctsio->cdb[0]) {
5626 	case SYNCHRONIZE_CACHE: {
5627 		struct scsi_sync_cache *cdb;
5628 		cdb = (struct scsi_sync_cache *)ctsio->cdb;
5629 
5630 		starting_lba = scsi_4btoul(cdb->begin_lba);
5631 		block_count = scsi_2btoul(cdb->lb_count);
5632 		break;
5633 	}
5634 	case SYNCHRONIZE_CACHE_16: {
5635 		struct scsi_sync_cache_16 *cdb;
5636 		cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5637 
5638 		starting_lba = scsi_8btou64(cdb->begin_lba);
5639 		block_count = scsi_4btoul(cdb->lb_count);
5640 		break;
5641 	}
5642 	default:
5643 		ctl_set_invalid_opcode(ctsio);
5644 		ctl_done((union ctl_io *)ctsio);
5645 		goto bailout;
5646 		break; /* NOTREACHED */
5647 	}
5648 
5649 	/*
5650 	 * We check the LBA and length, but don't do anything with them.
5651 	 * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5652 	 * get flushed.  This check will just help satisfy anyone who wants
5653 	 * to see an error for an out of range LBA.
5654 	 */
5655 	if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5656 		ctl_set_lba_out_of_range(ctsio);
5657 		ctl_done((union ctl_io *)ctsio);
5658 		goto bailout;
5659 	}
5660 
5661 	/*
5662 	 * If this LUN has no backend, we can't flush the cache anyway.
5663 	 */
5664 	if (lun->backend == NULL) {
5665 		ctl_set_invalid_opcode(ctsio);
5666 		ctl_done((union ctl_io *)ctsio);
5667 		goto bailout;
5668 	}
5669 
5670 	/*
5671 	 * Check to see whether we're configured to send the SYNCHRONIZE
5672 	 * CACHE command directly to the back end.
5673 	 */
5674 	mtx_lock(&lun->lun_lock);
5675 	if ((ctl_softc->flags & CTL_FLAG_REAL_SYNC)
5676 	 && (++(lun->sync_count) >= lun->sync_interval)) {
5677 		lun->sync_count = 0;
5678 		mtx_unlock(&lun->lun_lock);
5679 		retval = lun->backend->config_write((union ctl_io *)ctsio);
5680 	} else {
5681 		mtx_unlock(&lun->lun_lock);
5682 		ctl_set_success(ctsio);
5683 		ctl_done((union ctl_io *)ctsio);
5684 	}
5685 
5686 bailout:
5687 
5688 	return (retval);
5689 }
5690 
5691 int
5692 ctl_format(struct ctl_scsiio *ctsio)
5693 {
5694 	struct scsi_format *cdb;
5695 	struct ctl_lun *lun;
5696 	struct ctl_softc *ctl_softc;
5697 	int length, defect_list_len;
5698 
5699 	CTL_DEBUG_PRINT(("ctl_format\n"));
5700 
5701 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5702 	ctl_softc = control_softc;
5703 
5704 	cdb = (struct scsi_format *)ctsio->cdb;
5705 
5706 	length = 0;
5707 	if (cdb->byte2 & SF_FMTDATA) {
5708 		if (cdb->byte2 & SF_LONGLIST)
5709 			length = sizeof(struct scsi_format_header_long);
5710 		else
5711 			length = sizeof(struct scsi_format_header_short);
5712 	}
5713 
5714 	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5715 	 && (length > 0)) {
5716 		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5717 		ctsio->kern_data_len = length;
5718 		ctsio->kern_total_len = length;
5719 		ctsio->kern_data_resid = 0;
5720 		ctsio->kern_rel_offset = 0;
5721 		ctsio->kern_sg_entries = 0;
5722 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5723 		ctsio->be_move_done = ctl_config_move_done;
5724 		ctl_datamove((union ctl_io *)ctsio);
5725 
5726 		return (CTL_RETVAL_COMPLETE);
5727 	}
5728 
5729 	defect_list_len = 0;
5730 
5731 	if (cdb->byte2 & SF_FMTDATA) {
5732 		if (cdb->byte2 & SF_LONGLIST) {
5733 			struct scsi_format_header_long *header;
5734 
5735 			header = (struct scsi_format_header_long *)
5736 				ctsio->kern_data_ptr;
5737 
5738 			defect_list_len = scsi_4btoul(header->defect_list_len);
5739 			if (defect_list_len != 0) {
5740 				ctl_set_invalid_field(ctsio,
5741 						      /*sks_valid*/ 1,
5742 						      /*command*/ 0,
5743 						      /*field*/ 2,
5744 						      /*bit_valid*/ 0,
5745 						      /*bit*/ 0);
5746 				goto bailout;
5747 			}
5748 		} else {
5749 			struct scsi_format_header_short *header;
5750 
5751 			header = (struct scsi_format_header_short *)
5752 				ctsio->kern_data_ptr;
5753 
5754 			defect_list_len = scsi_2btoul(header->defect_list_len);
5755 			if (defect_list_len != 0) {
5756 				ctl_set_invalid_field(ctsio,
5757 						      /*sks_valid*/ 1,
5758 						      /*command*/ 0,
5759 						      /*field*/ 2,
5760 						      /*bit_valid*/ 0,
5761 						      /*bit*/ 0);
5762 				goto bailout;
5763 			}
5764 		}
5765 	}
5766 
5767 	/*
5768 	 * The format command will clear out the "Medium format corrupted"
5769 	 * status if set by the configuration code.  That status is really
5770 	 * just a way to notify the host that we have lost the media, and
5771 	 * get them to issue a command that will basically make them think
5772 	 * they're blowing away the media.
5773 	 */
5774 	mtx_lock(&lun->lun_lock);
5775 	lun->flags &= ~CTL_LUN_INOPERABLE;
5776 	mtx_unlock(&lun->lun_lock);
5777 
5778 	ctsio->scsi_status = SCSI_STATUS_OK;
5779 	ctsio->io_hdr.status = CTL_SUCCESS;
5780 bailout:
5781 
5782 	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5783 		free(ctsio->kern_data_ptr, M_CTL);
5784 		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5785 	}
5786 
5787 	ctl_done((union ctl_io *)ctsio);
5788 	return (CTL_RETVAL_COMPLETE);
5789 }
5790 
5791 int
5792 ctl_read_buffer(struct ctl_scsiio *ctsio)
5793 {
5794 	struct scsi_read_buffer *cdb;
5795 	struct ctl_lun *lun;
5796 	int buffer_offset, len;
5797 	static uint8_t descr[4];
5798 	static uint8_t echo_descr[4] = { 0 };
5799 
5800 	CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5801 
5802 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5803 	cdb = (struct scsi_read_buffer *)ctsio->cdb;
5804 
5805 	if (lun->flags & CTL_LUN_PR_RESERVED) {
5806 		uint32_t residx;
5807 
5808 		/*
5809 		 * XXX KDM need a lock here.
5810 		 */
5811 		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5812 		if ((lun->res_type == SPR_TYPE_EX_AC
5813 		  && residx != lun->pr_res_idx)
5814 		 || ((lun->res_type == SPR_TYPE_EX_AC_RO
5815 		   || lun->res_type == SPR_TYPE_EX_AC_AR)
5816 		  && !lun->per_res[residx].registered)) {
5817 			ctl_set_reservation_conflict(ctsio);
5818 			ctl_done((union ctl_io *)ctsio);
5819 			return (CTL_RETVAL_COMPLETE);
5820 	        }
5821 	}
5822 
5823 	if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA &&
5824 	    (cdb->byte2 & RWB_MODE) != RWB_MODE_ECHO_DESCR &&
5825 	    (cdb->byte2 & RWB_MODE) != RWB_MODE_DESCR) {
5826 		ctl_set_invalid_field(ctsio,
5827 				      /*sks_valid*/ 1,
5828 				      /*command*/ 1,
5829 				      /*field*/ 1,
5830 				      /*bit_valid*/ 1,
5831 				      /*bit*/ 4);
5832 		ctl_done((union ctl_io *)ctsio);
5833 		return (CTL_RETVAL_COMPLETE);
5834 	}
5835 
5836 	len = scsi_3btoul(cdb->length);
5837 	buffer_offset = scsi_3btoul(cdb->offset);
5838 
5839 	if (buffer_offset + len > sizeof(lun->write_buffer)) {
5840 		ctl_set_invalid_field(ctsio,
5841 				      /*sks_valid*/ 1,
5842 				      /*command*/ 1,
5843 				      /*field*/ 6,
5844 				      /*bit_valid*/ 0,
5845 				      /*bit*/ 0);
5846 		ctl_done((union ctl_io *)ctsio);
5847 		return (CTL_RETVAL_COMPLETE);
5848 	}
5849 
5850 	if ((cdb->byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5851 		descr[0] = 0;
5852 		scsi_ulto3b(sizeof(lun->write_buffer), &descr[1]);
5853 		ctsio->kern_data_ptr = descr;
5854 		len = min(len, sizeof(descr));
5855 	} else if ((cdb->byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5856 		ctsio->kern_data_ptr = echo_descr;
5857 		len = min(len, sizeof(echo_descr));
5858 	} else
5859 		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5860 	ctsio->kern_data_len = len;
5861 	ctsio->kern_total_len = len;
5862 	ctsio->kern_data_resid = 0;
5863 	ctsio->kern_rel_offset = 0;
5864 	ctsio->kern_sg_entries = 0;
5865 	ctsio->be_move_done = ctl_config_move_done;
5866 	ctl_datamove((union ctl_io *)ctsio);
5867 
5868 	return (CTL_RETVAL_COMPLETE);
5869 }
5870 
5871 int
5872 ctl_write_buffer(struct ctl_scsiio *ctsio)
5873 {
5874 	struct scsi_write_buffer *cdb;
5875 	struct ctl_lun *lun;
5876 	int buffer_offset, len;
5877 
5878 	CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5879 
5880 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5881 	cdb = (struct scsi_write_buffer *)ctsio->cdb;
5882 
5883 	if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA) {
5884 		ctl_set_invalid_field(ctsio,
5885 				      /*sks_valid*/ 1,
5886 				      /*command*/ 1,
5887 				      /*field*/ 1,
5888 				      /*bit_valid*/ 1,
5889 				      /*bit*/ 4);
5890 		ctl_done((union ctl_io *)ctsio);
5891 		return (CTL_RETVAL_COMPLETE);
5892 	}
5893 
5894 	len = scsi_3btoul(cdb->length);
5895 	buffer_offset = scsi_3btoul(cdb->offset);
5896 
5897 	if (buffer_offset + len > sizeof(lun->write_buffer)) {
5898 		ctl_set_invalid_field(ctsio,
5899 				      /*sks_valid*/ 1,
5900 				      /*command*/ 1,
5901 				      /*field*/ 6,
5902 				      /*bit_valid*/ 0,
5903 				      /*bit*/ 0);
5904 		ctl_done((union ctl_io *)ctsio);
5905 		return (CTL_RETVAL_COMPLETE);
5906 	}
5907 
5908 	/*
5909 	 * If we've got a kernel request that hasn't been malloced yet,
5910 	 * malloc it and tell the caller the data buffer is here.
5911 	 */
5912 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5913 		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5914 		ctsio->kern_data_len = len;
5915 		ctsio->kern_total_len = len;
5916 		ctsio->kern_data_resid = 0;
5917 		ctsio->kern_rel_offset = 0;
5918 		ctsio->kern_sg_entries = 0;
5919 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5920 		ctsio->be_move_done = ctl_config_move_done;
5921 		ctl_datamove((union ctl_io *)ctsio);
5922 
5923 		return (CTL_RETVAL_COMPLETE);
5924 	}
5925 
5926 	ctl_done((union ctl_io *)ctsio);
5927 
5928 	return (CTL_RETVAL_COMPLETE);
5929 }
5930 
5931 int
5932 ctl_write_same(struct ctl_scsiio *ctsio)
5933 {
5934 	struct ctl_lun *lun;
5935 	struct ctl_lba_len_flags *lbalen;
5936 	uint64_t lba;
5937 	uint32_t num_blocks;
5938 	int len, retval;
5939 	uint8_t byte2;
5940 
5941 	retval = CTL_RETVAL_COMPLETE;
5942 
5943 	CTL_DEBUG_PRINT(("ctl_write_same\n"));
5944 
5945 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5946 
5947 	switch (ctsio->cdb[0]) {
5948 	case WRITE_SAME_10: {
5949 		struct scsi_write_same_10 *cdb;
5950 
5951 		cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5952 
5953 		lba = scsi_4btoul(cdb->addr);
5954 		num_blocks = scsi_2btoul(cdb->length);
5955 		byte2 = cdb->byte2;
5956 		break;
5957 	}
5958 	case WRITE_SAME_16: {
5959 		struct scsi_write_same_16 *cdb;
5960 
5961 		cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5962 
5963 		lba = scsi_8btou64(cdb->addr);
5964 		num_blocks = scsi_4btoul(cdb->length);
5965 		byte2 = cdb->byte2;
5966 		break;
5967 	}
5968 	default:
5969 		/*
5970 		 * We got a command we don't support.  This shouldn't
5971 		 * happen, commands should be filtered out above us.
5972 		 */
5973 		ctl_set_invalid_opcode(ctsio);
5974 		ctl_done((union ctl_io *)ctsio);
5975 
5976 		return (CTL_RETVAL_COMPLETE);
5977 		break; /* NOTREACHED */
5978 	}
5979 
5980 	/*
5981 	 * The first check is to make sure we're in bounds, the second
5982 	 * check is to catch wrap-around problems.  If the lba + num blocks
5983 	 * is less than the lba, then we've wrapped around and the block
5984 	 * range is invalid anyway.
5985 	 */
5986 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5987 	 || ((lba + num_blocks) < lba)) {
5988 		ctl_set_lba_out_of_range(ctsio);
5989 		ctl_done((union ctl_io *)ctsio);
5990 		return (CTL_RETVAL_COMPLETE);
5991 	}
5992 
5993 	/* Zero number of blocks means "to the last logical block" */
5994 	if (num_blocks == 0) {
5995 		if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5996 			ctl_set_invalid_field(ctsio,
5997 					      /*sks_valid*/ 0,
5998 					      /*command*/ 1,
5999 					      /*field*/ 0,
6000 					      /*bit_valid*/ 0,
6001 					      /*bit*/ 0);
6002 			ctl_done((union ctl_io *)ctsio);
6003 			return (CTL_RETVAL_COMPLETE);
6004 		}
6005 		num_blocks = (lun->be_lun->maxlba + 1) - lba;
6006 	}
6007 
6008 	len = lun->be_lun->blocksize;
6009 
6010 	/*
6011 	 * If we've got a kernel request that hasn't been malloced yet,
6012 	 * malloc it and tell the caller the data buffer is here.
6013 	 */
6014 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6015 		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
6016 		ctsio->kern_data_len = len;
6017 		ctsio->kern_total_len = len;
6018 		ctsio->kern_data_resid = 0;
6019 		ctsio->kern_rel_offset = 0;
6020 		ctsio->kern_sg_entries = 0;
6021 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6022 		ctsio->be_move_done = ctl_config_move_done;
6023 		ctl_datamove((union ctl_io *)ctsio);
6024 
6025 		return (CTL_RETVAL_COMPLETE);
6026 	}
6027 
6028 	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
6029 	lbalen->lba = lba;
6030 	lbalen->len = num_blocks;
6031 	lbalen->flags = byte2;
6032 	retval = lun->backend->config_write((union ctl_io *)ctsio);
6033 
6034 	return (retval);
6035 }
6036 
6037 int
6038 ctl_unmap(struct ctl_scsiio *ctsio)
6039 {
6040 	struct ctl_lun *lun;
6041 	struct scsi_unmap *cdb;
6042 	struct ctl_ptr_len_flags *ptrlen;
6043 	struct scsi_unmap_header *hdr;
6044 	struct scsi_unmap_desc *buf, *end;
6045 	uint64_t lba;
6046 	uint32_t num_blocks;
6047 	int len, retval;
6048 	uint8_t byte2;
6049 
6050 	retval = CTL_RETVAL_COMPLETE;
6051 
6052 	CTL_DEBUG_PRINT(("ctl_unmap\n"));
6053 
6054 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6055 	cdb = (struct scsi_unmap *)ctsio->cdb;
6056 
6057 	len = scsi_2btoul(cdb->length);
6058 	byte2 = cdb->byte2;
6059 
6060 	/*
6061 	 * If we've got a kernel request that hasn't been malloced yet,
6062 	 * malloc it and tell the caller the data buffer is here.
6063 	 */
6064 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6065 		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
6066 		ctsio->kern_data_len = len;
6067 		ctsio->kern_total_len = len;
6068 		ctsio->kern_data_resid = 0;
6069 		ctsio->kern_rel_offset = 0;
6070 		ctsio->kern_sg_entries = 0;
6071 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6072 		ctsio->be_move_done = ctl_config_move_done;
6073 		ctl_datamove((union ctl_io *)ctsio);
6074 
6075 		return (CTL_RETVAL_COMPLETE);
6076 	}
6077 
6078 	len = ctsio->kern_total_len - ctsio->kern_data_resid;
6079 	hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
6080 	if (len < sizeof (*hdr) ||
6081 	    len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
6082 	    len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
6083 	    scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
6084 		ctl_set_invalid_field(ctsio,
6085 				      /*sks_valid*/ 0,
6086 				      /*command*/ 0,
6087 				      /*field*/ 0,
6088 				      /*bit_valid*/ 0,
6089 				      /*bit*/ 0);
6090 		ctl_done((union ctl_io *)ctsio);
6091 		return (CTL_RETVAL_COMPLETE);
6092 	}
6093 	len = scsi_2btoul(hdr->desc_length);
6094 	buf = (struct scsi_unmap_desc *)(hdr + 1);
6095 	end = buf + len / sizeof(*buf);
6096 
6097 	ptrlen = (struct ctl_ptr_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
6098 	ptrlen->ptr = (void *)buf;
6099 	ptrlen->len = len;
6100 	ptrlen->flags = byte2;
6101 
6102 	for (; buf < end; buf++) {
6103 		lba = scsi_8btou64(buf->lba);
6104 		num_blocks = scsi_4btoul(buf->length);
6105 		if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
6106 		 || ((lba + num_blocks) < lba)) {
6107 			ctl_set_lba_out_of_range(ctsio);
6108 			ctl_done((union ctl_io *)ctsio);
6109 			return (CTL_RETVAL_COMPLETE);
6110 		}
6111 	}
6112 
6113 	retval = lun->backend->config_write((union ctl_io *)ctsio);
6114 
6115 	return (retval);
6116 }
6117 
6118 /*
6119  * Note that this function currently doesn't actually do anything inside
6120  * CTL to enforce things if the DQue bit is turned on.
6121  *
6122  * Also note that this function can't be used in the default case, because
6123  * the DQue bit isn't set in the changeable mask for the control mode page
6124  * anyway.  This is just here as an example for how to implement a page
6125  * handler, and a placeholder in case we want to allow the user to turn
6126  * tagged queueing on and off.
6127  *
6128  * The D_SENSE bit handling is functional, however, and will turn
6129  * descriptor sense on and off for a given LUN.
6130  */
6131 int
6132 ctl_control_page_handler(struct ctl_scsiio *ctsio,
6133 			 struct ctl_page_index *page_index, uint8_t *page_ptr)
6134 {
6135 	struct scsi_control_page *current_cp, *saved_cp, *user_cp;
6136 	struct ctl_lun *lun;
6137 	struct ctl_softc *softc;
6138 	int set_ua;
6139 	uint32_t initidx;
6140 
6141 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6142 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6143 	set_ua = 0;
6144 
6145 	user_cp = (struct scsi_control_page *)page_ptr;
6146 	current_cp = (struct scsi_control_page *)
6147 		(page_index->page_data + (page_index->page_len *
6148 		CTL_PAGE_CURRENT));
6149 	saved_cp = (struct scsi_control_page *)
6150 		(page_index->page_data + (page_index->page_len *
6151 		CTL_PAGE_SAVED));
6152 
6153 	softc = control_softc;
6154 
6155 	mtx_lock(&lun->lun_lock);
6156 	if (((current_cp->rlec & SCP_DSENSE) == 0)
6157 	 && ((user_cp->rlec & SCP_DSENSE) != 0)) {
6158 		/*
6159 		 * Descriptor sense is currently turned off and the user
6160 		 * wants to turn it on.
6161 		 */
6162 		current_cp->rlec |= SCP_DSENSE;
6163 		saved_cp->rlec |= SCP_DSENSE;
6164 		lun->flags |= CTL_LUN_SENSE_DESC;
6165 		set_ua = 1;
6166 	} else if (((current_cp->rlec & SCP_DSENSE) != 0)
6167 		&& ((user_cp->rlec & SCP_DSENSE) == 0)) {
6168 		/*
6169 		 * Descriptor sense is currently turned on, and the user
6170 		 * wants to turn it off.
6171 		 */
6172 		current_cp->rlec &= ~SCP_DSENSE;
6173 		saved_cp->rlec &= ~SCP_DSENSE;
6174 		lun->flags &= ~CTL_LUN_SENSE_DESC;
6175 		set_ua = 1;
6176 	}
6177 	if (current_cp->queue_flags & SCP_QUEUE_DQUE) {
6178 		if (user_cp->queue_flags & SCP_QUEUE_DQUE) {
6179 #ifdef NEEDTOPORT
6180 			csevent_log(CSC_CTL | CSC_SHELF_SW |
6181 				    CTL_UNTAG_TO_UNTAG,
6182 				    csevent_LogType_Trace,
6183 				    csevent_Severity_Information,
6184 				    csevent_AlertLevel_Green,
6185 				    csevent_FRU_Firmware,
6186 				    csevent_FRU_Unknown,
6187 				    "Received untagged to untagged transition");
6188 #endif /* NEEDTOPORT */
6189 		} else {
6190 #ifdef NEEDTOPORT
6191 			csevent_log(CSC_CTL | CSC_SHELF_SW |
6192 				    CTL_UNTAG_TO_TAG,
6193 				    csevent_LogType_ConfigChange,
6194 				    csevent_Severity_Information,
6195 				    csevent_AlertLevel_Green,
6196 				    csevent_FRU_Firmware,
6197 				    csevent_FRU_Unknown,
6198 				    "Received untagged to tagged "
6199 				    "queueing transition");
6200 #endif /* NEEDTOPORT */
6201 
6202 			current_cp->queue_flags &= ~SCP_QUEUE_DQUE;
6203 			saved_cp->queue_flags &= ~SCP_QUEUE_DQUE;
6204 			set_ua = 1;
6205 		}
6206 	} else {
6207 		if (user_cp->queue_flags & SCP_QUEUE_DQUE) {
6208 #ifdef NEEDTOPORT
6209 			csevent_log(CSC_CTL | CSC_SHELF_SW |
6210 				    CTL_TAG_TO_UNTAG,
6211 				    csevent_LogType_ConfigChange,
6212 				    csevent_Severity_Warning,
6213 				    csevent_AlertLevel_Yellow,
6214 				    csevent_FRU_Firmware,
6215 				    csevent_FRU_Unknown,
6216 				    "Received tagged queueing to untagged "
6217 				    "transition");
6218 #endif /* NEEDTOPORT */
6219 
6220 			current_cp->queue_flags |= SCP_QUEUE_DQUE;
6221 			saved_cp->queue_flags |= SCP_QUEUE_DQUE;
6222 			set_ua = 1;
6223 		} else {
6224 #ifdef NEEDTOPORT
6225 			csevent_log(CSC_CTL | CSC_SHELF_SW |
6226 				    CTL_TAG_TO_TAG,
6227 				    csevent_LogType_Trace,
6228 				    csevent_Severity_Information,
6229 				    csevent_AlertLevel_Green,
6230 				    csevent_FRU_Firmware,
6231 				    csevent_FRU_Unknown,
6232 				    "Received tagged queueing to tagged "
6233 				    "queueing transition");
6234 #endif /* NEEDTOPORT */
6235 		}
6236 	}
6237 	if (set_ua != 0) {
6238 		int i;
6239 		/*
6240 		 * Let other initiators know that the mode
6241 		 * parameters for this LUN have changed.
6242 		 */
6243 		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
6244 			if (i == initidx)
6245 				continue;
6246 
6247 			lun->pending_ua[i] |= CTL_UA_MODE_CHANGE;
6248 		}
6249 	}
6250 	mtx_unlock(&lun->lun_lock);
6251 
6252 	return (0);
6253 }
6254 
6255 int
6256 ctl_caching_sp_handler(struct ctl_scsiio *ctsio,
6257 		     struct ctl_page_index *page_index, uint8_t *page_ptr)
6258 {
6259 	struct scsi_caching_page *current_cp, *saved_cp, *user_cp;
6260 	struct ctl_lun *lun;
6261 	int set_ua;
6262 	uint32_t initidx;
6263 
6264 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6265 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6266 	set_ua = 0;
6267 
6268 	user_cp = (struct scsi_caching_page *)page_ptr;
6269 	current_cp = (struct scsi_caching_page *)
6270 		(page_index->page_data + (page_index->page_len *
6271 		CTL_PAGE_CURRENT));
6272 	saved_cp = (struct scsi_caching_page *)
6273 		(page_index->page_data + (page_index->page_len *
6274 		CTL_PAGE_SAVED));
6275 
6276 	mtx_lock(&lun->lun_lock);
6277 	if ((current_cp->flags1 & (SCP_WCE | SCP_RCD)) !=
6278 	    (user_cp->flags1 & (SCP_WCE | SCP_RCD)))
6279 		set_ua = 1;
6280 	current_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6281 	current_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6282 	saved_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6283 	saved_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6284 	if (set_ua != 0) {
6285 		int i;
6286 		/*
6287 		 * Let other initiators know that the mode
6288 		 * parameters for this LUN have changed.
6289 		 */
6290 		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
6291 			if (i == initidx)
6292 				continue;
6293 
6294 			lun->pending_ua[i] |= CTL_UA_MODE_CHANGE;
6295 		}
6296 	}
6297 	mtx_unlock(&lun->lun_lock);
6298 
6299 	return (0);
6300 }
6301 
6302 int
6303 ctl_power_sp_handler(struct ctl_scsiio *ctsio,
6304 		     struct ctl_page_index *page_index, uint8_t *page_ptr)
6305 {
6306 	return (0);
6307 }
6308 
6309 int
6310 ctl_power_sp_sense_handler(struct ctl_scsiio *ctsio,
6311 			   struct ctl_page_index *page_index, int pc)
6312 {
6313 	struct copan_power_subpage *page;
6314 
6315 	page = (struct copan_power_subpage *)page_index->page_data +
6316 		(page_index->page_len * pc);
6317 
6318 	switch (pc) {
6319 	case SMS_PAGE_CTRL_CHANGEABLE >> 6:
6320 		/*
6321 		 * We don't update the changable bits for this page.
6322 		 */
6323 		break;
6324 	case SMS_PAGE_CTRL_CURRENT >> 6:
6325 	case SMS_PAGE_CTRL_DEFAULT >> 6:
6326 	case SMS_PAGE_CTRL_SAVED >> 6:
6327 #ifdef NEEDTOPORT
6328 		ctl_update_power_subpage(page);
6329 #endif
6330 		break;
6331 	default:
6332 #ifdef NEEDTOPORT
6333 		EPRINT(0, "Invalid PC %d!!", pc);
6334 #endif
6335 		break;
6336 	}
6337 	return (0);
6338 }
6339 
6340 
6341 int
6342 ctl_aps_sp_handler(struct ctl_scsiio *ctsio,
6343 		   struct ctl_page_index *page_index, uint8_t *page_ptr)
6344 {
6345 	struct copan_aps_subpage *user_sp;
6346 	struct copan_aps_subpage *current_sp;
6347 	union ctl_modepage_info *modepage_info;
6348 	struct ctl_softc *softc;
6349 	struct ctl_lun *lun;
6350 	int retval;
6351 
6352 	retval = CTL_RETVAL_COMPLETE;
6353 	current_sp = (struct copan_aps_subpage *)(page_index->page_data +
6354 		     (page_index->page_len * CTL_PAGE_CURRENT));
6355 	softc = control_softc;
6356 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6357 
6358 	user_sp = (struct copan_aps_subpage *)page_ptr;
6359 
6360 	modepage_info = (union ctl_modepage_info *)
6361 		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6362 
6363 	modepage_info->header.page_code = page_index->page_code & SMPH_PC_MASK;
6364 	modepage_info->header.subpage = page_index->subpage;
6365 	modepage_info->aps.lock_active = user_sp->lock_active;
6366 
6367 	mtx_lock(&softc->ctl_lock);
6368 
6369 	/*
6370 	 * If there is a request to lock the LUN and another LUN is locked
6371 	 * this is an error. If the requested LUN is already locked ignore
6372 	 * the request. If no LUN is locked attempt to lock it.
6373 	 * if there is a request to unlock the LUN and the LUN is currently
6374 	 * locked attempt to unlock it. Otherwise ignore the request. i.e.
6375 	 * if another LUN is locked or no LUN is locked.
6376 	 */
6377 	if (user_sp->lock_active & APS_LOCK_ACTIVE) {
6378 		if (softc->aps_locked_lun == lun->lun) {
6379 			/*
6380 			 * This LUN is already locked, so we're done.
6381 			 */
6382 			retval = CTL_RETVAL_COMPLETE;
6383 		} else if (softc->aps_locked_lun == 0) {
6384 			/*
6385 			 * No one has the lock, pass the request to the
6386 			 * backend.
6387 			 */
6388 			retval = lun->backend->config_write(
6389 				(union ctl_io *)ctsio);
6390 		} else {
6391 			/*
6392 			 * Someone else has the lock, throw out the request.
6393 			 */
6394 			ctl_set_already_locked(ctsio);
6395 			free(ctsio->kern_data_ptr, M_CTL);
6396 			ctl_done((union ctl_io *)ctsio);
6397 
6398 			/*
6399 			 * Set the return value so that ctl_do_mode_select()
6400 			 * won't try to complete the command.  We already
6401 			 * completed it here.
6402 			 */
6403 			retval = CTL_RETVAL_ERROR;
6404 		}
6405 	} else if (softc->aps_locked_lun == lun->lun) {
6406 		/*
6407 		 * This LUN is locked, so pass the unlock request to the
6408 		 * backend.
6409 		 */
6410 		retval = lun->backend->config_write((union ctl_io *)ctsio);
6411 	}
6412 	mtx_unlock(&softc->ctl_lock);
6413 
6414 	return (retval);
6415 }
6416 
6417 int
6418 ctl_debugconf_sp_select_handler(struct ctl_scsiio *ctsio,
6419 				struct ctl_page_index *page_index,
6420 				uint8_t *page_ptr)
6421 {
6422 	uint8_t *c;
6423 	int i;
6424 
6425 	c = ((struct copan_debugconf_subpage *)page_ptr)->ctl_time_io_secs;
6426 	ctl_time_io_secs =
6427 		(c[0] << 8) |
6428 		(c[1] << 0) |
6429 		0;
6430 	CTL_DEBUG_PRINT(("set ctl_time_io_secs to %d\n", ctl_time_io_secs));
6431 	printf("set ctl_time_io_secs to %d\n", ctl_time_io_secs);
6432 	printf("page data:");
6433 	for (i=0; i<8; i++)
6434 		printf(" %.2x",page_ptr[i]);
6435 	printf("\n");
6436 	return (0);
6437 }
6438 
6439 int
6440 ctl_debugconf_sp_sense_handler(struct ctl_scsiio *ctsio,
6441 			       struct ctl_page_index *page_index,
6442 			       int pc)
6443 {
6444 	struct copan_debugconf_subpage *page;
6445 
6446 	page = (struct copan_debugconf_subpage *)page_index->page_data +
6447 		(page_index->page_len * pc);
6448 
6449 	switch (pc) {
6450 	case SMS_PAGE_CTRL_CHANGEABLE >> 6:
6451 	case SMS_PAGE_CTRL_DEFAULT >> 6:
6452 	case SMS_PAGE_CTRL_SAVED >> 6:
6453 		/*
6454 		 * We don't update the changable or default bits for this page.
6455 		 */
6456 		break;
6457 	case SMS_PAGE_CTRL_CURRENT >> 6:
6458 		page->ctl_time_io_secs[0] = ctl_time_io_secs >> 8;
6459 		page->ctl_time_io_secs[1] = ctl_time_io_secs >> 0;
6460 		break;
6461 	default:
6462 #ifdef NEEDTOPORT
6463 		EPRINT(0, "Invalid PC %d!!", pc);
6464 #endif /* NEEDTOPORT */
6465 		break;
6466 	}
6467 	return (0);
6468 }
6469 
6470 
6471 static int
6472 ctl_do_mode_select(union ctl_io *io)
6473 {
6474 	struct scsi_mode_page_header *page_header;
6475 	struct ctl_page_index *page_index;
6476 	struct ctl_scsiio *ctsio;
6477 	int control_dev, page_len;
6478 	int page_len_offset, page_len_size;
6479 	union ctl_modepage_info *modepage_info;
6480 	struct ctl_lun *lun;
6481 	int *len_left, *len_used;
6482 	int retval, i;
6483 
6484 	ctsio = &io->scsiio;
6485 	page_index = NULL;
6486 	page_len = 0;
6487 	retval = CTL_RETVAL_COMPLETE;
6488 
6489 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6490 
6491 	if (lun->be_lun->lun_type != T_DIRECT)
6492 		control_dev = 1;
6493 	else
6494 		control_dev = 0;
6495 
6496 	modepage_info = (union ctl_modepage_info *)
6497 		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6498 	len_left = &modepage_info->header.len_left;
6499 	len_used = &modepage_info->header.len_used;
6500 
6501 do_next_page:
6502 
6503 	page_header = (struct scsi_mode_page_header *)
6504 		(ctsio->kern_data_ptr + *len_used);
6505 
6506 	if (*len_left == 0) {
6507 		free(ctsio->kern_data_ptr, M_CTL);
6508 		ctl_set_success(ctsio);
6509 		ctl_done((union ctl_io *)ctsio);
6510 		return (CTL_RETVAL_COMPLETE);
6511 	} else if (*len_left < sizeof(struct scsi_mode_page_header)) {
6512 
6513 		free(ctsio->kern_data_ptr, M_CTL);
6514 		ctl_set_param_len_error(ctsio);
6515 		ctl_done((union ctl_io *)ctsio);
6516 		return (CTL_RETVAL_COMPLETE);
6517 
6518 	} else if ((page_header->page_code & SMPH_SPF)
6519 		&& (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
6520 
6521 		free(ctsio->kern_data_ptr, M_CTL);
6522 		ctl_set_param_len_error(ctsio);
6523 		ctl_done((union ctl_io *)ctsio);
6524 		return (CTL_RETVAL_COMPLETE);
6525 	}
6526 
6527 
6528 	/*
6529 	 * XXX KDM should we do something with the block descriptor?
6530 	 */
6531 	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6532 
6533 		if ((control_dev != 0)
6534 		 && (lun->mode_pages.index[i].page_flags &
6535 		     CTL_PAGE_FLAG_DISK_ONLY))
6536 			continue;
6537 
6538 		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
6539 		    (page_header->page_code & SMPH_PC_MASK))
6540 			continue;
6541 
6542 		/*
6543 		 * If neither page has a subpage code, then we've got a
6544 		 * match.
6545 		 */
6546 		if (((lun->mode_pages.index[i].page_code & SMPH_SPF) == 0)
6547 		 && ((page_header->page_code & SMPH_SPF) == 0)) {
6548 			page_index = &lun->mode_pages.index[i];
6549 			page_len = page_header->page_length;
6550 			break;
6551 		}
6552 
6553 		/*
6554 		 * If both pages have subpages, then the subpage numbers
6555 		 * have to match.
6556 		 */
6557 		if ((lun->mode_pages.index[i].page_code & SMPH_SPF)
6558 		  && (page_header->page_code & SMPH_SPF)) {
6559 			struct scsi_mode_page_header_sp *sph;
6560 
6561 			sph = (struct scsi_mode_page_header_sp *)page_header;
6562 
6563 			if (lun->mode_pages.index[i].subpage ==
6564 			    sph->subpage) {
6565 				page_index = &lun->mode_pages.index[i];
6566 				page_len = scsi_2btoul(sph->page_length);
6567 				break;
6568 			}
6569 		}
6570 	}
6571 
6572 	/*
6573 	 * If we couldn't find the page, or if we don't have a mode select
6574 	 * handler for it, send back an error to the user.
6575 	 */
6576 	if ((page_index == NULL)
6577 	 || (page_index->select_handler == NULL)) {
6578 		ctl_set_invalid_field(ctsio,
6579 				      /*sks_valid*/ 1,
6580 				      /*command*/ 0,
6581 				      /*field*/ *len_used,
6582 				      /*bit_valid*/ 0,
6583 				      /*bit*/ 0);
6584 		free(ctsio->kern_data_ptr, M_CTL);
6585 		ctl_done((union ctl_io *)ctsio);
6586 		return (CTL_RETVAL_COMPLETE);
6587 	}
6588 
6589 	if (page_index->page_code & SMPH_SPF) {
6590 		page_len_offset = 2;
6591 		page_len_size = 2;
6592 	} else {
6593 		page_len_size = 1;
6594 		page_len_offset = 1;
6595 	}
6596 
6597 	/*
6598 	 * If the length the initiator gives us isn't the one we specify in
6599 	 * the mode page header, or if they didn't specify enough data in
6600 	 * the CDB to avoid truncating this page, kick out the request.
6601 	 */
6602 	if ((page_len != (page_index->page_len - page_len_offset -
6603 			  page_len_size))
6604 	 || (*len_left < page_index->page_len)) {
6605 
6606 
6607 		ctl_set_invalid_field(ctsio,
6608 				      /*sks_valid*/ 1,
6609 				      /*command*/ 0,
6610 				      /*field*/ *len_used + page_len_offset,
6611 				      /*bit_valid*/ 0,
6612 				      /*bit*/ 0);
6613 		free(ctsio->kern_data_ptr, M_CTL);
6614 		ctl_done((union ctl_io *)ctsio);
6615 		return (CTL_RETVAL_COMPLETE);
6616 	}
6617 
6618 	/*
6619 	 * Run through the mode page, checking to make sure that the bits
6620 	 * the user changed are actually legal for him to change.
6621 	 */
6622 	for (i = 0; i < page_index->page_len; i++) {
6623 		uint8_t *user_byte, *change_mask, *current_byte;
6624 		int bad_bit;
6625 		int j;
6626 
6627 		user_byte = (uint8_t *)page_header + i;
6628 		change_mask = page_index->page_data +
6629 			      (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6630 		current_byte = page_index->page_data +
6631 			       (page_index->page_len * CTL_PAGE_CURRENT) + i;
6632 
6633 		/*
6634 		 * Check to see whether the user set any bits in this byte
6635 		 * that he is not allowed to set.
6636 		 */
6637 		if ((*user_byte & ~(*change_mask)) ==
6638 		    (*current_byte & ~(*change_mask)))
6639 			continue;
6640 
6641 		/*
6642 		 * Go through bit by bit to determine which one is illegal.
6643 		 */
6644 		bad_bit = 0;
6645 		for (j = 7; j >= 0; j--) {
6646 			if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6647 			    (((1 << i) & ~(*change_mask)) & *current_byte)) {
6648 				bad_bit = i;
6649 				break;
6650 			}
6651 		}
6652 		ctl_set_invalid_field(ctsio,
6653 				      /*sks_valid*/ 1,
6654 				      /*command*/ 0,
6655 				      /*field*/ *len_used + i,
6656 				      /*bit_valid*/ 1,
6657 				      /*bit*/ bad_bit);
6658 		free(ctsio->kern_data_ptr, M_CTL);
6659 		ctl_done((union ctl_io *)ctsio);
6660 		return (CTL_RETVAL_COMPLETE);
6661 	}
6662 
6663 	/*
6664 	 * Decrement these before we call the page handler, since we may
6665 	 * end up getting called back one way or another before the handler
6666 	 * returns to this context.
6667 	 */
6668 	*len_left -= page_index->page_len;
6669 	*len_used += page_index->page_len;
6670 
6671 	retval = page_index->select_handler(ctsio, page_index,
6672 					    (uint8_t *)page_header);
6673 
6674 	/*
6675 	 * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6676 	 * wait until this queued command completes to finish processing
6677 	 * the mode page.  If it returns anything other than
6678 	 * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6679 	 * already set the sense information, freed the data pointer, and
6680 	 * completed the io for us.
6681 	 */
6682 	if (retval != CTL_RETVAL_COMPLETE)
6683 		goto bailout_no_done;
6684 
6685 	/*
6686 	 * If the initiator sent us more than one page, parse the next one.
6687 	 */
6688 	if (*len_left > 0)
6689 		goto do_next_page;
6690 
6691 	ctl_set_success(ctsio);
6692 	free(ctsio->kern_data_ptr, M_CTL);
6693 	ctl_done((union ctl_io *)ctsio);
6694 
6695 bailout_no_done:
6696 
6697 	return (CTL_RETVAL_COMPLETE);
6698 
6699 }
6700 
6701 int
6702 ctl_mode_select(struct ctl_scsiio *ctsio)
6703 {
6704 	int param_len, pf, sp;
6705 	int header_size, bd_len;
6706 	int len_left, len_used;
6707 	struct ctl_page_index *page_index;
6708 	struct ctl_lun *lun;
6709 	int control_dev, page_len;
6710 	union ctl_modepage_info *modepage_info;
6711 	int retval;
6712 
6713 	pf = 0;
6714 	sp = 0;
6715 	page_len = 0;
6716 	len_used = 0;
6717 	len_left = 0;
6718 	retval = 0;
6719 	bd_len = 0;
6720 	page_index = NULL;
6721 
6722 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6723 
6724 	if (lun->be_lun->lun_type != T_DIRECT)
6725 		control_dev = 1;
6726 	else
6727 		control_dev = 0;
6728 
6729 	switch (ctsio->cdb[0]) {
6730 	case MODE_SELECT_6: {
6731 		struct scsi_mode_select_6 *cdb;
6732 
6733 		cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6734 
6735 		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6736 		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6737 
6738 		param_len = cdb->length;
6739 		header_size = sizeof(struct scsi_mode_header_6);
6740 		break;
6741 	}
6742 	case MODE_SELECT_10: {
6743 		struct scsi_mode_select_10 *cdb;
6744 
6745 		cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6746 
6747 		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6748 		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6749 
6750 		param_len = scsi_2btoul(cdb->length);
6751 		header_size = sizeof(struct scsi_mode_header_10);
6752 		break;
6753 	}
6754 	default:
6755 		ctl_set_invalid_opcode(ctsio);
6756 		ctl_done((union ctl_io *)ctsio);
6757 		return (CTL_RETVAL_COMPLETE);
6758 		break; /* NOTREACHED */
6759 	}
6760 
6761 	/*
6762 	 * From SPC-3:
6763 	 * "A parameter list length of zero indicates that the Data-Out Buffer
6764 	 * shall be empty. This condition shall not be considered as an error."
6765 	 */
6766 	if (param_len == 0) {
6767 		ctl_set_success(ctsio);
6768 		ctl_done((union ctl_io *)ctsio);
6769 		return (CTL_RETVAL_COMPLETE);
6770 	}
6771 
6772 	/*
6773 	 * Since we'll hit this the first time through, prior to
6774 	 * allocation, we don't need to free a data buffer here.
6775 	 */
6776 	if (param_len < header_size) {
6777 		ctl_set_param_len_error(ctsio);
6778 		ctl_done((union ctl_io *)ctsio);
6779 		return (CTL_RETVAL_COMPLETE);
6780 	}
6781 
6782 	/*
6783 	 * Allocate the data buffer and grab the user's data.  In theory,
6784 	 * we shouldn't have to sanity check the parameter list length here
6785 	 * because the maximum size is 64K.  We should be able to malloc
6786 	 * that much without too many problems.
6787 	 */
6788 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6789 		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6790 		ctsio->kern_data_len = param_len;
6791 		ctsio->kern_total_len = param_len;
6792 		ctsio->kern_data_resid = 0;
6793 		ctsio->kern_rel_offset = 0;
6794 		ctsio->kern_sg_entries = 0;
6795 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6796 		ctsio->be_move_done = ctl_config_move_done;
6797 		ctl_datamove((union ctl_io *)ctsio);
6798 
6799 		return (CTL_RETVAL_COMPLETE);
6800 	}
6801 
6802 	switch (ctsio->cdb[0]) {
6803 	case MODE_SELECT_6: {
6804 		struct scsi_mode_header_6 *mh6;
6805 
6806 		mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6807 		bd_len = mh6->blk_desc_len;
6808 		break;
6809 	}
6810 	case MODE_SELECT_10: {
6811 		struct scsi_mode_header_10 *mh10;
6812 
6813 		mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6814 		bd_len = scsi_2btoul(mh10->blk_desc_len);
6815 		break;
6816 	}
6817 	default:
6818 		panic("Invalid CDB type %#x", ctsio->cdb[0]);
6819 		break;
6820 	}
6821 
6822 	if (param_len < (header_size + bd_len)) {
6823 		free(ctsio->kern_data_ptr, M_CTL);
6824 		ctl_set_param_len_error(ctsio);
6825 		ctl_done((union ctl_io *)ctsio);
6826 		return (CTL_RETVAL_COMPLETE);
6827 	}
6828 
6829 	/*
6830 	 * Set the IO_CONT flag, so that if this I/O gets passed to
6831 	 * ctl_config_write_done(), it'll get passed back to
6832 	 * ctl_do_mode_select() for further processing, or completion if
6833 	 * we're all done.
6834 	 */
6835 	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6836 	ctsio->io_cont = ctl_do_mode_select;
6837 
6838 	modepage_info = (union ctl_modepage_info *)
6839 		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6840 
6841 	memset(modepage_info, 0, sizeof(*modepage_info));
6842 
6843 	len_left = param_len - header_size - bd_len;
6844 	len_used = header_size + bd_len;
6845 
6846 	modepage_info->header.len_left = len_left;
6847 	modepage_info->header.len_used = len_used;
6848 
6849 	return (ctl_do_mode_select((union ctl_io *)ctsio));
6850 }
6851 
6852 int
6853 ctl_mode_sense(struct ctl_scsiio *ctsio)
6854 {
6855 	struct ctl_lun *lun;
6856 	int pc, page_code, dbd, llba, subpage;
6857 	int alloc_len, page_len, header_len, total_len;
6858 	struct scsi_mode_block_descr *block_desc;
6859 	struct ctl_page_index *page_index;
6860 	int control_dev;
6861 
6862 	dbd = 0;
6863 	llba = 0;
6864 	block_desc = NULL;
6865 	page_index = NULL;
6866 
6867 	CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6868 
6869 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6870 
6871 	if (lun->be_lun->lun_type != T_DIRECT)
6872 		control_dev = 1;
6873 	else
6874 		control_dev = 0;
6875 
6876 	if (lun->flags & CTL_LUN_PR_RESERVED) {
6877 		uint32_t residx;
6878 
6879 		/*
6880 		 * XXX KDM need a lock here.
6881 		 */
6882 		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
6883 		if ((lun->res_type == SPR_TYPE_EX_AC
6884 		  && residx != lun->pr_res_idx)
6885 		 || ((lun->res_type == SPR_TYPE_EX_AC_RO
6886 		   || lun->res_type == SPR_TYPE_EX_AC_AR)
6887 		  && !lun->per_res[residx].registered)) {
6888 			ctl_set_reservation_conflict(ctsio);
6889 			ctl_done((union ctl_io *)ctsio);
6890 			return (CTL_RETVAL_COMPLETE);
6891 		}
6892 	}
6893 
6894 	switch (ctsio->cdb[0]) {
6895 	case MODE_SENSE_6: {
6896 		struct scsi_mode_sense_6 *cdb;
6897 
6898 		cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6899 
6900 		header_len = sizeof(struct scsi_mode_hdr_6);
6901 		if (cdb->byte2 & SMS_DBD)
6902 			dbd = 1;
6903 		else
6904 			header_len += sizeof(struct scsi_mode_block_descr);
6905 
6906 		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6907 		page_code = cdb->page & SMS_PAGE_CODE;
6908 		subpage = cdb->subpage;
6909 		alloc_len = cdb->length;
6910 		break;
6911 	}
6912 	case MODE_SENSE_10: {
6913 		struct scsi_mode_sense_10 *cdb;
6914 
6915 		cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6916 
6917 		header_len = sizeof(struct scsi_mode_hdr_10);
6918 
6919 		if (cdb->byte2 & SMS_DBD)
6920 			dbd = 1;
6921 		else
6922 			header_len += sizeof(struct scsi_mode_block_descr);
6923 		if (cdb->byte2 & SMS10_LLBAA)
6924 			llba = 1;
6925 		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6926 		page_code = cdb->page & SMS_PAGE_CODE;
6927 		subpage = cdb->subpage;
6928 		alloc_len = scsi_2btoul(cdb->length);
6929 		break;
6930 	}
6931 	default:
6932 		ctl_set_invalid_opcode(ctsio);
6933 		ctl_done((union ctl_io *)ctsio);
6934 		return (CTL_RETVAL_COMPLETE);
6935 		break; /* NOTREACHED */
6936 	}
6937 
6938 	/*
6939 	 * We have to make a first pass through to calculate the size of
6940 	 * the pages that match the user's query.  Then we allocate enough
6941 	 * memory to hold it, and actually copy the data into the buffer.
6942 	 */
6943 	switch (page_code) {
6944 	case SMS_ALL_PAGES_PAGE: {
6945 		int i;
6946 
6947 		page_len = 0;
6948 
6949 		/*
6950 		 * At the moment, values other than 0 and 0xff here are
6951 		 * reserved according to SPC-3.
6952 		 */
6953 		if ((subpage != SMS_SUBPAGE_PAGE_0)
6954 		 && (subpage != SMS_SUBPAGE_ALL)) {
6955 			ctl_set_invalid_field(ctsio,
6956 					      /*sks_valid*/ 1,
6957 					      /*command*/ 1,
6958 					      /*field*/ 3,
6959 					      /*bit_valid*/ 0,
6960 					      /*bit*/ 0);
6961 			ctl_done((union ctl_io *)ctsio);
6962 			return (CTL_RETVAL_COMPLETE);
6963 		}
6964 
6965 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6966 			if ((control_dev != 0)
6967 			 && (lun->mode_pages.index[i].page_flags &
6968 			     CTL_PAGE_FLAG_DISK_ONLY))
6969 				continue;
6970 
6971 			/*
6972 			 * We don't use this subpage if the user didn't
6973 			 * request all subpages.
6974 			 */
6975 			if ((lun->mode_pages.index[i].subpage != 0)
6976 			 && (subpage == SMS_SUBPAGE_PAGE_0))
6977 				continue;
6978 
6979 #if 0
6980 			printf("found page %#x len %d\n",
6981 			       lun->mode_pages.index[i].page_code &
6982 			       SMPH_PC_MASK,
6983 			       lun->mode_pages.index[i].page_len);
6984 #endif
6985 			page_len += lun->mode_pages.index[i].page_len;
6986 		}
6987 		break;
6988 	}
6989 	default: {
6990 		int i;
6991 
6992 		page_len = 0;
6993 
6994 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6995 			/* Look for the right page code */
6996 			if ((lun->mode_pages.index[i].page_code &
6997 			     SMPH_PC_MASK) != page_code)
6998 				continue;
6999 
7000 			/* Look for the right subpage or the subpage wildcard*/
7001 			if ((lun->mode_pages.index[i].subpage != subpage)
7002 			 && (subpage != SMS_SUBPAGE_ALL))
7003 				continue;
7004 
7005 			/* Make sure the page is supported for this dev type */
7006 			if ((control_dev != 0)
7007 			 && (lun->mode_pages.index[i].page_flags &
7008 			     CTL_PAGE_FLAG_DISK_ONLY))
7009 				continue;
7010 
7011 #if 0
7012 			printf("found page %#x len %d\n",
7013 			       lun->mode_pages.index[i].page_code &
7014 			       SMPH_PC_MASK,
7015 			       lun->mode_pages.index[i].page_len);
7016 #endif
7017 
7018 			page_len += lun->mode_pages.index[i].page_len;
7019 		}
7020 
7021 		if (page_len == 0) {
7022 			ctl_set_invalid_field(ctsio,
7023 					      /*sks_valid*/ 1,
7024 					      /*command*/ 1,
7025 					      /*field*/ 2,
7026 					      /*bit_valid*/ 1,
7027 					      /*bit*/ 5);
7028 			ctl_done((union ctl_io *)ctsio);
7029 			return (CTL_RETVAL_COMPLETE);
7030 		}
7031 		break;
7032 	}
7033 	}
7034 
7035 	total_len = header_len + page_len;
7036 #if 0
7037 	printf("header_len = %d, page_len = %d, total_len = %d\n",
7038 	       header_len, page_len, total_len);
7039 #endif
7040 
7041 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7042 	ctsio->kern_sg_entries = 0;
7043 	ctsio->kern_data_resid = 0;
7044 	ctsio->kern_rel_offset = 0;
7045 	if (total_len < alloc_len) {
7046 		ctsio->residual = alloc_len - total_len;
7047 		ctsio->kern_data_len = total_len;
7048 		ctsio->kern_total_len = total_len;
7049 	} else {
7050 		ctsio->residual = 0;
7051 		ctsio->kern_data_len = alloc_len;
7052 		ctsio->kern_total_len = alloc_len;
7053 	}
7054 
7055 	switch (ctsio->cdb[0]) {
7056 	case MODE_SENSE_6: {
7057 		struct scsi_mode_hdr_6 *header;
7058 
7059 		header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
7060 
7061 		header->datalen = ctl_min(total_len - 1, 254);
7062 		if (control_dev == 0)
7063 			header->dev_specific = 0x10; /* DPOFUA */
7064 		if (dbd)
7065 			header->block_descr_len = 0;
7066 		else
7067 			header->block_descr_len =
7068 				sizeof(struct scsi_mode_block_descr);
7069 		block_desc = (struct scsi_mode_block_descr *)&header[1];
7070 		break;
7071 	}
7072 	case MODE_SENSE_10: {
7073 		struct scsi_mode_hdr_10 *header;
7074 		int datalen;
7075 
7076 		header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
7077 
7078 		datalen = ctl_min(total_len - 2, 65533);
7079 		scsi_ulto2b(datalen, header->datalen);
7080 		if (control_dev == 0)
7081 			header->dev_specific = 0x10; /* DPOFUA */
7082 		if (dbd)
7083 			scsi_ulto2b(0, header->block_descr_len);
7084 		else
7085 			scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
7086 				    header->block_descr_len);
7087 		block_desc = (struct scsi_mode_block_descr *)&header[1];
7088 		break;
7089 	}
7090 	default:
7091 		panic("invalid CDB type %#x", ctsio->cdb[0]);
7092 		break; /* NOTREACHED */
7093 	}
7094 
7095 	/*
7096 	 * If we've got a disk, use its blocksize in the block
7097 	 * descriptor.  Otherwise, just set it to 0.
7098 	 */
7099 	if (dbd == 0) {
7100 		if (control_dev != 0)
7101 			scsi_ulto3b(lun->be_lun->blocksize,
7102 				    block_desc->block_len);
7103 		else
7104 			scsi_ulto3b(0, block_desc->block_len);
7105 	}
7106 
7107 	switch (page_code) {
7108 	case SMS_ALL_PAGES_PAGE: {
7109 		int i, data_used;
7110 
7111 		data_used = header_len;
7112 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
7113 			struct ctl_page_index *page_index;
7114 
7115 			page_index = &lun->mode_pages.index[i];
7116 
7117 			if ((control_dev != 0)
7118 			 && (page_index->page_flags &
7119 			    CTL_PAGE_FLAG_DISK_ONLY))
7120 				continue;
7121 
7122 			/*
7123 			 * We don't use this subpage if the user didn't
7124 			 * request all subpages.  We already checked (above)
7125 			 * to make sure the user only specified a subpage
7126 			 * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
7127 			 */
7128 			if ((page_index->subpage != 0)
7129 			 && (subpage == SMS_SUBPAGE_PAGE_0))
7130 				continue;
7131 
7132 			/*
7133 			 * Call the handler, if it exists, to update the
7134 			 * page to the latest values.
7135 			 */
7136 			if (page_index->sense_handler != NULL)
7137 				page_index->sense_handler(ctsio, page_index,pc);
7138 
7139 			memcpy(ctsio->kern_data_ptr + data_used,
7140 			       page_index->page_data +
7141 			       (page_index->page_len * pc),
7142 			       page_index->page_len);
7143 			data_used += page_index->page_len;
7144 		}
7145 		break;
7146 	}
7147 	default: {
7148 		int i, data_used;
7149 
7150 		data_used = header_len;
7151 
7152 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
7153 			struct ctl_page_index *page_index;
7154 
7155 			page_index = &lun->mode_pages.index[i];
7156 
7157 			/* Look for the right page code */
7158 			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
7159 				continue;
7160 
7161 			/* Look for the right subpage or the subpage wildcard*/
7162 			if ((page_index->subpage != subpage)
7163 			 && (subpage != SMS_SUBPAGE_ALL))
7164 				continue;
7165 
7166 			/* Make sure the page is supported for this dev type */
7167 			if ((control_dev != 0)
7168 			 && (page_index->page_flags &
7169 			     CTL_PAGE_FLAG_DISK_ONLY))
7170 				continue;
7171 
7172 			/*
7173 			 * Call the handler, if it exists, to update the
7174 			 * page to the latest values.
7175 			 */
7176 			if (page_index->sense_handler != NULL)
7177 				page_index->sense_handler(ctsio, page_index,pc);
7178 
7179 			memcpy(ctsio->kern_data_ptr + data_used,
7180 			       page_index->page_data +
7181 			       (page_index->page_len * pc),
7182 			       page_index->page_len);
7183 			data_used += page_index->page_len;
7184 		}
7185 		break;
7186 	}
7187 	}
7188 
7189 	ctsio->scsi_status = SCSI_STATUS_OK;
7190 
7191 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7192 	ctsio->be_move_done = ctl_config_move_done;
7193 	ctl_datamove((union ctl_io *)ctsio);
7194 
7195 	return (CTL_RETVAL_COMPLETE);
7196 }
7197 
7198 int
7199 ctl_read_capacity(struct ctl_scsiio *ctsio)
7200 {
7201 	struct scsi_read_capacity *cdb;
7202 	struct scsi_read_capacity_data *data;
7203 	struct ctl_lun *lun;
7204 	uint32_t lba;
7205 
7206 	CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
7207 
7208 	cdb = (struct scsi_read_capacity *)ctsio->cdb;
7209 
7210 	lba = scsi_4btoul(cdb->addr);
7211 	if (((cdb->pmi & SRC_PMI) == 0)
7212 	 && (lba != 0)) {
7213 		ctl_set_invalid_field(/*ctsio*/ ctsio,
7214 				      /*sks_valid*/ 1,
7215 				      /*command*/ 1,
7216 				      /*field*/ 2,
7217 				      /*bit_valid*/ 0,
7218 				      /*bit*/ 0);
7219 		ctl_done((union ctl_io *)ctsio);
7220 		return (CTL_RETVAL_COMPLETE);
7221 	}
7222 
7223 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7224 
7225 	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7226 	data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
7227 	ctsio->residual = 0;
7228 	ctsio->kern_data_len = sizeof(*data);
7229 	ctsio->kern_total_len = sizeof(*data);
7230 	ctsio->kern_data_resid = 0;
7231 	ctsio->kern_rel_offset = 0;
7232 	ctsio->kern_sg_entries = 0;
7233 
7234 	/*
7235 	 * If the maximum LBA is greater than 0xfffffffe, the user must
7236 	 * issue a SERVICE ACTION IN (16) command, with the read capacity
7237 	 * serivce action set.
7238 	 */
7239 	if (lun->be_lun->maxlba > 0xfffffffe)
7240 		scsi_ulto4b(0xffffffff, data->addr);
7241 	else
7242 		scsi_ulto4b(lun->be_lun->maxlba, data->addr);
7243 
7244 	/*
7245 	 * XXX KDM this may not be 512 bytes...
7246 	 */
7247 	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7248 
7249 	ctsio->scsi_status = SCSI_STATUS_OK;
7250 
7251 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7252 	ctsio->be_move_done = ctl_config_move_done;
7253 	ctl_datamove((union ctl_io *)ctsio);
7254 
7255 	return (CTL_RETVAL_COMPLETE);
7256 }
7257 
7258 int
7259 ctl_read_capacity_16(struct ctl_scsiio *ctsio)
7260 {
7261 	struct scsi_read_capacity_16 *cdb;
7262 	struct scsi_read_capacity_data_long *data;
7263 	struct ctl_lun *lun;
7264 	uint64_t lba;
7265 	uint32_t alloc_len;
7266 
7267 	CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
7268 
7269 	cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
7270 
7271 	alloc_len = scsi_4btoul(cdb->alloc_len);
7272 	lba = scsi_8btou64(cdb->addr);
7273 
7274 	if ((cdb->reladr & SRC16_PMI)
7275 	 && (lba != 0)) {
7276 		ctl_set_invalid_field(/*ctsio*/ ctsio,
7277 				      /*sks_valid*/ 1,
7278 				      /*command*/ 1,
7279 				      /*field*/ 2,
7280 				      /*bit_valid*/ 0,
7281 				      /*bit*/ 0);
7282 		ctl_done((union ctl_io *)ctsio);
7283 		return (CTL_RETVAL_COMPLETE);
7284 	}
7285 
7286 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7287 
7288 	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7289 	data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
7290 
7291 	if (sizeof(*data) < alloc_len) {
7292 		ctsio->residual = alloc_len - sizeof(*data);
7293 		ctsio->kern_data_len = sizeof(*data);
7294 		ctsio->kern_total_len = sizeof(*data);
7295 	} else {
7296 		ctsio->residual = 0;
7297 		ctsio->kern_data_len = alloc_len;
7298 		ctsio->kern_total_len = alloc_len;
7299 	}
7300 	ctsio->kern_data_resid = 0;
7301 	ctsio->kern_rel_offset = 0;
7302 	ctsio->kern_sg_entries = 0;
7303 
7304 	scsi_u64to8b(lun->be_lun->maxlba, data->addr);
7305 	/* XXX KDM this may not be 512 bytes... */
7306 	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7307 	data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
7308 	scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
7309 	if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
7310 		data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
7311 
7312 	ctsio->scsi_status = SCSI_STATUS_OK;
7313 
7314 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7315 	ctsio->be_move_done = ctl_config_move_done;
7316 	ctl_datamove((union ctl_io *)ctsio);
7317 
7318 	return (CTL_RETVAL_COMPLETE);
7319 }
7320 
7321 int
7322 ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7323 {
7324 	struct scsi_maintenance_in *cdb;
7325 	int retval;
7326 	int alloc_len, ext, total_len = 0, g, p, pc, pg;
7327 	int num_target_port_groups, num_target_ports, single;
7328 	struct ctl_lun *lun;
7329 	struct ctl_softc *softc;
7330 	struct ctl_port *port;
7331 	struct scsi_target_group_data *rtg_ptr;
7332 	struct scsi_target_group_data_extended *rtg_ext_ptr;
7333 	struct scsi_target_port_group_descriptor *tpg_desc;
7334 
7335 	CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7336 
7337 	cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7338 	softc = control_softc;
7339 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7340 
7341 	retval = CTL_RETVAL_COMPLETE;
7342 
7343 	switch (cdb->byte2 & STG_PDF_MASK) {
7344 	case STG_PDF_LENGTH:
7345 		ext = 0;
7346 		break;
7347 	case STG_PDF_EXTENDED:
7348 		ext = 1;
7349 		break;
7350 	default:
7351 		ctl_set_invalid_field(/*ctsio*/ ctsio,
7352 				      /*sks_valid*/ 1,
7353 				      /*command*/ 1,
7354 				      /*field*/ 2,
7355 				      /*bit_valid*/ 1,
7356 				      /*bit*/ 5);
7357 		ctl_done((union ctl_io *)ctsio);
7358 		return(retval);
7359 	}
7360 
7361 	single = ctl_is_single;
7362 	if (single)
7363 		num_target_port_groups = 1;
7364 	else
7365 		num_target_port_groups = NUM_TARGET_PORT_GROUPS;
7366 	num_target_ports = 0;
7367 	mtx_lock(&softc->ctl_lock);
7368 	STAILQ_FOREACH(port, &softc->port_list, links) {
7369 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7370 			continue;
7371 		if (ctl_map_lun_back(port->targ_port, lun->lun) >= CTL_MAX_LUNS)
7372 			continue;
7373 		num_target_ports++;
7374 	}
7375 	mtx_unlock(&softc->ctl_lock);
7376 
7377 	if (ext)
7378 		total_len = sizeof(struct scsi_target_group_data_extended);
7379 	else
7380 		total_len = sizeof(struct scsi_target_group_data);
7381 	total_len += sizeof(struct scsi_target_port_group_descriptor) *
7382 		num_target_port_groups +
7383 	    sizeof(struct scsi_target_port_descriptor) *
7384 		num_target_ports * num_target_port_groups;
7385 
7386 	alloc_len = scsi_4btoul(cdb->length);
7387 
7388 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7389 
7390 	ctsio->kern_sg_entries = 0;
7391 
7392 	if (total_len < alloc_len) {
7393 		ctsio->residual = alloc_len - total_len;
7394 		ctsio->kern_data_len = total_len;
7395 		ctsio->kern_total_len = total_len;
7396 	} else {
7397 		ctsio->residual = 0;
7398 		ctsio->kern_data_len = alloc_len;
7399 		ctsio->kern_total_len = alloc_len;
7400 	}
7401 	ctsio->kern_data_resid = 0;
7402 	ctsio->kern_rel_offset = 0;
7403 
7404 	if (ext) {
7405 		rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7406 		    ctsio->kern_data_ptr;
7407 		scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7408 		rtg_ext_ptr->format_type = 0x10;
7409 		rtg_ext_ptr->implicit_transition_time = 0;
7410 		tpg_desc = &rtg_ext_ptr->groups[0];
7411 	} else {
7412 		rtg_ptr = (struct scsi_target_group_data *)
7413 		    ctsio->kern_data_ptr;
7414 		scsi_ulto4b(total_len - 4, rtg_ptr->length);
7415 		tpg_desc = &rtg_ptr->groups[0];
7416 	}
7417 
7418 	pg = ctsio->io_hdr.nexus.targ_port / CTL_MAX_PORTS;
7419 	mtx_lock(&softc->ctl_lock);
7420 	for (g = 0; g < num_target_port_groups; g++) {
7421 		if (g == pg)
7422 			tpg_desc->pref_state = TPG_PRIMARY |
7423 			    TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7424 		else
7425 			tpg_desc->pref_state =
7426 			    TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7427 		tpg_desc->support = TPG_AO_SUP;
7428 		if (!single)
7429 			tpg_desc->support |= TPG_AN_SUP;
7430 		scsi_ulto2b(g + 1, tpg_desc->target_port_group);
7431 		tpg_desc->status = TPG_IMPLICIT;
7432 		pc = 0;
7433 		STAILQ_FOREACH(port, &softc->port_list, links) {
7434 			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7435 				continue;
7436 			if (ctl_map_lun_back(port->targ_port, lun->lun) >=
7437 			    CTL_MAX_LUNS)
7438 				continue;
7439 			p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
7440 			scsi_ulto2b(p, tpg_desc->descriptors[pc].
7441 			    relative_target_port_identifier);
7442 			pc++;
7443 		}
7444 		tpg_desc->target_port_count = pc;
7445 		tpg_desc = (struct scsi_target_port_group_descriptor *)
7446 		    &tpg_desc->descriptors[pc];
7447 	}
7448 	mtx_unlock(&softc->ctl_lock);
7449 
7450 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7451 	ctsio->be_move_done = ctl_config_move_done;
7452 
7453 	CTL_DEBUG_PRINT(("buf = %x %x %x %x %x %x %x %x\n",
7454 			 ctsio->kern_data_ptr[0], ctsio->kern_data_ptr[1],
7455 			 ctsio->kern_data_ptr[2], ctsio->kern_data_ptr[3],
7456 			 ctsio->kern_data_ptr[4], ctsio->kern_data_ptr[5],
7457 			 ctsio->kern_data_ptr[6], ctsio->kern_data_ptr[7]));
7458 
7459 	ctl_datamove((union ctl_io *)ctsio);
7460 	return(retval);
7461 }
7462 
7463 int
7464 ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7465 {
7466 	struct ctl_lun *lun;
7467 	struct scsi_report_supported_opcodes *cdb;
7468 	const struct ctl_cmd_entry *entry, *sentry;
7469 	struct scsi_report_supported_opcodes_all *all;
7470 	struct scsi_report_supported_opcodes_descr *descr;
7471 	struct scsi_report_supported_opcodes_one *one;
7472 	int retval;
7473 	int alloc_len, total_len;
7474 	int opcode, service_action, i, j, num;
7475 
7476 	CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7477 
7478 	cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7479 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7480 
7481 	retval = CTL_RETVAL_COMPLETE;
7482 
7483 	opcode = cdb->requested_opcode;
7484 	service_action = scsi_2btoul(cdb->requested_service_action);
7485 	switch (cdb->options & RSO_OPTIONS_MASK) {
7486 	case RSO_OPTIONS_ALL:
7487 		num = 0;
7488 		for (i = 0; i < 256; i++) {
7489 			entry = &ctl_cmd_table[i];
7490 			if (entry->flags & CTL_CMD_FLAG_SA5) {
7491 				for (j = 0; j < 32; j++) {
7492 					sentry = &((const struct ctl_cmd_entry *)
7493 					    entry->execute)[j];
7494 					if (ctl_cmd_applicable(
7495 					    lun->be_lun->lun_type, sentry))
7496 						num++;
7497 				}
7498 			} else {
7499 				if (ctl_cmd_applicable(lun->be_lun->lun_type,
7500 				    entry))
7501 					num++;
7502 			}
7503 		}
7504 		total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7505 		    num * sizeof(struct scsi_report_supported_opcodes_descr);
7506 		break;
7507 	case RSO_OPTIONS_OC:
7508 		if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7509 			ctl_set_invalid_field(/*ctsio*/ ctsio,
7510 					      /*sks_valid*/ 1,
7511 					      /*command*/ 1,
7512 					      /*field*/ 2,
7513 					      /*bit_valid*/ 1,
7514 					      /*bit*/ 2);
7515 			ctl_done((union ctl_io *)ctsio);
7516 			return (CTL_RETVAL_COMPLETE);
7517 		}
7518 		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7519 		break;
7520 	case RSO_OPTIONS_OC_SA:
7521 		if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7522 		    service_action >= 32) {
7523 			ctl_set_invalid_field(/*ctsio*/ ctsio,
7524 					      /*sks_valid*/ 1,
7525 					      /*command*/ 1,
7526 					      /*field*/ 2,
7527 					      /*bit_valid*/ 1,
7528 					      /*bit*/ 2);
7529 			ctl_done((union ctl_io *)ctsio);
7530 			return (CTL_RETVAL_COMPLETE);
7531 		}
7532 		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7533 		break;
7534 	default:
7535 		ctl_set_invalid_field(/*ctsio*/ ctsio,
7536 				      /*sks_valid*/ 1,
7537 				      /*command*/ 1,
7538 				      /*field*/ 2,
7539 				      /*bit_valid*/ 1,
7540 				      /*bit*/ 2);
7541 		ctl_done((union ctl_io *)ctsio);
7542 		return (CTL_RETVAL_COMPLETE);
7543 	}
7544 
7545 	alloc_len = scsi_4btoul(cdb->length);
7546 
7547 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7548 
7549 	ctsio->kern_sg_entries = 0;
7550 
7551 	if (total_len < alloc_len) {
7552 		ctsio->residual = alloc_len - total_len;
7553 		ctsio->kern_data_len = total_len;
7554 		ctsio->kern_total_len = total_len;
7555 	} else {
7556 		ctsio->residual = 0;
7557 		ctsio->kern_data_len = alloc_len;
7558 		ctsio->kern_total_len = alloc_len;
7559 	}
7560 	ctsio->kern_data_resid = 0;
7561 	ctsio->kern_rel_offset = 0;
7562 
7563 	switch (cdb->options & RSO_OPTIONS_MASK) {
7564 	case RSO_OPTIONS_ALL:
7565 		all = (struct scsi_report_supported_opcodes_all *)
7566 		    ctsio->kern_data_ptr;
7567 		num = 0;
7568 		for (i = 0; i < 256; i++) {
7569 			entry = &ctl_cmd_table[i];
7570 			if (entry->flags & CTL_CMD_FLAG_SA5) {
7571 				for (j = 0; j < 32; j++) {
7572 					sentry = &((const struct ctl_cmd_entry *)
7573 					    entry->execute)[j];
7574 					if (!ctl_cmd_applicable(
7575 					    lun->be_lun->lun_type, sentry))
7576 						continue;
7577 					descr = &all->descr[num++];
7578 					descr->opcode = i;
7579 					scsi_ulto2b(j, descr->service_action);
7580 					descr->flags = RSO_SERVACTV;
7581 					scsi_ulto2b(sentry->length,
7582 					    descr->cdb_length);
7583 				}
7584 			} else {
7585 				if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7586 				    entry))
7587 					continue;
7588 				descr = &all->descr[num++];
7589 				descr->opcode = i;
7590 				scsi_ulto2b(0, descr->service_action);
7591 				descr->flags = 0;
7592 				scsi_ulto2b(entry->length, descr->cdb_length);
7593 			}
7594 		}
7595 		scsi_ulto4b(
7596 		    num * sizeof(struct scsi_report_supported_opcodes_descr),
7597 		    all->length);
7598 		break;
7599 	case RSO_OPTIONS_OC:
7600 		one = (struct scsi_report_supported_opcodes_one *)
7601 		    ctsio->kern_data_ptr;
7602 		entry = &ctl_cmd_table[opcode];
7603 		goto fill_one;
7604 	case RSO_OPTIONS_OC_SA:
7605 		one = (struct scsi_report_supported_opcodes_one *)
7606 		    ctsio->kern_data_ptr;
7607 		entry = &ctl_cmd_table[opcode];
7608 		entry = &((const struct ctl_cmd_entry *)
7609 		    entry->execute)[service_action];
7610 fill_one:
7611 		if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7612 			one->support = 3;
7613 			scsi_ulto2b(entry->length, one->cdb_length);
7614 			one->cdb_usage[0] = opcode;
7615 			memcpy(&one->cdb_usage[1], entry->usage,
7616 			    entry->length - 1);
7617 		} else
7618 			one->support = 1;
7619 		break;
7620 	}
7621 
7622 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7623 	ctsio->be_move_done = ctl_config_move_done;
7624 
7625 	ctl_datamove((union ctl_io *)ctsio);
7626 	return(retval);
7627 }
7628 
7629 int
7630 ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7631 {
7632 	struct ctl_lun *lun;
7633 	struct scsi_report_supported_tmf *cdb;
7634 	struct scsi_report_supported_tmf_data *data;
7635 	int retval;
7636 	int alloc_len, total_len;
7637 
7638 	CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7639 
7640 	cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7641 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7642 
7643 	retval = CTL_RETVAL_COMPLETE;
7644 
7645 	total_len = sizeof(struct scsi_report_supported_tmf_data);
7646 	alloc_len = scsi_4btoul(cdb->length);
7647 
7648 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7649 
7650 	ctsio->kern_sg_entries = 0;
7651 
7652 	if (total_len < alloc_len) {
7653 		ctsio->residual = alloc_len - total_len;
7654 		ctsio->kern_data_len = total_len;
7655 		ctsio->kern_total_len = total_len;
7656 	} else {
7657 		ctsio->residual = 0;
7658 		ctsio->kern_data_len = alloc_len;
7659 		ctsio->kern_total_len = alloc_len;
7660 	}
7661 	ctsio->kern_data_resid = 0;
7662 	ctsio->kern_rel_offset = 0;
7663 
7664 	data = (struct scsi_report_supported_tmf_data *)ctsio->kern_data_ptr;
7665 	data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_TRS;
7666 	data->byte2 |= RST_ITNRS;
7667 
7668 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7669 	ctsio->be_move_done = ctl_config_move_done;
7670 
7671 	ctl_datamove((union ctl_io *)ctsio);
7672 	return (retval);
7673 }
7674 
7675 int
7676 ctl_report_timestamp(struct ctl_scsiio *ctsio)
7677 {
7678 	struct ctl_lun *lun;
7679 	struct scsi_report_timestamp *cdb;
7680 	struct scsi_report_timestamp_data *data;
7681 	struct timeval tv;
7682 	int64_t timestamp;
7683 	int retval;
7684 	int alloc_len, total_len;
7685 
7686 	CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7687 
7688 	cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7689 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7690 
7691 	retval = CTL_RETVAL_COMPLETE;
7692 
7693 	total_len = sizeof(struct scsi_report_timestamp_data);
7694 	alloc_len = scsi_4btoul(cdb->length);
7695 
7696 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7697 
7698 	ctsio->kern_sg_entries = 0;
7699 
7700 	if (total_len < alloc_len) {
7701 		ctsio->residual = alloc_len - total_len;
7702 		ctsio->kern_data_len = total_len;
7703 		ctsio->kern_total_len = total_len;
7704 	} else {
7705 		ctsio->residual = 0;
7706 		ctsio->kern_data_len = alloc_len;
7707 		ctsio->kern_total_len = alloc_len;
7708 	}
7709 	ctsio->kern_data_resid = 0;
7710 	ctsio->kern_rel_offset = 0;
7711 
7712 	data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7713 	scsi_ulto2b(sizeof(*data) - 2, data->length);
7714 	data->origin = RTS_ORIG_OUTSIDE;
7715 	getmicrotime(&tv);
7716 	timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7717 	scsi_ulto4b(timestamp >> 16, data->timestamp);
7718 	scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7719 
7720 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7721 	ctsio->be_move_done = ctl_config_move_done;
7722 
7723 	ctl_datamove((union ctl_io *)ctsio);
7724 	return (retval);
7725 }
7726 
7727 int
7728 ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7729 {
7730 	struct scsi_per_res_in *cdb;
7731 	int alloc_len, total_len = 0;
7732 	/* struct scsi_per_res_in_rsrv in_data; */
7733 	struct ctl_lun *lun;
7734 	struct ctl_softc *softc;
7735 
7736 	CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7737 
7738 	softc = control_softc;
7739 
7740 	cdb = (struct scsi_per_res_in *)ctsio->cdb;
7741 
7742 	alloc_len = scsi_2btoul(cdb->length);
7743 
7744 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7745 
7746 retry:
7747 	mtx_lock(&lun->lun_lock);
7748 	switch (cdb->action) {
7749 	case SPRI_RK: /* read keys */
7750 		total_len = sizeof(struct scsi_per_res_in_keys) +
7751 			lun->pr_key_count *
7752 			sizeof(struct scsi_per_res_key);
7753 		break;
7754 	case SPRI_RR: /* read reservation */
7755 		if (lun->flags & CTL_LUN_PR_RESERVED)
7756 			total_len = sizeof(struct scsi_per_res_in_rsrv);
7757 		else
7758 			total_len = sizeof(struct scsi_per_res_in_header);
7759 		break;
7760 	case SPRI_RC: /* report capabilities */
7761 		total_len = sizeof(struct scsi_per_res_cap);
7762 		break;
7763 	case SPRI_RS: /* read full status */
7764 		total_len = sizeof(struct scsi_per_res_in_header) +
7765 		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7766 		    lun->pr_key_count;
7767 		break;
7768 	default:
7769 		panic("Invalid PR type %x", cdb->action);
7770 	}
7771 	mtx_unlock(&lun->lun_lock);
7772 
7773 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7774 
7775 	if (total_len < alloc_len) {
7776 		ctsio->residual = alloc_len - total_len;
7777 		ctsio->kern_data_len = total_len;
7778 		ctsio->kern_total_len = total_len;
7779 	} else {
7780 		ctsio->residual = 0;
7781 		ctsio->kern_data_len = alloc_len;
7782 		ctsio->kern_total_len = alloc_len;
7783 	}
7784 
7785 	ctsio->kern_data_resid = 0;
7786 	ctsio->kern_rel_offset = 0;
7787 	ctsio->kern_sg_entries = 0;
7788 
7789 	mtx_lock(&lun->lun_lock);
7790 	switch (cdb->action) {
7791 	case SPRI_RK: { // read keys
7792         struct scsi_per_res_in_keys *res_keys;
7793 		int i, key_count;
7794 
7795 		res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7796 
7797 		/*
7798 		 * We had to drop the lock to allocate our buffer, which
7799 		 * leaves time for someone to come in with another
7800 		 * persistent reservation.  (That is unlikely, though,
7801 		 * since this should be the only persistent reservation
7802 		 * command active right now.)
7803 		 */
7804 		if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7805 		    (lun->pr_key_count *
7806 		     sizeof(struct scsi_per_res_key)))){
7807 			mtx_unlock(&lun->lun_lock);
7808 			free(ctsio->kern_data_ptr, M_CTL);
7809 			printf("%s: reservation length changed, retrying\n",
7810 			       __func__);
7811 			goto retry;
7812 		}
7813 
7814 		scsi_ulto4b(lun->PRGeneration, res_keys->header.generation);
7815 
7816 		scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7817 			     lun->pr_key_count, res_keys->header.length);
7818 
7819 		for (i = 0, key_count = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7820 			if (!lun->per_res[i].registered)
7821 				continue;
7822 
7823 			/*
7824 			 * We used lun->pr_key_count to calculate the
7825 			 * size to allocate.  If it turns out the number of
7826 			 * initiators with the registered flag set is
7827 			 * larger than that (i.e. they haven't been kept in
7828 			 * sync), we've got a problem.
7829 			 */
7830 			if (key_count >= lun->pr_key_count) {
7831 #ifdef NEEDTOPORT
7832 				csevent_log(CSC_CTL | CSC_SHELF_SW |
7833 					    CTL_PR_ERROR,
7834 					    csevent_LogType_Fault,
7835 					    csevent_AlertLevel_Yellow,
7836 					    csevent_FRU_ShelfController,
7837 					    csevent_FRU_Firmware,
7838 				        csevent_FRU_Unknown,
7839 					    "registered keys %d >= key "
7840 					    "count %d", key_count,
7841 					    lun->pr_key_count);
7842 #endif
7843 				key_count++;
7844 				continue;
7845 			}
7846 			memcpy(res_keys->keys[key_count].key,
7847 			       lun->per_res[i].res_key.key,
7848 			       ctl_min(sizeof(res_keys->keys[key_count].key),
7849 			       sizeof(lun->per_res[i].res_key)));
7850 			key_count++;
7851 		}
7852 		break;
7853 	}
7854 	case SPRI_RR: { // read reservation
7855 		struct scsi_per_res_in_rsrv *res;
7856 		int tmp_len, header_only;
7857 
7858 		res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7859 
7860 		scsi_ulto4b(lun->PRGeneration, res->header.generation);
7861 
7862 		if (lun->flags & CTL_LUN_PR_RESERVED)
7863 		{
7864 			tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7865 			scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7866 				    res->header.length);
7867 			header_only = 0;
7868 		} else {
7869 			tmp_len = sizeof(struct scsi_per_res_in_header);
7870 			scsi_ulto4b(0, res->header.length);
7871 			header_only = 1;
7872 		}
7873 
7874 		/*
7875 		 * We had to drop the lock to allocate our buffer, which
7876 		 * leaves time for someone to come in with another
7877 		 * persistent reservation.  (That is unlikely, though,
7878 		 * since this should be the only persistent reservation
7879 		 * command active right now.)
7880 		 */
7881 		if (tmp_len != total_len) {
7882 			mtx_unlock(&lun->lun_lock);
7883 			free(ctsio->kern_data_ptr, M_CTL);
7884 			printf("%s: reservation status changed, retrying\n",
7885 			       __func__);
7886 			goto retry;
7887 		}
7888 
7889 		/*
7890 		 * No reservation held, so we're done.
7891 		 */
7892 		if (header_only != 0)
7893 			break;
7894 
7895 		/*
7896 		 * If the registration is an All Registrants type, the key
7897 		 * is 0, since it doesn't really matter.
7898 		 */
7899 		if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7900 			memcpy(res->data.reservation,
7901 			       &lun->per_res[lun->pr_res_idx].res_key,
7902 			       sizeof(struct scsi_per_res_key));
7903 		}
7904 		res->data.scopetype = lun->res_type;
7905 		break;
7906 	}
7907 	case SPRI_RC:     //report capabilities
7908 	{
7909 		struct scsi_per_res_cap *res_cap;
7910 		uint16_t type_mask;
7911 
7912 		res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7913 		scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7914 		res_cap->flags2 |= SPRI_TMV | SPRI_ALLOW_3;
7915 		type_mask = SPRI_TM_WR_EX_AR |
7916 			    SPRI_TM_EX_AC_RO |
7917 			    SPRI_TM_WR_EX_RO |
7918 			    SPRI_TM_EX_AC |
7919 			    SPRI_TM_WR_EX |
7920 			    SPRI_TM_EX_AC_AR;
7921 		scsi_ulto2b(type_mask, res_cap->type_mask);
7922 		break;
7923 	}
7924 	case SPRI_RS: { // read full status
7925 		struct scsi_per_res_in_full *res_status;
7926 		struct scsi_per_res_in_full_desc *res_desc;
7927 		struct ctl_port *port;
7928 		int i, len;
7929 
7930 		res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7931 
7932 		/*
7933 		 * We had to drop the lock to allocate our buffer, which
7934 		 * leaves time for someone to come in with another
7935 		 * persistent reservation.  (That is unlikely, though,
7936 		 * since this should be the only persistent reservation
7937 		 * command active right now.)
7938 		 */
7939 		if (total_len < (sizeof(struct scsi_per_res_in_header) +
7940 		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7941 		     lun->pr_key_count)){
7942 			mtx_unlock(&lun->lun_lock);
7943 			free(ctsio->kern_data_ptr, M_CTL);
7944 			printf("%s: reservation length changed, retrying\n",
7945 			       __func__);
7946 			goto retry;
7947 		}
7948 
7949 		scsi_ulto4b(lun->PRGeneration, res_status->header.generation);
7950 
7951 		res_desc = &res_status->desc[0];
7952 		for (i = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7953 			if (!lun->per_res[i].registered)
7954 				continue;
7955 
7956 			memcpy(&res_desc->res_key, &lun->per_res[i].res_key.key,
7957 			    sizeof(res_desc->res_key));
7958 			if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7959 			    (lun->pr_res_idx == i ||
7960 			     lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7961 				res_desc->flags = SPRI_FULL_R_HOLDER;
7962 				res_desc->scopetype = lun->res_type;
7963 			}
7964 			scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7965 			    res_desc->rel_trgt_port_id);
7966 			len = 0;
7967 			port = softc->ctl_ports[
7968 			    ctl_port_idx(i / CTL_MAX_INIT_PER_PORT)];
7969 			if (port != NULL)
7970 				len = ctl_create_iid(port,
7971 				    i % CTL_MAX_INIT_PER_PORT,
7972 				    res_desc->transport_id);
7973 			scsi_ulto4b(len, res_desc->additional_length);
7974 			res_desc = (struct scsi_per_res_in_full_desc *)
7975 			    &res_desc->transport_id[len];
7976 		}
7977 		scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7978 		    res_status->header.length);
7979 		break;
7980 	}
7981 	default:
7982 		/*
7983 		 * This is a bug, because we just checked for this above,
7984 		 * and should have returned an error.
7985 		 */
7986 		panic("Invalid PR type %x", cdb->action);
7987 		break; /* NOTREACHED */
7988 	}
7989 	mtx_unlock(&lun->lun_lock);
7990 
7991 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7992 	ctsio->be_move_done = ctl_config_move_done;
7993 
7994 	CTL_DEBUG_PRINT(("buf = %x %x %x %x %x %x %x %x\n",
7995 			 ctsio->kern_data_ptr[0], ctsio->kern_data_ptr[1],
7996 			 ctsio->kern_data_ptr[2], ctsio->kern_data_ptr[3],
7997 			 ctsio->kern_data_ptr[4], ctsio->kern_data_ptr[5],
7998 			 ctsio->kern_data_ptr[6], ctsio->kern_data_ptr[7]));
7999 
8000 	ctl_datamove((union ctl_io *)ctsio);
8001 
8002 	return (CTL_RETVAL_COMPLETE);
8003 }
8004 
8005 /*
8006  * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
8007  * it should return.
8008  */
8009 static int
8010 ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
8011 		uint64_t sa_res_key, uint8_t type, uint32_t residx,
8012 		struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
8013 		struct scsi_per_res_out_parms* param)
8014 {
8015 	union ctl_ha_msg persis_io;
8016 	int retval, i;
8017 	int isc_retval;
8018 
8019 	retval = 0;
8020 
8021 	mtx_lock(&lun->lun_lock);
8022 	if (sa_res_key == 0) {
8023 		if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8024 			/* validate scope and type */
8025 			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8026 			     SPR_LU_SCOPE) {
8027 				mtx_unlock(&lun->lun_lock);
8028 				ctl_set_invalid_field(/*ctsio*/ ctsio,
8029 						      /*sks_valid*/ 1,
8030 						      /*command*/ 1,
8031 						      /*field*/ 2,
8032 						      /*bit_valid*/ 1,
8033 						      /*bit*/ 4);
8034 				ctl_done((union ctl_io *)ctsio);
8035 				return (1);
8036 			}
8037 
8038 		        if (type>8 || type==2 || type==4 || type==0) {
8039 				mtx_unlock(&lun->lun_lock);
8040 				ctl_set_invalid_field(/*ctsio*/ ctsio,
8041        	           				      /*sks_valid*/ 1,
8042 						      /*command*/ 1,
8043 						      /*field*/ 2,
8044 						      /*bit_valid*/ 1,
8045 						      /*bit*/ 0);
8046 				ctl_done((union ctl_io *)ctsio);
8047 				return (1);
8048 		        }
8049 
8050 			/* temporarily unregister this nexus */
8051 			lun->per_res[residx].registered = 0;
8052 
8053 			/*
8054 			 * Unregister everybody else and build UA for
8055 			 * them
8056 			 */
8057 			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8058 				if (lun->per_res[i].registered == 0)
8059 					continue;
8060 
8061 				if (!persis_offset
8062 				 && i <CTL_MAX_INITIATORS)
8063 					lun->pending_ua[i] |=
8064 						CTL_UA_REG_PREEMPT;
8065 				else if (persis_offset
8066 				      && i >= persis_offset)
8067 					lun->pending_ua[i-persis_offset] |=
8068 						CTL_UA_REG_PREEMPT;
8069 				lun->per_res[i].registered = 0;
8070 				memset(&lun->per_res[i].res_key, 0,
8071 				       sizeof(struct scsi_per_res_key));
8072 			}
8073 			lun->per_res[residx].registered = 1;
8074 			lun->pr_key_count = 1;
8075 			lun->res_type = type;
8076 			if (lun->res_type != SPR_TYPE_WR_EX_AR
8077 			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8078 				lun->pr_res_idx = residx;
8079 
8080 			/* send msg to other side */
8081 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8082 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8083 			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8084 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8085 			persis_io.pr.pr_info.res_type = type;
8086 			memcpy(persis_io.pr.pr_info.sa_res_key,
8087 			       param->serv_act_res_key,
8088 			       sizeof(param->serv_act_res_key));
8089 			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8090 			     &persis_io, sizeof(persis_io), 0)) >
8091 			     CTL_HA_STATUS_SUCCESS) {
8092 				printf("CTL:Persis Out error returned "
8093 				       "from ctl_ha_msg_send %d\n",
8094 				       isc_retval);
8095 			}
8096 		} else {
8097 			/* not all registrants */
8098 			mtx_unlock(&lun->lun_lock);
8099 			free(ctsio->kern_data_ptr, M_CTL);
8100 			ctl_set_invalid_field(ctsio,
8101 					      /*sks_valid*/ 1,
8102 					      /*command*/ 0,
8103 					      /*field*/ 8,
8104 					      /*bit_valid*/ 0,
8105 					      /*bit*/ 0);
8106 			ctl_done((union ctl_io *)ctsio);
8107 			return (1);
8108 		}
8109 	} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8110 		|| !(lun->flags & CTL_LUN_PR_RESERVED)) {
8111 		int found = 0;
8112 
8113 		if (res_key == sa_res_key) {
8114 			/* special case */
8115 			/*
8116 			 * The spec implies this is not good but doesn't
8117 			 * say what to do. There are two choices either
8118 			 * generate a res conflict or check condition
8119 			 * with illegal field in parameter data. Since
8120 			 * that is what is done when the sa_res_key is
8121 			 * zero I'll take that approach since this has
8122 			 * to do with the sa_res_key.
8123 			 */
8124 			mtx_unlock(&lun->lun_lock);
8125 			free(ctsio->kern_data_ptr, M_CTL);
8126 			ctl_set_invalid_field(ctsio,
8127 					      /*sks_valid*/ 1,
8128 					      /*command*/ 0,
8129 					      /*field*/ 8,
8130 					      /*bit_valid*/ 0,
8131 					      /*bit*/ 0);
8132 			ctl_done((union ctl_io *)ctsio);
8133 			return (1);
8134 		}
8135 
8136 		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8137 			if (lun->per_res[i].registered
8138 			 && memcmp(param->serv_act_res_key,
8139 			    lun->per_res[i].res_key.key,
8140 			    sizeof(struct scsi_per_res_key)) != 0)
8141 				continue;
8142 
8143 			found = 1;
8144 			lun->per_res[i].registered = 0;
8145 			memset(&lun->per_res[i].res_key, 0,
8146 			       sizeof(struct scsi_per_res_key));
8147 			lun->pr_key_count--;
8148 
8149 			if (!persis_offset && i < CTL_MAX_INITIATORS)
8150 				lun->pending_ua[i] |= CTL_UA_REG_PREEMPT;
8151 			else if (persis_offset && i >= persis_offset)
8152 				lun->pending_ua[i-persis_offset] |=
8153 					CTL_UA_REG_PREEMPT;
8154 		}
8155 		if (!found) {
8156 			mtx_unlock(&lun->lun_lock);
8157 			free(ctsio->kern_data_ptr, M_CTL);
8158 			ctl_set_reservation_conflict(ctsio);
8159 			ctl_done((union ctl_io *)ctsio);
8160 			return (CTL_RETVAL_COMPLETE);
8161 		}
8162 		/* send msg to other side */
8163 		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8164 		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8165 		persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8166 		persis_io.pr.pr_info.residx = lun->pr_res_idx;
8167 		persis_io.pr.pr_info.res_type = type;
8168 		memcpy(persis_io.pr.pr_info.sa_res_key,
8169 		       param->serv_act_res_key,
8170 		       sizeof(param->serv_act_res_key));
8171 		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8172 		     &persis_io, sizeof(persis_io), 0)) >
8173 		     CTL_HA_STATUS_SUCCESS) {
8174 			printf("CTL:Persis Out error returned from "
8175 			       "ctl_ha_msg_send %d\n", isc_retval);
8176 		}
8177 	} else {
8178 		/* Reserved but not all registrants */
8179 		/* sa_res_key is res holder */
8180 		if (memcmp(param->serv_act_res_key,
8181                    lun->per_res[lun->pr_res_idx].res_key.key,
8182                    sizeof(struct scsi_per_res_key)) == 0) {
8183 			/* validate scope and type */
8184 			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8185 			     SPR_LU_SCOPE) {
8186 				mtx_unlock(&lun->lun_lock);
8187 				ctl_set_invalid_field(/*ctsio*/ ctsio,
8188 						      /*sks_valid*/ 1,
8189 						      /*command*/ 1,
8190 						      /*field*/ 2,
8191 						      /*bit_valid*/ 1,
8192 						      /*bit*/ 4);
8193 				ctl_done((union ctl_io *)ctsio);
8194 				return (1);
8195 			}
8196 
8197 			if (type>8 || type==2 || type==4 || type==0) {
8198 				mtx_unlock(&lun->lun_lock);
8199 				ctl_set_invalid_field(/*ctsio*/ ctsio,
8200 						      /*sks_valid*/ 1,
8201 						      /*command*/ 1,
8202 						      /*field*/ 2,
8203 						      /*bit_valid*/ 1,
8204 						      /*bit*/ 0);
8205 				ctl_done((union ctl_io *)ctsio);
8206 				return (1);
8207 			}
8208 
8209 			/*
8210 			 * Do the following:
8211 			 * if sa_res_key != res_key remove all
8212 			 * registrants w/sa_res_key and generate UA
8213 			 * for these registrants(Registrations
8214 			 * Preempted) if it wasn't an exclusive
8215 			 * reservation generate UA(Reservations
8216 			 * Preempted) for all other registered nexuses
8217 			 * if the type has changed. Establish the new
8218 			 * reservation and holder. If res_key and
8219 			 * sa_res_key are the same do the above
8220 			 * except don't unregister the res holder.
8221 			 */
8222 
8223 			/*
8224 			 * Temporarily unregister so it won't get
8225 			 * removed or UA generated
8226 			 */
8227 			lun->per_res[residx].registered = 0;
8228 			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8229 				if (lun->per_res[i].registered == 0)
8230 					continue;
8231 
8232 				if (memcmp(param->serv_act_res_key,
8233 				    lun->per_res[i].res_key.key,
8234 				    sizeof(struct scsi_per_res_key)) == 0) {
8235 					lun->per_res[i].registered = 0;
8236 					memset(&lun->per_res[i].res_key,
8237 					       0,
8238 					       sizeof(struct scsi_per_res_key));
8239 					lun->pr_key_count--;
8240 
8241 					if (!persis_offset
8242 					 && i < CTL_MAX_INITIATORS)
8243 						lun->pending_ua[i] |=
8244 							CTL_UA_REG_PREEMPT;
8245 					else if (persis_offset
8246 					      && i >= persis_offset)
8247 						lun->pending_ua[i-persis_offset] |=
8248 						  CTL_UA_REG_PREEMPT;
8249 				} else if (type != lun->res_type
8250 					&& (lun->res_type == SPR_TYPE_WR_EX_RO
8251 					 || lun->res_type ==SPR_TYPE_EX_AC_RO)){
8252 						if (!persis_offset
8253 						 && i < CTL_MAX_INITIATORS)
8254 							lun->pending_ua[i] |=
8255 							CTL_UA_RES_RELEASE;
8256 						else if (persis_offset
8257 						      && i >= persis_offset)
8258 							lun->pending_ua[
8259 							i-persis_offset] |=
8260 							CTL_UA_RES_RELEASE;
8261 				}
8262 			}
8263 			lun->per_res[residx].registered = 1;
8264 			lun->res_type = type;
8265 			if (lun->res_type != SPR_TYPE_WR_EX_AR
8266 			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8267 				lun->pr_res_idx = residx;
8268 			else
8269 				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8270 
8271 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8272 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8273 			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8274 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8275 			persis_io.pr.pr_info.res_type = type;
8276 			memcpy(persis_io.pr.pr_info.sa_res_key,
8277 			       param->serv_act_res_key,
8278 			       sizeof(param->serv_act_res_key));
8279 			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8280 			     &persis_io, sizeof(persis_io), 0)) >
8281 			     CTL_HA_STATUS_SUCCESS) {
8282 				printf("CTL:Persis Out error returned "
8283 				       "from ctl_ha_msg_send %d\n",
8284 				       isc_retval);
8285 			}
8286 		} else {
8287 			/*
8288 			 * sa_res_key is not the res holder just
8289 			 * remove registrants
8290 			 */
8291 			int found=0;
8292 
8293 			for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8294 				if (memcmp(param->serv_act_res_key,
8295 				    lun->per_res[i].res_key.key,
8296 				    sizeof(struct scsi_per_res_key)) != 0)
8297 					continue;
8298 
8299 				found = 1;
8300 				lun->per_res[i].registered = 0;
8301 				memset(&lun->per_res[i].res_key, 0,
8302 				       sizeof(struct scsi_per_res_key));
8303 				lun->pr_key_count--;
8304 
8305 				if (!persis_offset
8306 				 && i < CTL_MAX_INITIATORS)
8307 					lun->pending_ua[i] |=
8308 						CTL_UA_REG_PREEMPT;
8309 				else if (persis_offset
8310 				      && i >= persis_offset)
8311 					lun->pending_ua[i-persis_offset] |=
8312 						CTL_UA_REG_PREEMPT;
8313 			}
8314 
8315 			if (!found) {
8316 				mtx_unlock(&lun->lun_lock);
8317 				free(ctsio->kern_data_ptr, M_CTL);
8318 				ctl_set_reservation_conflict(ctsio);
8319 				ctl_done((union ctl_io *)ctsio);
8320 		        	return (1);
8321 			}
8322 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8323 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8324 			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8325 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8326 			persis_io.pr.pr_info.res_type = type;
8327 			memcpy(persis_io.pr.pr_info.sa_res_key,
8328 			       param->serv_act_res_key,
8329 			       sizeof(param->serv_act_res_key));
8330 			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8331 			     &persis_io, sizeof(persis_io), 0)) >
8332 			     CTL_HA_STATUS_SUCCESS) {
8333 				printf("CTL:Persis Out error returned "
8334 				       "from ctl_ha_msg_send %d\n",
8335 				isc_retval);
8336 			}
8337 		}
8338 	}
8339 
8340 	lun->PRGeneration++;
8341 	mtx_unlock(&lun->lun_lock);
8342 
8343 	return (retval);
8344 }
8345 
8346 static void
8347 ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8348 {
8349 	int i;
8350 
8351 	if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8352 	 || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8353 	 || memcmp(&lun->per_res[lun->pr_res_idx].res_key,
8354 		   msg->pr.pr_info.sa_res_key,
8355 		   sizeof(struct scsi_per_res_key)) != 0) {
8356 		uint64_t sa_res_key;
8357 		sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8358 
8359 		if (sa_res_key == 0) {
8360 			/* temporarily unregister this nexus */
8361 			lun->per_res[msg->pr.pr_info.residx].registered = 0;
8362 
8363 			/*
8364 			 * Unregister everybody else and build UA for
8365 			 * them
8366 			 */
8367 			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8368 				if (lun->per_res[i].registered == 0)
8369 					continue;
8370 
8371 				if (!persis_offset
8372 				 && i < CTL_MAX_INITIATORS)
8373 					lun->pending_ua[i] |=
8374 						CTL_UA_REG_PREEMPT;
8375 				else if (persis_offset && i >= persis_offset)
8376 					lun->pending_ua[i - persis_offset] |=
8377 						CTL_UA_REG_PREEMPT;
8378 				lun->per_res[i].registered = 0;
8379 				memset(&lun->per_res[i].res_key, 0,
8380 				       sizeof(struct scsi_per_res_key));
8381 			}
8382 
8383 			lun->per_res[msg->pr.pr_info.residx].registered = 1;
8384 			lun->pr_key_count = 1;
8385 			lun->res_type = msg->pr.pr_info.res_type;
8386 			if (lun->res_type != SPR_TYPE_WR_EX_AR
8387 			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8388 				lun->pr_res_idx = msg->pr.pr_info.residx;
8389 		} else {
8390 		        for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8391 				if (memcmp(msg->pr.pr_info.sa_res_key,
8392 		                   lun->per_res[i].res_key.key,
8393 		                   sizeof(struct scsi_per_res_key)) != 0)
8394 					continue;
8395 
8396 				lun->per_res[i].registered = 0;
8397 				memset(&lun->per_res[i].res_key, 0,
8398 				       sizeof(struct scsi_per_res_key));
8399 				lun->pr_key_count--;
8400 
8401 				if (!persis_offset
8402 				 && i < persis_offset)
8403 					lun->pending_ua[i] |=
8404 						CTL_UA_REG_PREEMPT;
8405 				else if (persis_offset
8406 				      && i >= persis_offset)
8407 					lun->pending_ua[i - persis_offset] |=
8408 						CTL_UA_REG_PREEMPT;
8409 			}
8410 		}
8411 	} else {
8412 		/*
8413 		 * Temporarily unregister so it won't get removed
8414 		 * or UA generated
8415 		 */
8416 		lun->per_res[msg->pr.pr_info.residx].registered = 0;
8417 		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8418 			if (lun->per_res[i].registered == 0)
8419 				continue;
8420 
8421 			if (memcmp(msg->pr.pr_info.sa_res_key,
8422 	                   lun->per_res[i].res_key.key,
8423 	                   sizeof(struct scsi_per_res_key)) == 0) {
8424 				lun->per_res[i].registered = 0;
8425 				memset(&lun->per_res[i].res_key, 0,
8426 				       sizeof(struct scsi_per_res_key));
8427 				lun->pr_key_count--;
8428 				if (!persis_offset
8429 				 && i < CTL_MAX_INITIATORS)
8430 					lun->pending_ua[i] |=
8431 						CTL_UA_REG_PREEMPT;
8432 				else if (persis_offset
8433 				      && i >= persis_offset)
8434 					lun->pending_ua[i - persis_offset] |=
8435 						CTL_UA_REG_PREEMPT;
8436 			} else if (msg->pr.pr_info.res_type != lun->res_type
8437 				&& (lun->res_type == SPR_TYPE_WR_EX_RO
8438 				 || lun->res_type == SPR_TYPE_EX_AC_RO)) {
8439 					if (!persis_offset
8440 					 && i < persis_offset)
8441 						lun->pending_ua[i] |=
8442 							CTL_UA_RES_RELEASE;
8443 					else if (persis_offset
8444 					      && i >= persis_offset)
8445 					lun->pending_ua[i - persis_offset] |=
8446 						CTL_UA_RES_RELEASE;
8447 			}
8448 		}
8449 		lun->per_res[msg->pr.pr_info.residx].registered = 1;
8450 		lun->res_type = msg->pr.pr_info.res_type;
8451 		if (lun->res_type != SPR_TYPE_WR_EX_AR
8452 		 && lun->res_type != SPR_TYPE_EX_AC_AR)
8453 			lun->pr_res_idx = msg->pr.pr_info.residx;
8454 		else
8455 			lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8456 	}
8457 	lun->PRGeneration++;
8458 
8459 }
8460 
8461 
8462 int
8463 ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8464 {
8465 	int retval;
8466 	int isc_retval;
8467 	u_int32_t param_len;
8468 	struct scsi_per_res_out *cdb;
8469 	struct ctl_lun *lun;
8470 	struct scsi_per_res_out_parms* param;
8471 	struct ctl_softc *softc;
8472 	uint32_t residx;
8473 	uint64_t res_key, sa_res_key;
8474 	uint8_t type;
8475 	union ctl_ha_msg persis_io;
8476 	int    i;
8477 
8478 	CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8479 
8480 	retval = CTL_RETVAL_COMPLETE;
8481 
8482 	softc = control_softc;
8483 
8484 	cdb = (struct scsi_per_res_out *)ctsio->cdb;
8485 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8486 
8487 	/*
8488 	 * We only support whole-LUN scope.  The scope & type are ignored for
8489 	 * register, register and ignore existing key and clear.
8490 	 * We sometimes ignore scope and type on preempts too!!
8491 	 * Verify reservation type here as well.
8492 	 */
8493 	type = cdb->scope_type & SPR_TYPE_MASK;
8494 	if ((cdb->action == SPRO_RESERVE)
8495 	 || (cdb->action == SPRO_RELEASE)) {
8496 		if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8497 			ctl_set_invalid_field(/*ctsio*/ ctsio,
8498 					      /*sks_valid*/ 1,
8499 					      /*command*/ 1,
8500 					      /*field*/ 2,
8501 					      /*bit_valid*/ 1,
8502 					      /*bit*/ 4);
8503 			ctl_done((union ctl_io *)ctsio);
8504 			return (CTL_RETVAL_COMPLETE);
8505 		}
8506 
8507 		if (type>8 || type==2 || type==4 || type==0) {
8508 			ctl_set_invalid_field(/*ctsio*/ ctsio,
8509 					      /*sks_valid*/ 1,
8510 					      /*command*/ 1,
8511 					      /*field*/ 2,
8512 					      /*bit_valid*/ 1,
8513 					      /*bit*/ 0);
8514 			ctl_done((union ctl_io *)ctsio);
8515 			return (CTL_RETVAL_COMPLETE);
8516 		}
8517 	}
8518 
8519 	param_len = scsi_4btoul(cdb->length);
8520 
8521 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8522 		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8523 		ctsio->kern_data_len = param_len;
8524 		ctsio->kern_total_len = param_len;
8525 		ctsio->kern_data_resid = 0;
8526 		ctsio->kern_rel_offset = 0;
8527 		ctsio->kern_sg_entries = 0;
8528 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8529 		ctsio->be_move_done = ctl_config_move_done;
8530 		ctl_datamove((union ctl_io *)ctsio);
8531 
8532 		return (CTL_RETVAL_COMPLETE);
8533 	}
8534 
8535 	param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8536 
8537 	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
8538 	res_key = scsi_8btou64(param->res_key.key);
8539 	sa_res_key = scsi_8btou64(param->serv_act_res_key);
8540 
8541 	/*
8542 	 * Validate the reservation key here except for SPRO_REG_IGNO
8543 	 * This must be done for all other service actions
8544 	 */
8545 	if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8546 		mtx_lock(&lun->lun_lock);
8547 		if (lun->per_res[residx].registered) {
8548 		    if (memcmp(param->res_key.key,
8549 			       lun->per_res[residx].res_key.key,
8550 			       ctl_min(sizeof(param->res_key),
8551 			       sizeof(lun->per_res[residx].res_key))) != 0) {
8552 				/*
8553 				 * The current key passed in doesn't match
8554 				 * the one the initiator previously
8555 				 * registered.
8556 				 */
8557 				mtx_unlock(&lun->lun_lock);
8558 				free(ctsio->kern_data_ptr, M_CTL);
8559 				ctl_set_reservation_conflict(ctsio);
8560 				ctl_done((union ctl_io *)ctsio);
8561 				return (CTL_RETVAL_COMPLETE);
8562 			}
8563 		} else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8564 			/*
8565 			 * We are not registered
8566 			 */
8567 			mtx_unlock(&lun->lun_lock);
8568 			free(ctsio->kern_data_ptr, M_CTL);
8569 			ctl_set_reservation_conflict(ctsio);
8570 			ctl_done((union ctl_io *)ctsio);
8571 			return (CTL_RETVAL_COMPLETE);
8572 		} else if (res_key != 0) {
8573 			/*
8574 			 * We are not registered and trying to register but
8575 			 * the register key isn't zero.
8576 			 */
8577 			mtx_unlock(&lun->lun_lock);
8578 			free(ctsio->kern_data_ptr, M_CTL);
8579 			ctl_set_reservation_conflict(ctsio);
8580 			ctl_done((union ctl_io *)ctsio);
8581 			return (CTL_RETVAL_COMPLETE);
8582 		}
8583 		mtx_unlock(&lun->lun_lock);
8584 	}
8585 
8586 	switch (cdb->action & SPRO_ACTION_MASK) {
8587 	case SPRO_REGISTER:
8588 	case SPRO_REG_IGNO: {
8589 
8590 #if 0
8591 		printf("Registration received\n");
8592 #endif
8593 
8594 		/*
8595 		 * We don't support any of these options, as we report in
8596 		 * the read capabilities request (see
8597 		 * ctl_persistent_reserve_in(), above).
8598 		 */
8599 		if ((param->flags & SPR_SPEC_I_PT)
8600 		 || (param->flags & SPR_ALL_TG_PT)
8601 		 || (param->flags & SPR_APTPL)) {
8602 			int bit_ptr;
8603 
8604 			if (param->flags & SPR_APTPL)
8605 				bit_ptr = 0;
8606 			else if (param->flags & SPR_ALL_TG_PT)
8607 				bit_ptr = 2;
8608 			else /* SPR_SPEC_I_PT */
8609 				bit_ptr = 3;
8610 
8611 			free(ctsio->kern_data_ptr, M_CTL);
8612 			ctl_set_invalid_field(ctsio,
8613 					      /*sks_valid*/ 1,
8614 					      /*command*/ 0,
8615 					      /*field*/ 20,
8616 					      /*bit_valid*/ 1,
8617 					      /*bit*/ bit_ptr);
8618 			ctl_done((union ctl_io *)ctsio);
8619 			return (CTL_RETVAL_COMPLETE);
8620 		}
8621 
8622 		mtx_lock(&lun->lun_lock);
8623 
8624 		/*
8625 		 * The initiator wants to clear the
8626 		 * key/unregister.
8627 		 */
8628 		if (sa_res_key == 0) {
8629 			if ((res_key == 0
8630 			  && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8631 			 || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8632 			  && !lun->per_res[residx].registered)) {
8633 				mtx_unlock(&lun->lun_lock);
8634 				goto done;
8635 			}
8636 
8637 			lun->per_res[residx].registered = 0;
8638 			memset(&lun->per_res[residx].res_key,
8639 			       0, sizeof(lun->per_res[residx].res_key));
8640 			lun->pr_key_count--;
8641 
8642 			if (residx == lun->pr_res_idx) {
8643 				lun->flags &= ~CTL_LUN_PR_RESERVED;
8644 				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8645 
8646 				if ((lun->res_type == SPR_TYPE_WR_EX_RO
8647 				  || lun->res_type == SPR_TYPE_EX_AC_RO)
8648 				 && lun->pr_key_count) {
8649 					/*
8650 					 * If the reservation is a registrants
8651 					 * only type we need to generate a UA
8652 					 * for other registered inits.  The
8653 					 * sense code should be RESERVATIONS
8654 					 * RELEASED
8655 					 */
8656 
8657 					for (i = 0; i < CTL_MAX_INITIATORS;i++){
8658 						if (lun->per_res[
8659 						    i+persis_offset].registered
8660 						    == 0)
8661 							continue;
8662 						lun->pending_ua[i] |=
8663 							CTL_UA_RES_RELEASE;
8664 					}
8665 				}
8666 				lun->res_type = 0;
8667 			} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8668 				if (lun->pr_key_count==0) {
8669 					lun->flags &= ~CTL_LUN_PR_RESERVED;
8670 					lun->res_type = 0;
8671 					lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8672 				}
8673 			}
8674 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8675 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8676 			persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8677 			persis_io.pr.pr_info.residx = residx;
8678 			if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8679 			     &persis_io, sizeof(persis_io), 0 )) >
8680 			     CTL_HA_STATUS_SUCCESS) {
8681 				printf("CTL:Persis Out error returned from "
8682 				       "ctl_ha_msg_send %d\n", isc_retval);
8683 			}
8684 		} else /* sa_res_key != 0 */ {
8685 
8686 			/*
8687 			 * If we aren't registered currently then increment
8688 			 * the key count and set the registered flag.
8689 			 */
8690 			if (!lun->per_res[residx].registered) {
8691 				lun->pr_key_count++;
8692 				lun->per_res[residx].registered = 1;
8693 			}
8694 
8695 			memcpy(&lun->per_res[residx].res_key,
8696 			       param->serv_act_res_key,
8697 			       ctl_min(sizeof(param->serv_act_res_key),
8698 			       sizeof(lun->per_res[residx].res_key)));
8699 
8700 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8701 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8702 			persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8703 			persis_io.pr.pr_info.residx = residx;
8704 			memcpy(persis_io.pr.pr_info.sa_res_key,
8705 			       param->serv_act_res_key,
8706 			       sizeof(param->serv_act_res_key));
8707 			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8708 			     &persis_io, sizeof(persis_io), 0)) >
8709 			     CTL_HA_STATUS_SUCCESS) {
8710 				printf("CTL:Persis Out error returned from "
8711 				       "ctl_ha_msg_send %d\n", isc_retval);
8712 			}
8713 		}
8714 		lun->PRGeneration++;
8715 		mtx_unlock(&lun->lun_lock);
8716 
8717 		break;
8718 	}
8719 	case SPRO_RESERVE:
8720 #if 0
8721                 printf("Reserve executed type %d\n", type);
8722 #endif
8723 		mtx_lock(&lun->lun_lock);
8724 		if (lun->flags & CTL_LUN_PR_RESERVED) {
8725 			/*
8726 			 * if this isn't the reservation holder and it's
8727 			 * not a "all registrants" type or if the type is
8728 			 * different then we have a conflict
8729 			 */
8730 			if ((lun->pr_res_idx != residx
8731 			  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8732 			 || lun->res_type != type) {
8733 				mtx_unlock(&lun->lun_lock);
8734 				free(ctsio->kern_data_ptr, M_CTL);
8735 				ctl_set_reservation_conflict(ctsio);
8736 				ctl_done((union ctl_io *)ctsio);
8737 				return (CTL_RETVAL_COMPLETE);
8738 			}
8739 			mtx_unlock(&lun->lun_lock);
8740 		} else /* create a reservation */ {
8741 			/*
8742 			 * If it's not an "all registrants" type record
8743 			 * reservation holder
8744 			 */
8745 			if (type != SPR_TYPE_WR_EX_AR
8746 			 && type != SPR_TYPE_EX_AC_AR)
8747 				lun->pr_res_idx = residx; /* Res holder */
8748 			else
8749 				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8750 
8751 			lun->flags |= CTL_LUN_PR_RESERVED;
8752 			lun->res_type = type;
8753 
8754 			mtx_unlock(&lun->lun_lock);
8755 
8756 			/* send msg to other side */
8757 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8758 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8759 			persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8760 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8761 			persis_io.pr.pr_info.res_type = type;
8762 			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8763 			     &persis_io, sizeof(persis_io), 0)) >
8764 			     CTL_HA_STATUS_SUCCESS) {
8765 				printf("CTL:Persis Out error returned from "
8766 				       "ctl_ha_msg_send %d\n", isc_retval);
8767 			}
8768 		}
8769 		break;
8770 
8771 	case SPRO_RELEASE:
8772 		mtx_lock(&lun->lun_lock);
8773 		if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8774 			/* No reservation exists return good status */
8775 			mtx_unlock(&lun->lun_lock);
8776 			goto done;
8777 		}
8778 		/*
8779 		 * Is this nexus a reservation holder?
8780 		 */
8781 		if (lun->pr_res_idx != residx
8782 		 && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8783 			/*
8784 			 * not a res holder return good status but
8785 			 * do nothing
8786 			 */
8787 			mtx_unlock(&lun->lun_lock);
8788 			goto done;
8789 		}
8790 
8791 		if (lun->res_type != type) {
8792 			mtx_unlock(&lun->lun_lock);
8793 			free(ctsio->kern_data_ptr, M_CTL);
8794 			ctl_set_illegal_pr_release(ctsio);
8795 			ctl_done((union ctl_io *)ctsio);
8796 			return (CTL_RETVAL_COMPLETE);
8797 		}
8798 
8799 		/* okay to release */
8800 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8801 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8802 		lun->res_type = 0;
8803 
8804 		/*
8805 		 * if this isn't an exclusive access
8806 		 * res generate UA for all other
8807 		 * registrants.
8808 		 */
8809 		if (type != SPR_TYPE_EX_AC
8810 		 && type != SPR_TYPE_WR_EX) {
8811 			/*
8812 			 * temporarily unregister so we don't generate UA
8813 			 */
8814 			lun->per_res[residx].registered = 0;
8815 
8816 			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8817 				if (lun->per_res[i+persis_offset].registered
8818 				    == 0)
8819 					continue;
8820 				lun->pending_ua[i] |=
8821 					CTL_UA_RES_RELEASE;
8822 			}
8823 
8824 			lun->per_res[residx].registered = 1;
8825 		}
8826 		mtx_unlock(&lun->lun_lock);
8827 		/* Send msg to other side */
8828 		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8829 		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8830 		persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8831 		if ((isc_retval=ctl_ha_msg_send( CTL_HA_CHAN_CTL, &persis_io,
8832 		     sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8833 			printf("CTL:Persis Out error returned from "
8834 			       "ctl_ha_msg_send %d\n", isc_retval);
8835 		}
8836 		break;
8837 
8838 	case SPRO_CLEAR:
8839 		/* send msg to other side */
8840 
8841 		mtx_lock(&lun->lun_lock);
8842 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8843 		lun->res_type = 0;
8844 		lun->pr_key_count = 0;
8845 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8846 
8847 
8848 		memset(&lun->per_res[residx].res_key,
8849 		       0, sizeof(lun->per_res[residx].res_key));
8850 		lun->per_res[residx].registered = 0;
8851 
8852 		for (i=0; i < 2*CTL_MAX_INITIATORS; i++)
8853 			if (lun->per_res[i].registered) {
8854 				if (!persis_offset && i < CTL_MAX_INITIATORS)
8855 					lun->pending_ua[i] |=
8856 						CTL_UA_RES_PREEMPT;
8857 				else if (persis_offset && i >= persis_offset)
8858 					lun->pending_ua[i-persis_offset] |=
8859 					    CTL_UA_RES_PREEMPT;
8860 
8861 				memset(&lun->per_res[i].res_key,
8862 				       0, sizeof(struct scsi_per_res_key));
8863 				lun->per_res[i].registered = 0;
8864 			}
8865 		lun->PRGeneration++;
8866 		mtx_unlock(&lun->lun_lock);
8867 		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8868 		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8869 		persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8870 		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8871 		     sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8872 			printf("CTL:Persis Out error returned from "
8873 			       "ctl_ha_msg_send %d\n", isc_retval);
8874 		}
8875 		break;
8876 
8877 	case SPRO_PREEMPT: {
8878 		int nretval;
8879 
8880 		nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8881 					  residx, ctsio, cdb, param);
8882 		if (nretval != 0)
8883 			return (CTL_RETVAL_COMPLETE);
8884 		break;
8885 	}
8886 	default:
8887 		panic("Invalid PR type %x", cdb->action);
8888 	}
8889 
8890 done:
8891 	free(ctsio->kern_data_ptr, M_CTL);
8892 	ctl_set_success(ctsio);
8893 	ctl_done((union ctl_io *)ctsio);
8894 
8895 	return (retval);
8896 }
8897 
8898 /*
8899  * This routine is for handling a message from the other SC pertaining to
8900  * persistent reserve out. All the error checking will have been done
8901  * so only perorming the action need be done here to keep the two
8902  * in sync.
8903  */
8904 static void
8905 ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg)
8906 {
8907 	struct ctl_lun *lun;
8908 	struct ctl_softc *softc;
8909 	int i;
8910 	uint32_t targ_lun;
8911 
8912 	softc = control_softc;
8913 
8914 	targ_lun = msg->hdr.nexus.targ_mapped_lun;
8915 	lun = softc->ctl_luns[targ_lun];
8916 	mtx_lock(&lun->lun_lock);
8917 	switch(msg->pr.pr_info.action) {
8918 	case CTL_PR_REG_KEY:
8919 		if (!lun->per_res[msg->pr.pr_info.residx].registered) {
8920 			lun->per_res[msg->pr.pr_info.residx].registered = 1;
8921 			lun->pr_key_count++;
8922 		}
8923 		lun->PRGeneration++;
8924 		memcpy(&lun->per_res[msg->pr.pr_info.residx].res_key,
8925 		       msg->pr.pr_info.sa_res_key,
8926 		       sizeof(struct scsi_per_res_key));
8927 		break;
8928 
8929 	case CTL_PR_UNREG_KEY:
8930 		lun->per_res[msg->pr.pr_info.residx].registered = 0;
8931 		memset(&lun->per_res[msg->pr.pr_info.residx].res_key,
8932 		       0, sizeof(struct scsi_per_res_key));
8933 		lun->pr_key_count--;
8934 
8935 		/* XXX Need to see if the reservation has been released */
8936 		/* if so do we need to generate UA? */
8937 		if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8938 			lun->flags &= ~CTL_LUN_PR_RESERVED;
8939 			lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8940 
8941 			if ((lun->res_type == SPR_TYPE_WR_EX_RO
8942 			  || lun->res_type == SPR_TYPE_EX_AC_RO)
8943 			 && lun->pr_key_count) {
8944 				/*
8945 				 * If the reservation is a registrants
8946 				 * only type we need to generate a UA
8947 				 * for other registered inits.  The
8948 				 * sense code should be RESERVATIONS
8949 				 * RELEASED
8950 				 */
8951 
8952 				for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8953 					if (lun->per_res[i+
8954 					    persis_offset].registered == 0)
8955 						continue;
8956 
8957 					lun->pending_ua[i] |=
8958 						CTL_UA_RES_RELEASE;
8959 				}
8960 			}
8961 			lun->res_type = 0;
8962 		} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8963 			if (lun->pr_key_count==0) {
8964 				lun->flags &= ~CTL_LUN_PR_RESERVED;
8965 				lun->res_type = 0;
8966 				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8967 			}
8968 		}
8969 		lun->PRGeneration++;
8970 		break;
8971 
8972 	case CTL_PR_RESERVE:
8973 		lun->flags |= CTL_LUN_PR_RESERVED;
8974 		lun->res_type = msg->pr.pr_info.res_type;
8975 		lun->pr_res_idx = msg->pr.pr_info.residx;
8976 
8977 		break;
8978 
8979 	case CTL_PR_RELEASE:
8980 		/*
8981 		 * if this isn't an exclusive access res generate UA for all
8982 		 * other registrants.
8983 		 */
8984 		if (lun->res_type != SPR_TYPE_EX_AC
8985 		 && lun->res_type != SPR_TYPE_WR_EX) {
8986 			for (i = 0; i < CTL_MAX_INITIATORS; i++)
8987 				if (lun->per_res[i+persis_offset].registered)
8988 					lun->pending_ua[i] |=
8989 						CTL_UA_RES_RELEASE;
8990 		}
8991 
8992 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8993 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8994 		lun->res_type = 0;
8995 		break;
8996 
8997 	case CTL_PR_PREEMPT:
8998 		ctl_pro_preempt_other(lun, msg);
8999 		break;
9000 	case CTL_PR_CLEAR:
9001 		lun->flags &= ~CTL_LUN_PR_RESERVED;
9002 		lun->res_type = 0;
9003 		lun->pr_key_count = 0;
9004 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
9005 
9006 		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
9007 			if (lun->per_res[i].registered == 0)
9008 				continue;
9009 			if (!persis_offset
9010 			 && i < CTL_MAX_INITIATORS)
9011 				lun->pending_ua[i] |= CTL_UA_RES_PREEMPT;
9012 			else if (persis_offset
9013 			      && i >= persis_offset)
9014 				lun->pending_ua[i-persis_offset] |=
9015 					CTL_UA_RES_PREEMPT;
9016 			memset(&lun->per_res[i].res_key, 0,
9017 			       sizeof(struct scsi_per_res_key));
9018 			lun->per_res[i].registered = 0;
9019 		}
9020 		lun->PRGeneration++;
9021 		break;
9022 	}
9023 
9024 	mtx_unlock(&lun->lun_lock);
9025 }
9026 
9027 int
9028 ctl_read_write(struct ctl_scsiio *ctsio)
9029 {
9030 	struct ctl_lun *lun;
9031 	struct ctl_lba_len_flags *lbalen;
9032 	uint64_t lba;
9033 	uint32_t num_blocks;
9034 	int flags, retval;
9035 	int isread;
9036 
9037 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9038 
9039 	CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
9040 
9041 	flags = 0;
9042 	retval = CTL_RETVAL_COMPLETE;
9043 
9044 	isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
9045 	      || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
9046 	if (lun->flags & CTL_LUN_PR_RESERVED && isread) {
9047 		uint32_t residx;
9048 
9049 		/*
9050 		 * XXX KDM need a lock here.
9051 		 */
9052 		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
9053 		if ((lun->res_type == SPR_TYPE_EX_AC
9054 		  && residx != lun->pr_res_idx)
9055 		 || ((lun->res_type == SPR_TYPE_EX_AC_RO
9056 		   || lun->res_type == SPR_TYPE_EX_AC_AR)
9057 		  && !lun->per_res[residx].registered)) {
9058 			ctl_set_reservation_conflict(ctsio);
9059 			ctl_done((union ctl_io *)ctsio);
9060 			return (CTL_RETVAL_COMPLETE);
9061 	        }
9062 	}
9063 
9064 	switch (ctsio->cdb[0]) {
9065 	case READ_6:
9066 	case WRITE_6: {
9067 		struct scsi_rw_6 *cdb;
9068 
9069 		cdb = (struct scsi_rw_6 *)ctsio->cdb;
9070 
9071 		lba = scsi_3btoul(cdb->addr);
9072 		/* only 5 bits are valid in the most significant address byte */
9073 		lba &= 0x1fffff;
9074 		num_blocks = cdb->length;
9075 		/*
9076 		 * This is correct according to SBC-2.
9077 		 */
9078 		if (num_blocks == 0)
9079 			num_blocks = 256;
9080 		break;
9081 	}
9082 	case READ_10:
9083 	case WRITE_10: {
9084 		struct scsi_rw_10 *cdb;
9085 
9086 		cdb = (struct scsi_rw_10 *)ctsio->cdb;
9087 		if (cdb->byte2 & SRW10_FUA)
9088 			flags |= CTL_LLF_FUA;
9089 		if (cdb->byte2 & SRW10_DPO)
9090 			flags |= CTL_LLF_DPO;
9091 		lba = scsi_4btoul(cdb->addr);
9092 		num_blocks = scsi_2btoul(cdb->length);
9093 		break;
9094 	}
9095 	case WRITE_VERIFY_10: {
9096 		struct scsi_write_verify_10 *cdb;
9097 
9098 		cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
9099 		flags |= CTL_LLF_FUA;
9100 		if (cdb->byte2 & SWV_DPO)
9101 			flags |= CTL_LLF_DPO;
9102 		lba = scsi_4btoul(cdb->addr);
9103 		num_blocks = scsi_2btoul(cdb->length);
9104 		break;
9105 	}
9106 	case READ_12:
9107 	case WRITE_12: {
9108 		struct scsi_rw_12 *cdb;
9109 
9110 		cdb = (struct scsi_rw_12 *)ctsio->cdb;
9111 		if (cdb->byte2 & SRW12_FUA)
9112 			flags |= CTL_LLF_FUA;
9113 		if (cdb->byte2 & SRW12_DPO)
9114 			flags |= CTL_LLF_DPO;
9115 		lba = scsi_4btoul(cdb->addr);
9116 		num_blocks = scsi_4btoul(cdb->length);
9117 		break;
9118 	}
9119 	case WRITE_VERIFY_12: {
9120 		struct scsi_write_verify_12 *cdb;
9121 
9122 		cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
9123 		flags |= CTL_LLF_FUA;
9124 		if (cdb->byte2 & SWV_DPO)
9125 			flags |= CTL_LLF_DPO;
9126 		lba = scsi_4btoul(cdb->addr);
9127 		num_blocks = scsi_4btoul(cdb->length);
9128 		break;
9129 	}
9130 	case READ_16:
9131 	case WRITE_16: {
9132 		struct scsi_rw_16 *cdb;
9133 
9134 		cdb = (struct scsi_rw_16 *)ctsio->cdb;
9135 		if (cdb->byte2 & SRW12_FUA)
9136 			flags |= CTL_LLF_FUA;
9137 		if (cdb->byte2 & SRW12_DPO)
9138 			flags |= CTL_LLF_DPO;
9139 		lba = scsi_8btou64(cdb->addr);
9140 		num_blocks = scsi_4btoul(cdb->length);
9141 		break;
9142 	}
9143 	case WRITE_VERIFY_16: {
9144 		struct scsi_write_verify_16 *cdb;
9145 
9146 		cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
9147 		flags |= CTL_LLF_FUA;
9148 		if (cdb->byte2 & SWV_DPO)
9149 			flags |= CTL_LLF_DPO;
9150 		lba = scsi_8btou64(cdb->addr);
9151 		num_blocks = scsi_4btoul(cdb->length);
9152 		break;
9153 	}
9154 	default:
9155 		/*
9156 		 * We got a command we don't support.  This shouldn't
9157 		 * happen, commands should be filtered out above us.
9158 		 */
9159 		ctl_set_invalid_opcode(ctsio);
9160 		ctl_done((union ctl_io *)ctsio);
9161 
9162 		return (CTL_RETVAL_COMPLETE);
9163 		break; /* NOTREACHED */
9164 	}
9165 
9166 	/*
9167 	 * The first check is to make sure we're in bounds, the second
9168 	 * check is to catch wrap-around problems.  If the lba + num blocks
9169 	 * is less than the lba, then we've wrapped around and the block
9170 	 * range is invalid anyway.
9171 	 */
9172 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9173 	 || ((lba + num_blocks) < lba)) {
9174 		ctl_set_lba_out_of_range(ctsio);
9175 		ctl_done((union ctl_io *)ctsio);
9176 		return (CTL_RETVAL_COMPLETE);
9177 	}
9178 
9179 	/*
9180 	 * According to SBC-3, a transfer length of 0 is not an error.
9181 	 * Note that this cannot happen with WRITE(6) or READ(6), since 0
9182 	 * translates to 256 blocks for those commands.
9183 	 */
9184 	if (num_blocks == 0) {
9185 		ctl_set_success(ctsio);
9186 		ctl_done((union ctl_io *)ctsio);
9187 		return (CTL_RETVAL_COMPLETE);
9188 	}
9189 
9190 	/* Set FUA and/or DPO if caches are disabled. */
9191 	if (isread) {
9192 		if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9193 		    SCP_RCD) != 0)
9194 			flags |= CTL_LLF_FUA | CTL_LLF_DPO;
9195 	} else {
9196 		if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9197 		    SCP_WCE) == 0)
9198 			flags |= CTL_LLF_FUA;
9199 	}
9200 
9201 	lbalen = (struct ctl_lba_len_flags *)
9202 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9203 	lbalen->lba = lba;
9204 	lbalen->len = num_blocks;
9205 	lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
9206 
9207 	ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9208 	ctsio->kern_rel_offset = 0;
9209 
9210 	CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
9211 
9212 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9213 
9214 	return (retval);
9215 }
9216 
9217 static int
9218 ctl_cnw_cont(union ctl_io *io)
9219 {
9220 	struct ctl_scsiio *ctsio;
9221 	struct ctl_lun *lun;
9222 	struct ctl_lba_len_flags *lbalen;
9223 	int retval;
9224 
9225 	ctsio = &io->scsiio;
9226 	ctsio->io_hdr.status = CTL_STATUS_NONE;
9227 	ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
9228 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9229 	lbalen = (struct ctl_lba_len_flags *)
9230 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9231 	lbalen->flags &= ~CTL_LLF_COMPARE;
9232 	lbalen->flags |= CTL_LLF_WRITE;
9233 
9234 	CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
9235 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9236 	return (retval);
9237 }
9238 
9239 int
9240 ctl_cnw(struct ctl_scsiio *ctsio)
9241 {
9242 	struct ctl_lun *lun;
9243 	struct ctl_lba_len_flags *lbalen;
9244 	uint64_t lba;
9245 	uint32_t num_blocks;
9246 	int flags, retval;
9247 
9248 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9249 
9250 	CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
9251 
9252 	flags = 0;
9253 	retval = CTL_RETVAL_COMPLETE;
9254 
9255 	switch (ctsio->cdb[0]) {
9256 	case COMPARE_AND_WRITE: {
9257 		struct scsi_compare_and_write *cdb;
9258 
9259 		cdb = (struct scsi_compare_and_write *)ctsio->cdb;
9260 		if (cdb->byte2 & SRW10_FUA)
9261 			flags |= CTL_LLF_FUA;
9262 		if (cdb->byte2 & SRW10_DPO)
9263 			flags |= CTL_LLF_DPO;
9264 		lba = scsi_8btou64(cdb->addr);
9265 		num_blocks = cdb->length;
9266 		break;
9267 	}
9268 	default:
9269 		/*
9270 		 * We got a command we don't support.  This shouldn't
9271 		 * happen, commands should be filtered out above us.
9272 		 */
9273 		ctl_set_invalid_opcode(ctsio);
9274 		ctl_done((union ctl_io *)ctsio);
9275 
9276 		return (CTL_RETVAL_COMPLETE);
9277 		break; /* NOTREACHED */
9278 	}
9279 
9280 	/*
9281 	 * The first check is to make sure we're in bounds, the second
9282 	 * check is to catch wrap-around problems.  If the lba + num blocks
9283 	 * is less than the lba, then we've wrapped around and the block
9284 	 * range is invalid anyway.
9285 	 */
9286 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9287 	 || ((lba + num_blocks) < lba)) {
9288 		ctl_set_lba_out_of_range(ctsio);
9289 		ctl_done((union ctl_io *)ctsio);
9290 		return (CTL_RETVAL_COMPLETE);
9291 	}
9292 
9293 	/*
9294 	 * According to SBC-3, a transfer length of 0 is not an error.
9295 	 */
9296 	if (num_blocks == 0) {
9297 		ctl_set_success(ctsio);
9298 		ctl_done((union ctl_io *)ctsio);
9299 		return (CTL_RETVAL_COMPLETE);
9300 	}
9301 
9302 	/* Set FUA if write cache is disabled. */
9303 	if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9304 	    SCP_WCE) == 0)
9305 		flags |= CTL_LLF_FUA;
9306 
9307 	ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
9308 	ctsio->kern_rel_offset = 0;
9309 
9310 	/*
9311 	 * Set the IO_CONT flag, so that if this I/O gets passed to
9312 	 * ctl_data_submit_done(), it'll get passed back to
9313 	 * ctl_ctl_cnw_cont() for further processing.
9314 	 */
9315 	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
9316 	ctsio->io_cont = ctl_cnw_cont;
9317 
9318 	lbalen = (struct ctl_lba_len_flags *)
9319 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9320 	lbalen->lba = lba;
9321 	lbalen->len = num_blocks;
9322 	lbalen->flags = CTL_LLF_COMPARE | flags;
9323 
9324 	CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
9325 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9326 	return (retval);
9327 }
9328 
9329 int
9330 ctl_verify(struct ctl_scsiio *ctsio)
9331 {
9332 	struct ctl_lun *lun;
9333 	struct ctl_lba_len_flags *lbalen;
9334 	uint64_t lba;
9335 	uint32_t num_blocks;
9336 	int bytchk, flags;
9337 	int retval;
9338 
9339 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9340 
9341 	CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
9342 
9343 	bytchk = 0;
9344 	flags = CTL_LLF_FUA;
9345 	retval = CTL_RETVAL_COMPLETE;
9346 
9347 	switch (ctsio->cdb[0]) {
9348 	case VERIFY_10: {
9349 		struct scsi_verify_10 *cdb;
9350 
9351 		cdb = (struct scsi_verify_10 *)ctsio->cdb;
9352 		if (cdb->byte2 & SVFY_BYTCHK)
9353 			bytchk = 1;
9354 		if (cdb->byte2 & SVFY_DPO)
9355 			flags |= CTL_LLF_DPO;
9356 		lba = scsi_4btoul(cdb->addr);
9357 		num_blocks = scsi_2btoul(cdb->length);
9358 		break;
9359 	}
9360 	case VERIFY_12: {
9361 		struct scsi_verify_12 *cdb;
9362 
9363 		cdb = (struct scsi_verify_12 *)ctsio->cdb;
9364 		if (cdb->byte2 & SVFY_BYTCHK)
9365 			bytchk = 1;
9366 		if (cdb->byte2 & SVFY_DPO)
9367 			flags |= CTL_LLF_DPO;
9368 		lba = scsi_4btoul(cdb->addr);
9369 		num_blocks = scsi_4btoul(cdb->length);
9370 		break;
9371 	}
9372 	case VERIFY_16: {
9373 		struct scsi_rw_16 *cdb;
9374 
9375 		cdb = (struct scsi_rw_16 *)ctsio->cdb;
9376 		if (cdb->byte2 & SVFY_BYTCHK)
9377 			bytchk = 1;
9378 		if (cdb->byte2 & SVFY_DPO)
9379 			flags |= CTL_LLF_DPO;
9380 		lba = scsi_8btou64(cdb->addr);
9381 		num_blocks = scsi_4btoul(cdb->length);
9382 		break;
9383 	}
9384 	default:
9385 		/*
9386 		 * We got a command we don't support.  This shouldn't
9387 		 * happen, commands should be filtered out above us.
9388 		 */
9389 		ctl_set_invalid_opcode(ctsio);
9390 		ctl_done((union ctl_io *)ctsio);
9391 		return (CTL_RETVAL_COMPLETE);
9392 	}
9393 
9394 	/*
9395 	 * The first check is to make sure we're in bounds, the second
9396 	 * check is to catch wrap-around problems.  If the lba + num blocks
9397 	 * is less than the lba, then we've wrapped around and the block
9398 	 * range is invalid anyway.
9399 	 */
9400 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9401 	 || ((lba + num_blocks) < lba)) {
9402 		ctl_set_lba_out_of_range(ctsio);
9403 		ctl_done((union ctl_io *)ctsio);
9404 		return (CTL_RETVAL_COMPLETE);
9405 	}
9406 
9407 	/*
9408 	 * According to SBC-3, a transfer length of 0 is not an error.
9409 	 */
9410 	if (num_blocks == 0) {
9411 		ctl_set_success(ctsio);
9412 		ctl_done((union ctl_io *)ctsio);
9413 		return (CTL_RETVAL_COMPLETE);
9414 	}
9415 
9416 	lbalen = (struct ctl_lba_len_flags *)
9417 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9418 	lbalen->lba = lba;
9419 	lbalen->len = num_blocks;
9420 	if (bytchk) {
9421 		lbalen->flags = CTL_LLF_COMPARE | flags;
9422 		ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9423 	} else {
9424 		lbalen->flags = CTL_LLF_VERIFY | flags;
9425 		ctsio->kern_total_len = 0;
9426 	}
9427 	ctsio->kern_rel_offset = 0;
9428 
9429 	CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9430 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9431 	return (retval);
9432 }
9433 
9434 int
9435 ctl_report_luns(struct ctl_scsiio *ctsio)
9436 {
9437 	struct scsi_report_luns *cdb;
9438 	struct scsi_report_luns_data *lun_data;
9439 	struct ctl_lun *lun, *request_lun;
9440 	int num_luns, retval;
9441 	uint32_t alloc_len, lun_datalen;
9442 	int num_filled, well_known;
9443 	uint32_t initidx, targ_lun_id, lun_id;
9444 
9445 	retval = CTL_RETVAL_COMPLETE;
9446 	well_known = 0;
9447 
9448 	cdb = (struct scsi_report_luns *)ctsio->cdb;
9449 
9450 	CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9451 
9452 	mtx_lock(&control_softc->ctl_lock);
9453 	num_luns = control_softc->num_luns;
9454 	mtx_unlock(&control_softc->ctl_lock);
9455 
9456 	switch (cdb->select_report) {
9457 	case RPL_REPORT_DEFAULT:
9458 	case RPL_REPORT_ALL:
9459 		break;
9460 	case RPL_REPORT_WELLKNOWN:
9461 		well_known = 1;
9462 		num_luns = 0;
9463 		break;
9464 	default:
9465 		ctl_set_invalid_field(ctsio,
9466 				      /*sks_valid*/ 1,
9467 				      /*command*/ 1,
9468 				      /*field*/ 2,
9469 				      /*bit_valid*/ 0,
9470 				      /*bit*/ 0);
9471 		ctl_done((union ctl_io *)ctsio);
9472 		return (retval);
9473 		break; /* NOTREACHED */
9474 	}
9475 
9476 	alloc_len = scsi_4btoul(cdb->length);
9477 	/*
9478 	 * The initiator has to allocate at least 16 bytes for this request,
9479 	 * so he can at least get the header and the first LUN.  Otherwise
9480 	 * we reject the request (per SPC-3 rev 14, section 6.21).
9481 	 */
9482 	if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9483 	    sizeof(struct scsi_report_luns_lundata))) {
9484 		ctl_set_invalid_field(ctsio,
9485 				      /*sks_valid*/ 1,
9486 				      /*command*/ 1,
9487 				      /*field*/ 6,
9488 				      /*bit_valid*/ 0,
9489 				      /*bit*/ 0);
9490 		ctl_done((union ctl_io *)ctsio);
9491 		return (retval);
9492 	}
9493 
9494 	request_lun = (struct ctl_lun *)
9495 		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9496 
9497 	lun_datalen = sizeof(*lun_data) +
9498 		(num_luns * sizeof(struct scsi_report_luns_lundata));
9499 
9500 	ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9501 	lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9502 	ctsio->kern_sg_entries = 0;
9503 
9504 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9505 
9506 	mtx_lock(&control_softc->ctl_lock);
9507 	for (targ_lun_id = 0, num_filled = 0; targ_lun_id < CTL_MAX_LUNS && num_filled < num_luns; targ_lun_id++) {
9508 		lun_id = ctl_map_lun(ctsio->io_hdr.nexus.targ_port, targ_lun_id);
9509 		if (lun_id >= CTL_MAX_LUNS)
9510 			continue;
9511 		lun = control_softc->ctl_luns[lun_id];
9512 		if (lun == NULL)
9513 			continue;
9514 
9515 		if (targ_lun_id <= 0xff) {
9516 			/*
9517 			 * Peripheral addressing method, bus number 0.
9518 			 */
9519 			lun_data->luns[num_filled].lundata[0] =
9520 				RPL_LUNDATA_ATYP_PERIPH;
9521 			lun_data->luns[num_filled].lundata[1] = targ_lun_id;
9522 			num_filled++;
9523 		} else if (targ_lun_id <= 0x3fff) {
9524 			/*
9525 			 * Flat addressing method.
9526 			 */
9527 			lun_data->luns[num_filled].lundata[0] =
9528 				RPL_LUNDATA_ATYP_FLAT |
9529 				(targ_lun_id & RPL_LUNDATA_FLAT_LUN_MASK);
9530 #ifdef OLDCTLHEADERS
9531 				(SRLD_ADDR_FLAT << SRLD_ADDR_SHIFT) |
9532 				(targ_lun_id & SRLD_BUS_LUN_MASK);
9533 #endif
9534 			lun_data->luns[num_filled].lundata[1] =
9535 #ifdef OLDCTLHEADERS
9536 				targ_lun_id >> SRLD_BUS_LUN_BITS;
9537 #endif
9538 				targ_lun_id >> RPL_LUNDATA_FLAT_LUN_BITS;
9539 			num_filled++;
9540 		} else {
9541 			printf("ctl_report_luns: bogus LUN number %jd, "
9542 			       "skipping\n", (intmax_t)targ_lun_id);
9543 		}
9544 		/*
9545 		 * According to SPC-3, rev 14 section 6.21:
9546 		 *
9547 		 * "The execution of a REPORT LUNS command to any valid and
9548 		 * installed logical unit shall clear the REPORTED LUNS DATA
9549 		 * HAS CHANGED unit attention condition for all logical
9550 		 * units of that target with respect to the requesting
9551 		 * initiator. A valid and installed logical unit is one
9552 		 * having a PERIPHERAL QUALIFIER of 000b in the standard
9553 		 * INQUIRY data (see 6.4.2)."
9554 		 *
9555 		 * If request_lun is NULL, the LUN this report luns command
9556 		 * was issued to is either disabled or doesn't exist. In that
9557 		 * case, we shouldn't clear any pending lun change unit
9558 		 * attention.
9559 		 */
9560 		if (request_lun != NULL) {
9561 			mtx_lock(&lun->lun_lock);
9562 			lun->pending_ua[initidx] &= ~CTL_UA_LUN_CHANGE;
9563 			mtx_unlock(&lun->lun_lock);
9564 		}
9565 	}
9566 	mtx_unlock(&control_softc->ctl_lock);
9567 
9568 	/*
9569 	 * It's quite possible that we've returned fewer LUNs than we allocated
9570 	 * space for.  Trim it.
9571 	 */
9572 	lun_datalen = sizeof(*lun_data) +
9573 		(num_filled * sizeof(struct scsi_report_luns_lundata));
9574 
9575 	if (lun_datalen < alloc_len) {
9576 		ctsio->residual = alloc_len - lun_datalen;
9577 		ctsio->kern_data_len = lun_datalen;
9578 		ctsio->kern_total_len = lun_datalen;
9579 	} else {
9580 		ctsio->residual = 0;
9581 		ctsio->kern_data_len = alloc_len;
9582 		ctsio->kern_total_len = alloc_len;
9583 	}
9584 	ctsio->kern_data_resid = 0;
9585 	ctsio->kern_rel_offset = 0;
9586 	ctsio->kern_sg_entries = 0;
9587 
9588 	/*
9589 	 * We set this to the actual data length, regardless of how much
9590 	 * space we actually have to return results.  If the user looks at
9591 	 * this value, he'll know whether or not he allocated enough space
9592 	 * and reissue the command if necessary.  We don't support well
9593 	 * known logical units, so if the user asks for that, return none.
9594 	 */
9595 	scsi_ulto4b(lun_datalen - 8, lun_data->length);
9596 
9597 	/*
9598 	 * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9599 	 * this request.
9600 	 */
9601 	ctsio->scsi_status = SCSI_STATUS_OK;
9602 
9603 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9604 	ctsio->be_move_done = ctl_config_move_done;
9605 	ctl_datamove((union ctl_io *)ctsio);
9606 
9607 	return (retval);
9608 }
9609 
9610 int
9611 ctl_request_sense(struct ctl_scsiio *ctsio)
9612 {
9613 	struct scsi_request_sense *cdb;
9614 	struct scsi_sense_data *sense_ptr;
9615 	struct ctl_lun *lun;
9616 	uint32_t initidx;
9617 	int have_error;
9618 	scsi_sense_data_type sense_format;
9619 
9620 	cdb = (struct scsi_request_sense *)ctsio->cdb;
9621 
9622 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9623 
9624 	CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9625 
9626 	/*
9627 	 * Determine which sense format the user wants.
9628 	 */
9629 	if (cdb->byte2 & SRS_DESC)
9630 		sense_format = SSD_TYPE_DESC;
9631 	else
9632 		sense_format = SSD_TYPE_FIXED;
9633 
9634 	ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9635 	sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9636 	ctsio->kern_sg_entries = 0;
9637 
9638 	/*
9639 	 * struct scsi_sense_data, which is currently set to 256 bytes, is
9640 	 * larger than the largest allowed value for the length field in the
9641 	 * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9642 	 */
9643 	ctsio->residual = 0;
9644 	ctsio->kern_data_len = cdb->length;
9645 	ctsio->kern_total_len = cdb->length;
9646 
9647 	ctsio->kern_data_resid = 0;
9648 	ctsio->kern_rel_offset = 0;
9649 	ctsio->kern_sg_entries = 0;
9650 
9651 	/*
9652 	 * If we don't have a LUN, we don't have any pending sense.
9653 	 */
9654 	if (lun == NULL)
9655 		goto no_sense;
9656 
9657 	have_error = 0;
9658 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9659 	/*
9660 	 * Check for pending sense, and then for pending unit attentions.
9661 	 * Pending sense gets returned first, then pending unit attentions.
9662 	 */
9663 	mtx_lock(&lun->lun_lock);
9664 #ifdef CTL_WITH_CA
9665 	if (ctl_is_set(lun->have_ca, initidx)) {
9666 		scsi_sense_data_type stored_format;
9667 
9668 		/*
9669 		 * Check to see which sense format was used for the stored
9670 		 * sense data.
9671 		 */
9672 		stored_format = scsi_sense_type(&lun->pending_sense[initidx]);
9673 
9674 		/*
9675 		 * If the user requested a different sense format than the
9676 		 * one we stored, then we need to convert it to the other
9677 		 * format.  If we're going from descriptor to fixed format
9678 		 * sense data, we may lose things in translation, depending
9679 		 * on what options were used.
9680 		 *
9681 		 * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9682 		 * for some reason we'll just copy it out as-is.
9683 		 */
9684 		if ((stored_format == SSD_TYPE_FIXED)
9685 		 && (sense_format == SSD_TYPE_DESC))
9686 			ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9687 			    &lun->pending_sense[initidx],
9688 			    (struct scsi_sense_data_desc *)sense_ptr);
9689 		else if ((stored_format == SSD_TYPE_DESC)
9690 		      && (sense_format == SSD_TYPE_FIXED))
9691 			ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9692 			    &lun->pending_sense[initidx],
9693 			    (struct scsi_sense_data_fixed *)sense_ptr);
9694 		else
9695 			memcpy(sense_ptr, &lun->pending_sense[initidx],
9696 			       ctl_min(sizeof(*sense_ptr),
9697 			       sizeof(lun->pending_sense[initidx])));
9698 
9699 		ctl_clear_mask(lun->have_ca, initidx);
9700 		have_error = 1;
9701 	} else
9702 #endif
9703 	if (lun->pending_ua[initidx] != CTL_UA_NONE) {
9704 		ctl_ua_type ua_type;
9705 
9706 		ua_type = ctl_build_ua(lun->pending_ua[initidx],
9707 				       sense_ptr, sense_format);
9708 		if (ua_type != CTL_UA_NONE) {
9709 			have_error = 1;
9710 			/* We're reporting this UA, so clear it */
9711 			lun->pending_ua[initidx] &= ~ua_type;
9712 		}
9713 	}
9714 	mtx_unlock(&lun->lun_lock);
9715 
9716 	/*
9717 	 * We already have a pending error, return it.
9718 	 */
9719 	if (have_error != 0) {
9720 		/*
9721 		 * We report the SCSI status as OK, since the status of the
9722 		 * request sense command itself is OK.
9723 		 */
9724 		ctsio->scsi_status = SCSI_STATUS_OK;
9725 
9726 		/*
9727 		 * We report 0 for the sense length, because we aren't doing
9728 		 * autosense in this case.  We're reporting sense as
9729 		 * parameter data.
9730 		 */
9731 		ctsio->sense_len = 0;
9732 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9733 		ctsio->be_move_done = ctl_config_move_done;
9734 		ctl_datamove((union ctl_io *)ctsio);
9735 
9736 		return (CTL_RETVAL_COMPLETE);
9737 	}
9738 
9739 no_sense:
9740 
9741 	/*
9742 	 * No sense information to report, so we report that everything is
9743 	 * okay.
9744 	 */
9745 	ctl_set_sense_data(sense_ptr,
9746 			   lun,
9747 			   sense_format,
9748 			   /*current_error*/ 1,
9749 			   /*sense_key*/ SSD_KEY_NO_SENSE,
9750 			   /*asc*/ 0x00,
9751 			   /*ascq*/ 0x00,
9752 			   SSD_ELEM_NONE);
9753 
9754 	ctsio->scsi_status = SCSI_STATUS_OK;
9755 
9756 	/*
9757 	 * We report 0 for the sense length, because we aren't doing
9758 	 * autosense in this case.  We're reporting sense as parameter data.
9759 	 */
9760 	ctsio->sense_len = 0;
9761 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9762 	ctsio->be_move_done = ctl_config_move_done;
9763 	ctl_datamove((union ctl_io *)ctsio);
9764 
9765 	return (CTL_RETVAL_COMPLETE);
9766 }
9767 
9768 int
9769 ctl_tur(struct ctl_scsiio *ctsio)
9770 {
9771 	struct ctl_lun *lun;
9772 
9773 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9774 
9775 	CTL_DEBUG_PRINT(("ctl_tur\n"));
9776 
9777 	if (lun == NULL)
9778 		return (EINVAL);
9779 
9780 	ctsio->scsi_status = SCSI_STATUS_OK;
9781 	ctsio->io_hdr.status = CTL_SUCCESS;
9782 
9783 	ctl_done((union ctl_io *)ctsio);
9784 
9785 	return (CTL_RETVAL_COMPLETE);
9786 }
9787 
9788 #ifdef notyet
9789 static int
9790 ctl_cmddt_inquiry(struct ctl_scsiio *ctsio)
9791 {
9792 
9793 }
9794 #endif
9795 
9796 static int
9797 ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9798 {
9799 	struct scsi_vpd_supported_pages *pages;
9800 	int sup_page_size;
9801 	struct ctl_lun *lun;
9802 
9803 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9804 
9805 	sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9806 	    SCSI_EVPD_NUM_SUPPORTED_PAGES;
9807 	ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9808 	pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9809 	ctsio->kern_sg_entries = 0;
9810 
9811 	if (sup_page_size < alloc_len) {
9812 		ctsio->residual = alloc_len - sup_page_size;
9813 		ctsio->kern_data_len = sup_page_size;
9814 		ctsio->kern_total_len = sup_page_size;
9815 	} else {
9816 		ctsio->residual = 0;
9817 		ctsio->kern_data_len = alloc_len;
9818 		ctsio->kern_total_len = alloc_len;
9819 	}
9820 	ctsio->kern_data_resid = 0;
9821 	ctsio->kern_rel_offset = 0;
9822 	ctsio->kern_sg_entries = 0;
9823 
9824 	/*
9825 	 * The control device is always connected.  The disk device, on the
9826 	 * other hand, may not be online all the time.  Need to change this
9827 	 * to figure out whether the disk device is actually online or not.
9828 	 */
9829 	if (lun != NULL)
9830 		pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9831 				lun->be_lun->lun_type;
9832 	else
9833 		pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9834 
9835 	pages->length = SCSI_EVPD_NUM_SUPPORTED_PAGES;
9836 	/* Supported VPD pages */
9837 	pages->page_list[0] = SVPD_SUPPORTED_PAGES;
9838 	/* Serial Number */
9839 	pages->page_list[1] = SVPD_UNIT_SERIAL_NUMBER;
9840 	/* Device Identification */
9841 	pages->page_list[2] = SVPD_DEVICE_ID;
9842 	/* Extended INQUIRY Data */
9843 	pages->page_list[3] = SVPD_EXTENDED_INQUIRY_DATA;
9844 	/* Mode Page Policy */
9845 	pages->page_list[4] = SVPD_MODE_PAGE_POLICY;
9846 	/* SCSI Ports */
9847 	pages->page_list[5] = SVPD_SCSI_PORTS;
9848 	/* Third-party Copy */
9849 	pages->page_list[6] = SVPD_SCSI_TPC;
9850 	/* Block limits */
9851 	pages->page_list[7] = SVPD_BLOCK_LIMITS;
9852 	/* Block Device Characteristics */
9853 	pages->page_list[8] = SVPD_BDC;
9854 	/* Logical Block Provisioning */
9855 	pages->page_list[9] = SVPD_LBP;
9856 
9857 	ctsio->scsi_status = SCSI_STATUS_OK;
9858 
9859 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9860 	ctsio->be_move_done = ctl_config_move_done;
9861 	ctl_datamove((union ctl_io *)ctsio);
9862 
9863 	return (CTL_RETVAL_COMPLETE);
9864 }
9865 
9866 static int
9867 ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9868 {
9869 	struct scsi_vpd_unit_serial_number *sn_ptr;
9870 	struct ctl_lun *lun;
9871 
9872 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9873 
9874 	ctsio->kern_data_ptr = malloc(sizeof(*sn_ptr), M_CTL, M_WAITOK | M_ZERO);
9875 	sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9876 	ctsio->kern_sg_entries = 0;
9877 
9878 	if (sizeof(*sn_ptr) < alloc_len) {
9879 		ctsio->residual = alloc_len - sizeof(*sn_ptr);
9880 		ctsio->kern_data_len = sizeof(*sn_ptr);
9881 		ctsio->kern_total_len = sizeof(*sn_ptr);
9882 	} else {
9883 		ctsio->residual = 0;
9884 		ctsio->kern_data_len = alloc_len;
9885 		ctsio->kern_total_len = alloc_len;
9886 	}
9887 	ctsio->kern_data_resid = 0;
9888 	ctsio->kern_rel_offset = 0;
9889 	ctsio->kern_sg_entries = 0;
9890 
9891 	/*
9892 	 * The control device is always connected.  The disk device, on the
9893 	 * other hand, may not be online all the time.  Need to change this
9894 	 * to figure out whether the disk device is actually online or not.
9895 	 */
9896 	if (lun != NULL)
9897 		sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9898 				  lun->be_lun->lun_type;
9899 	else
9900 		sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9901 
9902 	sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9903 	sn_ptr->length = ctl_min(sizeof(*sn_ptr) - 4, CTL_SN_LEN);
9904 	/*
9905 	 * If we don't have a LUN, we just leave the serial number as
9906 	 * all spaces.
9907 	 */
9908 	memset(sn_ptr->serial_num, 0x20, sizeof(sn_ptr->serial_num));
9909 	if (lun != NULL) {
9910 		strncpy((char *)sn_ptr->serial_num,
9911 			(char *)lun->be_lun->serial_num, CTL_SN_LEN);
9912 	}
9913 	ctsio->scsi_status = SCSI_STATUS_OK;
9914 
9915 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9916 	ctsio->be_move_done = ctl_config_move_done;
9917 	ctl_datamove((union ctl_io *)ctsio);
9918 
9919 	return (CTL_RETVAL_COMPLETE);
9920 }
9921 
9922 
9923 static int
9924 ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9925 {
9926 	struct scsi_vpd_extended_inquiry_data *eid_ptr;
9927 	struct ctl_lun *lun;
9928 	int data_len;
9929 
9930 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9931 
9932 	data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9933 	    sizeof(struct scsi_vpd_mode_page_policy_descr);
9934 
9935 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9936 	eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9937 	ctsio->kern_sg_entries = 0;
9938 
9939 	if (data_len < alloc_len) {
9940 		ctsio->residual = alloc_len - data_len;
9941 		ctsio->kern_data_len = data_len;
9942 		ctsio->kern_total_len = data_len;
9943 	} else {
9944 		ctsio->residual = 0;
9945 		ctsio->kern_data_len = alloc_len;
9946 		ctsio->kern_total_len = alloc_len;
9947 	}
9948 	ctsio->kern_data_resid = 0;
9949 	ctsio->kern_rel_offset = 0;
9950 	ctsio->kern_sg_entries = 0;
9951 
9952 	/*
9953 	 * The control device is always connected.  The disk device, on the
9954 	 * other hand, may not be online all the time.
9955 	 */
9956 	if (lun != NULL)
9957 		eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9958 				     lun->be_lun->lun_type;
9959 	else
9960 		eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9961 	eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9962 	eid_ptr->page_length = data_len - 4;
9963 	eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9964 	eid_ptr->flags3 = SVPD_EID_V_SUP;
9965 
9966 	ctsio->scsi_status = SCSI_STATUS_OK;
9967 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9968 	ctsio->be_move_done = ctl_config_move_done;
9969 	ctl_datamove((union ctl_io *)ctsio);
9970 
9971 	return (CTL_RETVAL_COMPLETE);
9972 }
9973 
9974 static int
9975 ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
9976 {
9977 	struct scsi_vpd_mode_page_policy *mpp_ptr;
9978 	struct ctl_lun *lun;
9979 	int data_len;
9980 
9981 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9982 
9983 	data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9984 	    sizeof(struct scsi_vpd_mode_page_policy_descr);
9985 
9986 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9987 	mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
9988 	ctsio->kern_sg_entries = 0;
9989 
9990 	if (data_len < alloc_len) {
9991 		ctsio->residual = alloc_len - data_len;
9992 		ctsio->kern_data_len = data_len;
9993 		ctsio->kern_total_len = data_len;
9994 	} else {
9995 		ctsio->residual = 0;
9996 		ctsio->kern_data_len = alloc_len;
9997 		ctsio->kern_total_len = alloc_len;
9998 	}
9999 	ctsio->kern_data_resid = 0;
10000 	ctsio->kern_rel_offset = 0;
10001 	ctsio->kern_sg_entries = 0;
10002 
10003 	/*
10004 	 * The control device is always connected.  The disk device, on the
10005 	 * other hand, may not be online all the time.
10006 	 */
10007 	if (lun != NULL)
10008 		mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10009 				     lun->be_lun->lun_type;
10010 	else
10011 		mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10012 	mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
10013 	scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
10014 	mpp_ptr->descr[0].page_code = 0x3f;
10015 	mpp_ptr->descr[0].subpage_code = 0xff;
10016 	mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
10017 
10018 	ctsio->scsi_status = SCSI_STATUS_OK;
10019 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10020 	ctsio->be_move_done = ctl_config_move_done;
10021 	ctl_datamove((union ctl_io *)ctsio);
10022 
10023 	return (CTL_RETVAL_COMPLETE);
10024 }
10025 
10026 static int
10027 ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
10028 {
10029 	struct scsi_vpd_device_id *devid_ptr;
10030 	struct scsi_vpd_id_descriptor *desc;
10031 	struct ctl_softc *ctl_softc;
10032 	struct ctl_lun *lun;
10033 	struct ctl_port *port;
10034 	int data_len;
10035 	uint8_t proto;
10036 
10037 	ctl_softc = control_softc;
10038 
10039 	port = ctl_softc->ctl_ports[ctl_port_idx(ctsio->io_hdr.nexus.targ_port)];
10040 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10041 
10042 	data_len = sizeof(struct scsi_vpd_device_id) +
10043 	    sizeof(struct scsi_vpd_id_descriptor) +
10044 		sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
10045 	    sizeof(struct scsi_vpd_id_descriptor) +
10046 		sizeof(struct scsi_vpd_id_trgt_port_grp_id);
10047 	if (lun && lun->lun_devid)
10048 		data_len += lun->lun_devid->len;
10049 	if (port->port_devid)
10050 		data_len += port->port_devid->len;
10051 	if (port->target_devid)
10052 		data_len += port->target_devid->len;
10053 
10054 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10055 	devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
10056 	ctsio->kern_sg_entries = 0;
10057 
10058 	if (data_len < alloc_len) {
10059 		ctsio->residual = alloc_len - data_len;
10060 		ctsio->kern_data_len = data_len;
10061 		ctsio->kern_total_len = data_len;
10062 	} else {
10063 		ctsio->residual = 0;
10064 		ctsio->kern_data_len = alloc_len;
10065 		ctsio->kern_total_len = alloc_len;
10066 	}
10067 	ctsio->kern_data_resid = 0;
10068 	ctsio->kern_rel_offset = 0;
10069 	ctsio->kern_sg_entries = 0;
10070 
10071 	/*
10072 	 * The control device is always connected.  The disk device, on the
10073 	 * other hand, may not be online all the time.
10074 	 */
10075 	if (lun != NULL)
10076 		devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10077 				     lun->be_lun->lun_type;
10078 	else
10079 		devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10080 	devid_ptr->page_code = SVPD_DEVICE_ID;
10081 	scsi_ulto2b(data_len - 4, devid_ptr->length);
10082 
10083 	if (port->port_type == CTL_PORT_FC)
10084 		proto = SCSI_PROTO_FC << 4;
10085 	else if (port->port_type == CTL_PORT_ISCSI)
10086 		proto = SCSI_PROTO_ISCSI << 4;
10087 	else
10088 		proto = SCSI_PROTO_SPI << 4;
10089 	desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
10090 
10091 	/*
10092 	 * We're using a LUN association here.  i.e., this device ID is a
10093 	 * per-LUN identifier.
10094 	 */
10095 	if (lun && lun->lun_devid) {
10096 		memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
10097 		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
10098 		    lun->lun_devid->len);
10099 	}
10100 
10101 	/*
10102 	 * This is for the WWPN which is a port association.
10103 	 */
10104 	if (port->port_devid) {
10105 		memcpy(desc, port->port_devid->data, port->port_devid->len);
10106 		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
10107 		    port->port_devid->len);
10108 	}
10109 
10110 	/*
10111 	 * This is for the Relative Target Port(type 4h) identifier
10112 	 */
10113 	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
10114 	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
10115 	    SVPD_ID_TYPE_RELTARG;
10116 	desc->length = 4;
10117 	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
10118 	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
10119 	    sizeof(struct scsi_vpd_id_rel_trgt_port_id));
10120 
10121 	/*
10122 	 * This is for the Target Port Group(type 5h) identifier
10123 	 */
10124 	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
10125 	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
10126 	    SVPD_ID_TYPE_TPORTGRP;
10127 	desc->length = 4;
10128 	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port / CTL_MAX_PORTS + 1,
10129 	    &desc->identifier[2]);
10130 	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
10131 	    sizeof(struct scsi_vpd_id_trgt_port_grp_id));
10132 
10133 	/*
10134 	 * This is for the Target identifier
10135 	 */
10136 	if (port->target_devid) {
10137 		memcpy(desc, port->target_devid->data, port->target_devid->len);
10138 	}
10139 
10140 	ctsio->scsi_status = SCSI_STATUS_OK;
10141 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10142 	ctsio->be_move_done = ctl_config_move_done;
10143 	ctl_datamove((union ctl_io *)ctsio);
10144 
10145 	return (CTL_RETVAL_COMPLETE);
10146 }
10147 
10148 static int
10149 ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
10150 {
10151 	struct ctl_softc *softc = control_softc;
10152 	struct scsi_vpd_scsi_ports *sp;
10153 	struct scsi_vpd_port_designation *pd;
10154 	struct scsi_vpd_port_designation_cont *pdc;
10155 	struct ctl_lun *lun;
10156 	struct ctl_port *port;
10157 	int data_len, num_target_ports, iid_len, id_len, g, pg, p;
10158 	int num_target_port_groups, single;
10159 
10160 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10161 
10162 	single = ctl_is_single;
10163 	if (single)
10164 		num_target_port_groups = 1;
10165 	else
10166 		num_target_port_groups = NUM_TARGET_PORT_GROUPS;
10167 	num_target_ports = 0;
10168 	iid_len = 0;
10169 	id_len = 0;
10170 	mtx_lock(&softc->ctl_lock);
10171 	STAILQ_FOREACH(port, &softc->port_list, links) {
10172 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
10173 			continue;
10174 		if (lun != NULL &&
10175 		    ctl_map_lun_back(port->targ_port, lun->lun) >=
10176 		    CTL_MAX_LUNS)
10177 			continue;
10178 		num_target_ports++;
10179 		if (port->init_devid)
10180 			iid_len += port->init_devid->len;
10181 		if (port->port_devid)
10182 			id_len += port->port_devid->len;
10183 	}
10184 	mtx_unlock(&softc->ctl_lock);
10185 
10186 	data_len = sizeof(struct scsi_vpd_scsi_ports) + num_target_port_groups *
10187 	    num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
10188 	     sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
10189 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10190 	sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
10191 	ctsio->kern_sg_entries = 0;
10192 
10193 	if (data_len < alloc_len) {
10194 		ctsio->residual = alloc_len - data_len;
10195 		ctsio->kern_data_len = data_len;
10196 		ctsio->kern_total_len = data_len;
10197 	} else {
10198 		ctsio->residual = 0;
10199 		ctsio->kern_data_len = alloc_len;
10200 		ctsio->kern_total_len = alloc_len;
10201 	}
10202 	ctsio->kern_data_resid = 0;
10203 	ctsio->kern_rel_offset = 0;
10204 	ctsio->kern_sg_entries = 0;
10205 
10206 	/*
10207 	 * The control device is always connected.  The disk device, on the
10208 	 * other hand, may not be online all the time.  Need to change this
10209 	 * to figure out whether the disk device is actually online or not.
10210 	 */
10211 	if (lun != NULL)
10212 		sp->device = (SID_QUAL_LU_CONNECTED << 5) |
10213 				  lun->be_lun->lun_type;
10214 	else
10215 		sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10216 
10217 	sp->page_code = SVPD_SCSI_PORTS;
10218 	scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
10219 	    sp->page_length);
10220 	pd = &sp->design[0];
10221 
10222 	mtx_lock(&softc->ctl_lock);
10223 	if (softc->flags & CTL_FLAG_MASTER_SHELF)
10224 		pg = 0;
10225 	else
10226 		pg = 1;
10227 	for (g = 0; g < num_target_port_groups; g++) {
10228 		STAILQ_FOREACH(port, &softc->port_list, links) {
10229 			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
10230 				continue;
10231 			if (lun != NULL &&
10232 			    ctl_map_lun_back(port->targ_port, lun->lun) >=
10233 			    CTL_MAX_LUNS)
10234 				continue;
10235 			p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
10236 			scsi_ulto2b(p, pd->relative_port_id);
10237 			if (port->init_devid && g == pg) {
10238 				iid_len = port->init_devid->len;
10239 				memcpy(pd->initiator_transportid,
10240 				    port->init_devid->data, port->init_devid->len);
10241 			} else
10242 				iid_len = 0;
10243 			scsi_ulto2b(iid_len, pd->initiator_transportid_length);
10244 			pdc = (struct scsi_vpd_port_designation_cont *)
10245 			    (&pd->initiator_transportid[iid_len]);
10246 			if (port->port_devid && g == pg) {
10247 				id_len = port->port_devid->len;
10248 				memcpy(pdc->target_port_descriptors,
10249 				    port->port_devid->data, port->port_devid->len);
10250 			} else
10251 				id_len = 0;
10252 			scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
10253 			pd = (struct scsi_vpd_port_designation *)
10254 			    ((uint8_t *)pdc->target_port_descriptors + id_len);
10255 		}
10256 	}
10257 	mtx_unlock(&softc->ctl_lock);
10258 
10259 	ctsio->scsi_status = SCSI_STATUS_OK;
10260 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10261 	ctsio->be_move_done = ctl_config_move_done;
10262 	ctl_datamove((union ctl_io *)ctsio);
10263 
10264 	return (CTL_RETVAL_COMPLETE);
10265 }
10266 
10267 static int
10268 ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
10269 {
10270 	struct scsi_vpd_block_limits *bl_ptr;
10271 	struct ctl_lun *lun;
10272 	int bs;
10273 
10274 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10275 
10276 	ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
10277 	bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
10278 	ctsio->kern_sg_entries = 0;
10279 
10280 	if (sizeof(*bl_ptr) < alloc_len) {
10281 		ctsio->residual = alloc_len - sizeof(*bl_ptr);
10282 		ctsio->kern_data_len = sizeof(*bl_ptr);
10283 		ctsio->kern_total_len = sizeof(*bl_ptr);
10284 	} else {
10285 		ctsio->residual = 0;
10286 		ctsio->kern_data_len = alloc_len;
10287 		ctsio->kern_total_len = alloc_len;
10288 	}
10289 	ctsio->kern_data_resid = 0;
10290 	ctsio->kern_rel_offset = 0;
10291 	ctsio->kern_sg_entries = 0;
10292 
10293 	/*
10294 	 * The control device is always connected.  The disk device, on the
10295 	 * other hand, may not be online all the time.  Need to change this
10296 	 * to figure out whether the disk device is actually online or not.
10297 	 */
10298 	if (lun != NULL)
10299 		bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10300 				  lun->be_lun->lun_type;
10301 	else
10302 		bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10303 
10304 	bl_ptr->page_code = SVPD_BLOCK_LIMITS;
10305 	scsi_ulto2b(sizeof(*bl_ptr), bl_ptr->page_length);
10306 	bl_ptr->max_cmp_write_len = 0xff;
10307 	scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
10308 	if (lun != NULL) {
10309 		bs = lun->be_lun->blocksize;
10310 		scsi_ulto4b(MAXPHYS / bs, bl_ptr->opt_txfer_len);
10311 		if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10312 			scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_lba_cnt);
10313 			scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_blk_cnt);
10314 			if (lun->be_lun->pblockexp != 0) {
10315 				scsi_ulto4b((1 << lun->be_lun->pblockexp),
10316 				    bl_ptr->opt_unmap_grain);
10317 				scsi_ulto4b(0x80000000 | lun->be_lun->pblockoff,
10318 				    bl_ptr->unmap_grain_align);
10319 			}
10320 		}
10321 	}
10322 	scsi_u64to8b(UINT64_MAX, bl_ptr->max_write_same_length);
10323 
10324 	ctsio->scsi_status = SCSI_STATUS_OK;
10325 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10326 	ctsio->be_move_done = ctl_config_move_done;
10327 	ctl_datamove((union ctl_io *)ctsio);
10328 
10329 	return (CTL_RETVAL_COMPLETE);
10330 }
10331 
10332 static int
10333 ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
10334 {
10335 	struct scsi_vpd_block_device_characteristics *bdc_ptr;
10336 	struct ctl_lun *lun;
10337 
10338 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10339 
10340 	ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
10341 	bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
10342 	ctsio->kern_sg_entries = 0;
10343 
10344 	if (sizeof(*bdc_ptr) < alloc_len) {
10345 		ctsio->residual = alloc_len - sizeof(*bdc_ptr);
10346 		ctsio->kern_data_len = sizeof(*bdc_ptr);
10347 		ctsio->kern_total_len = sizeof(*bdc_ptr);
10348 	} else {
10349 		ctsio->residual = 0;
10350 		ctsio->kern_data_len = alloc_len;
10351 		ctsio->kern_total_len = alloc_len;
10352 	}
10353 	ctsio->kern_data_resid = 0;
10354 	ctsio->kern_rel_offset = 0;
10355 	ctsio->kern_sg_entries = 0;
10356 
10357 	/*
10358 	 * The control device is always connected.  The disk device, on the
10359 	 * other hand, may not be online all the time.  Need to change this
10360 	 * to figure out whether the disk device is actually online or not.
10361 	 */
10362 	if (lun != NULL)
10363 		bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10364 				  lun->be_lun->lun_type;
10365 	else
10366 		bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10367 	bdc_ptr->page_code = SVPD_BDC;
10368 	scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
10369 	scsi_ulto2b(SVPD_NON_ROTATING, bdc_ptr->medium_rotation_rate);
10370 	bdc_ptr->flags = SVPD_FUAB | SVPD_VBULS;
10371 
10372 	ctsio->scsi_status = SCSI_STATUS_OK;
10373 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10374 	ctsio->be_move_done = ctl_config_move_done;
10375 	ctl_datamove((union ctl_io *)ctsio);
10376 
10377 	return (CTL_RETVAL_COMPLETE);
10378 }
10379 
10380 static int
10381 ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
10382 {
10383 	struct scsi_vpd_logical_block_prov *lbp_ptr;
10384 	struct ctl_lun *lun;
10385 
10386 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10387 
10388 	ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
10389 	lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
10390 	ctsio->kern_sg_entries = 0;
10391 
10392 	if (sizeof(*lbp_ptr) < alloc_len) {
10393 		ctsio->residual = alloc_len - sizeof(*lbp_ptr);
10394 		ctsio->kern_data_len = sizeof(*lbp_ptr);
10395 		ctsio->kern_total_len = sizeof(*lbp_ptr);
10396 	} else {
10397 		ctsio->residual = 0;
10398 		ctsio->kern_data_len = alloc_len;
10399 		ctsio->kern_total_len = alloc_len;
10400 	}
10401 	ctsio->kern_data_resid = 0;
10402 	ctsio->kern_rel_offset = 0;
10403 	ctsio->kern_sg_entries = 0;
10404 
10405 	/*
10406 	 * The control device is always connected.  The disk device, on the
10407 	 * other hand, may not be online all the time.  Need to change this
10408 	 * to figure out whether the disk device is actually online or not.
10409 	 */
10410 	if (lun != NULL)
10411 		lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10412 				  lun->be_lun->lun_type;
10413 	else
10414 		lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10415 
10416 	lbp_ptr->page_code = SVPD_LBP;
10417 	scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
10418 	if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10419 		lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
10420 		    SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
10421 		lbp_ptr->prov_type = SVPD_LBP_RESOURCE;
10422 	}
10423 
10424 	ctsio->scsi_status = SCSI_STATUS_OK;
10425 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10426 	ctsio->be_move_done = ctl_config_move_done;
10427 	ctl_datamove((union ctl_io *)ctsio);
10428 
10429 	return (CTL_RETVAL_COMPLETE);
10430 }
10431 
10432 static int
10433 ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
10434 {
10435 	struct scsi_inquiry *cdb;
10436 	struct ctl_lun *lun;
10437 	int alloc_len, retval;
10438 
10439 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10440 	cdb = (struct scsi_inquiry *)ctsio->cdb;
10441 
10442 	retval = CTL_RETVAL_COMPLETE;
10443 
10444 	alloc_len = scsi_2btoul(cdb->length);
10445 
10446 	switch (cdb->page_code) {
10447 	case SVPD_SUPPORTED_PAGES:
10448 		retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
10449 		break;
10450 	case SVPD_UNIT_SERIAL_NUMBER:
10451 		retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
10452 		break;
10453 	case SVPD_DEVICE_ID:
10454 		retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
10455 		break;
10456 	case SVPD_EXTENDED_INQUIRY_DATA:
10457 		retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
10458 		break;
10459 	case SVPD_MODE_PAGE_POLICY:
10460 		retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
10461 		break;
10462 	case SVPD_SCSI_PORTS:
10463 		retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10464 		break;
10465 	case SVPD_SCSI_TPC:
10466 		retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
10467 		break;
10468 	case SVPD_BLOCK_LIMITS:
10469 		retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10470 		break;
10471 	case SVPD_BDC:
10472 		retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
10473 		break;
10474 	case SVPD_LBP:
10475 		retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10476 		break;
10477 	default:
10478 		ctl_set_invalid_field(ctsio,
10479 				      /*sks_valid*/ 1,
10480 				      /*command*/ 1,
10481 				      /*field*/ 2,
10482 				      /*bit_valid*/ 0,
10483 				      /*bit*/ 0);
10484 		ctl_done((union ctl_io *)ctsio);
10485 		retval = CTL_RETVAL_COMPLETE;
10486 		break;
10487 	}
10488 
10489 	return (retval);
10490 }
10491 
10492 static int
10493 ctl_inquiry_std(struct ctl_scsiio *ctsio)
10494 {
10495 	struct scsi_inquiry_data *inq_ptr;
10496 	struct scsi_inquiry *cdb;
10497 	struct ctl_softc *ctl_softc;
10498 	struct ctl_lun *lun;
10499 	char *val;
10500 	uint32_t alloc_len;
10501 	ctl_port_type port_type;
10502 
10503 	ctl_softc = control_softc;
10504 
10505 	/*
10506 	 * Figure out whether we're talking to a Fibre Channel port or not.
10507 	 * We treat the ioctl front end, and any SCSI adapters, as packetized
10508 	 * SCSI front ends.
10509 	 */
10510 	port_type = ctl_softc->ctl_ports[
10511 	    ctl_port_idx(ctsio->io_hdr.nexus.targ_port)]->port_type;
10512 	if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10513 		port_type = CTL_PORT_SCSI;
10514 
10515 	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10516 	cdb = (struct scsi_inquiry *)ctsio->cdb;
10517 	alloc_len = scsi_2btoul(cdb->length);
10518 
10519 	/*
10520 	 * We malloc the full inquiry data size here and fill it
10521 	 * in.  If the user only asks for less, we'll give him
10522 	 * that much.
10523 	 */
10524 	ctsio->kern_data_ptr = malloc(sizeof(*inq_ptr), M_CTL, M_WAITOK | M_ZERO);
10525 	inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10526 	ctsio->kern_sg_entries = 0;
10527 	ctsio->kern_data_resid = 0;
10528 	ctsio->kern_rel_offset = 0;
10529 
10530 	if (sizeof(*inq_ptr) < alloc_len) {
10531 		ctsio->residual = alloc_len - sizeof(*inq_ptr);
10532 		ctsio->kern_data_len = sizeof(*inq_ptr);
10533 		ctsio->kern_total_len = sizeof(*inq_ptr);
10534 	} else {
10535 		ctsio->residual = 0;
10536 		ctsio->kern_data_len = alloc_len;
10537 		ctsio->kern_total_len = alloc_len;
10538 	}
10539 
10540 	/*
10541 	 * If we have a LUN configured, report it as connected.  Otherwise,
10542 	 * report that it is offline or no device is supported, depending
10543 	 * on the value of inquiry_pq_no_lun.
10544 	 *
10545 	 * According to the spec (SPC-4 r34), the peripheral qualifier
10546 	 * SID_QUAL_LU_OFFLINE (001b) is used in the following scenario:
10547 	 *
10548 	 * "A peripheral device having the specified peripheral device type
10549 	 * is not connected to this logical unit. However, the device
10550 	 * server is capable of supporting the specified peripheral device
10551 	 * type on this logical unit."
10552 	 *
10553 	 * According to the same spec, the peripheral qualifier
10554 	 * SID_QUAL_BAD_LU (011b) is used in this scenario:
10555 	 *
10556 	 * "The device server is not capable of supporting a peripheral
10557 	 * device on this logical unit. For this peripheral qualifier the
10558 	 * peripheral device type shall be set to 1Fh. All other peripheral
10559 	 * device type values are reserved for this peripheral qualifier."
10560 	 *
10561 	 * Given the text, it would seem that we probably want to report that
10562 	 * the LUN is offline here.  There is no LUN connected, but we can
10563 	 * support a LUN at the given LUN number.
10564 	 *
10565 	 * In the real world, though, it sounds like things are a little
10566 	 * different:
10567 	 *
10568 	 * - Linux, when presented with a LUN with the offline peripheral
10569 	 *   qualifier, will create an sg driver instance for it.  So when
10570 	 *   you attach it to CTL, you wind up with a ton of sg driver
10571 	 *   instances.  (One for every LUN that Linux bothered to probe.)
10572 	 *   Linux does this despite the fact that it issues a REPORT LUNs
10573 	 *   to LUN 0 to get the inventory of supported LUNs.
10574 	 *
10575 	 * - There is other anecdotal evidence (from Emulex folks) about
10576 	 *   arrays that use the offline peripheral qualifier for LUNs that
10577 	 *   are on the "passive" path in an active/passive array.
10578 	 *
10579 	 * So the solution is provide a hopefully reasonable default
10580 	 * (return bad/no LUN) and allow the user to change the behavior
10581 	 * with a tunable/sysctl variable.
10582 	 */
10583 	if (lun != NULL)
10584 		inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10585 				  lun->be_lun->lun_type;
10586 	else if (ctl_softc->inquiry_pq_no_lun == 0)
10587 		inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10588 	else
10589 		inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10590 
10591 	/* RMB in byte 2 is 0 */
10592 	inq_ptr->version = SCSI_REV_SPC4;
10593 
10594 	/*
10595 	 * According to SAM-3, even if a device only supports a single
10596 	 * level of LUN addressing, it should still set the HISUP bit:
10597 	 *
10598 	 * 4.9.1 Logical unit numbers overview
10599 	 *
10600 	 * All logical unit number formats described in this standard are
10601 	 * hierarchical in structure even when only a single level in that
10602 	 * hierarchy is used. The HISUP bit shall be set to one in the
10603 	 * standard INQUIRY data (see SPC-2) when any logical unit number
10604 	 * format described in this standard is used.  Non-hierarchical
10605 	 * formats are outside the scope of this standard.
10606 	 *
10607 	 * Therefore we set the HiSup bit here.
10608 	 *
10609 	 * The reponse format is 2, per SPC-3.
10610 	 */
10611 	inq_ptr->response_format = SID_HiSup | 2;
10612 
10613 	inq_ptr->additional_length =
10614 	    offsetof(struct scsi_inquiry_data, vendor_specific1) -
10615 	    (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10616 	CTL_DEBUG_PRINT(("additional_length = %d\n",
10617 			 inq_ptr->additional_length));
10618 
10619 	inq_ptr->spc3_flags = SPC3_SID_3PC;
10620 	if (!ctl_is_single)
10621 		inq_ptr->spc3_flags |= SPC3_SID_TPGS_IMPLICIT;
10622 	/* 16 bit addressing */
10623 	if (port_type == CTL_PORT_SCSI)
10624 		inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10625 	/* XXX set the SID_MultiP bit here if we're actually going to
10626 	   respond on multiple ports */
10627 	inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10628 
10629 	/* 16 bit data bus, synchronous transfers */
10630 	if (port_type == CTL_PORT_SCSI)
10631 		inq_ptr->flags = SID_WBus16 | SID_Sync;
10632 	/*
10633 	 * XXX KDM do we want to support tagged queueing on the control
10634 	 * device at all?
10635 	 */
10636 	if ((lun == NULL)
10637 	 || (lun->be_lun->lun_type != T_PROCESSOR))
10638 		inq_ptr->flags |= SID_CmdQue;
10639 	/*
10640 	 * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10641 	 * We have 8 bytes for the vendor name, and 16 bytes for the device
10642 	 * name and 4 bytes for the revision.
10643 	 */
10644 	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10645 	    "vendor")) == NULL) {
10646 		strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10647 	} else {
10648 		memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10649 		strncpy(inq_ptr->vendor, val,
10650 		    min(sizeof(inq_ptr->vendor), strlen(val)));
10651 	}
10652 	if (lun == NULL) {
10653 		strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10654 		    sizeof(inq_ptr->product));
10655 	} else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10656 		switch (lun->be_lun->lun_type) {
10657 		case T_DIRECT:
10658 			strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10659 			    sizeof(inq_ptr->product));
10660 			break;
10661 		case T_PROCESSOR:
10662 			strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10663 			    sizeof(inq_ptr->product));
10664 			break;
10665 		default:
10666 			strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10667 			    sizeof(inq_ptr->product));
10668 			break;
10669 		}
10670 	} else {
10671 		memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10672 		strncpy(inq_ptr->product, val,
10673 		    min(sizeof(inq_ptr->product), strlen(val)));
10674 	}
10675 
10676 	/*
10677 	 * XXX make this a macro somewhere so it automatically gets
10678 	 * incremented when we make changes.
10679 	 */
10680 	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10681 	    "revision")) == NULL) {
10682 		strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10683 	} else {
10684 		memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10685 		strncpy(inq_ptr->revision, val,
10686 		    min(sizeof(inq_ptr->revision), strlen(val)));
10687 	}
10688 
10689 	/*
10690 	 * For parallel SCSI, we support double transition and single
10691 	 * transition clocking.  We also support QAS (Quick Arbitration
10692 	 * and Selection) and Information Unit transfers on both the
10693 	 * control and array devices.
10694 	 */
10695 	if (port_type == CTL_PORT_SCSI)
10696 		inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10697 				    SID_SPI_IUS;
10698 
10699 	/* SAM-5 (no version claimed) */
10700 	scsi_ulto2b(0x00A0, inq_ptr->version1);
10701 	/* SPC-4 (no version claimed) */
10702 	scsi_ulto2b(0x0460, inq_ptr->version2);
10703 	if (port_type == CTL_PORT_FC) {
10704 		/* FCP-2 ANSI INCITS.350:2003 */
10705 		scsi_ulto2b(0x0917, inq_ptr->version3);
10706 	} else if (port_type == CTL_PORT_SCSI) {
10707 		/* SPI-4 ANSI INCITS.362:200x */
10708 		scsi_ulto2b(0x0B56, inq_ptr->version3);
10709 	} else if (port_type == CTL_PORT_ISCSI) {
10710 		/* iSCSI (no version claimed) */
10711 		scsi_ulto2b(0x0960, inq_ptr->version3);
10712 	} else if (port_type == CTL_PORT_SAS) {
10713 		/* SAS (no version claimed) */
10714 		scsi_ulto2b(0x0BE0, inq_ptr->version3);
10715 	}
10716 
10717 	if (lun == NULL) {
10718 		/* SBC-3 (no version claimed) */
10719 		scsi_ulto2b(0x04C0, inq_ptr->version4);
10720 	} else {
10721 		switch (lun->be_lun->lun_type) {
10722 		case T_DIRECT:
10723 			/* SBC-3 (no version claimed) */
10724 			scsi_ulto2b(0x04C0, inq_ptr->version4);
10725 			break;
10726 		case T_PROCESSOR:
10727 		default:
10728 			break;
10729 		}
10730 	}
10731 
10732 	ctsio->scsi_status = SCSI_STATUS_OK;
10733 	if (ctsio->kern_data_len > 0) {
10734 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10735 		ctsio->be_move_done = ctl_config_move_done;
10736 		ctl_datamove((union ctl_io *)ctsio);
10737 	} else {
10738 		ctsio->io_hdr.status = CTL_SUCCESS;
10739 		ctl_done((union ctl_io *)ctsio);
10740 	}
10741 
10742 	return (CTL_RETVAL_COMPLETE);
10743 }
10744 
10745 int
10746 ctl_inquiry(struct ctl_scsiio *ctsio)
10747 {
10748 	struct scsi_inquiry *cdb;
10749 	int retval;
10750 
10751 	cdb = (struct scsi_inquiry *)ctsio->cdb;
10752 
10753 	retval = 0;
10754 
10755 	CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10756 
10757 	/*
10758 	 * Right now, we don't support the CmdDt inquiry information.
10759 	 * This would be nice to support in the future.  When we do
10760 	 * support it, we should change this test so that it checks to make
10761 	 * sure SI_EVPD and SI_CMDDT aren't both set at the same time.
10762 	 */
10763 #ifdef notyet
10764 	if (((cdb->byte2 & SI_EVPD)
10765 	 && (cdb->byte2 & SI_CMDDT)))
10766 #endif
10767 	if (cdb->byte2 & SI_CMDDT) {
10768 		/*
10769 		 * Point to the SI_CMDDT bit.  We might change this
10770 		 * when we support SI_CMDDT, but since both bits would be
10771 		 * "wrong", this should probably just stay as-is then.
10772 		 */
10773 		ctl_set_invalid_field(ctsio,
10774 				      /*sks_valid*/ 1,
10775 				      /*command*/ 1,
10776 				      /*field*/ 1,
10777 				      /*bit_valid*/ 1,
10778 				      /*bit*/ 1);
10779 		ctl_done((union ctl_io *)ctsio);
10780 		return (CTL_RETVAL_COMPLETE);
10781 	}
10782 	if (cdb->byte2 & SI_EVPD)
10783 		retval = ctl_inquiry_evpd(ctsio);
10784 #ifdef notyet
10785 	else if (cdb->byte2 & SI_CMDDT)
10786 		retval = ctl_inquiry_cmddt(ctsio);
10787 #endif
10788 	else
10789 		retval = ctl_inquiry_std(ctsio);
10790 
10791 	return (retval);
10792 }
10793 
10794 /*
10795  * For known CDB types, parse the LBA and length.
10796  */
10797 static int
10798 ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint32_t *len)
10799 {
10800 	if (io->io_hdr.io_type != CTL_IO_SCSI)
10801 		return (1);
10802 
10803 	switch (io->scsiio.cdb[0]) {
10804 	case COMPARE_AND_WRITE: {
10805 		struct scsi_compare_and_write *cdb;
10806 
10807 		cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10808 
10809 		*lba = scsi_8btou64(cdb->addr);
10810 		*len = cdb->length;
10811 		break;
10812 	}
10813 	case READ_6:
10814 	case WRITE_6: {
10815 		struct scsi_rw_6 *cdb;
10816 
10817 		cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10818 
10819 		*lba = scsi_3btoul(cdb->addr);
10820 		/* only 5 bits are valid in the most significant address byte */
10821 		*lba &= 0x1fffff;
10822 		*len = cdb->length;
10823 		break;
10824 	}
10825 	case READ_10:
10826 	case WRITE_10: {
10827 		struct scsi_rw_10 *cdb;
10828 
10829 		cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10830 
10831 		*lba = scsi_4btoul(cdb->addr);
10832 		*len = scsi_2btoul(cdb->length);
10833 		break;
10834 	}
10835 	case WRITE_VERIFY_10: {
10836 		struct scsi_write_verify_10 *cdb;
10837 
10838 		cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10839 
10840 		*lba = scsi_4btoul(cdb->addr);
10841 		*len = scsi_2btoul(cdb->length);
10842 		break;
10843 	}
10844 	case READ_12:
10845 	case WRITE_12: {
10846 		struct scsi_rw_12 *cdb;
10847 
10848 		cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10849 
10850 		*lba = scsi_4btoul(cdb->addr);
10851 		*len = scsi_4btoul(cdb->length);
10852 		break;
10853 	}
10854 	case WRITE_VERIFY_12: {
10855 		struct scsi_write_verify_12 *cdb;
10856 
10857 		cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10858 
10859 		*lba = scsi_4btoul(cdb->addr);
10860 		*len = scsi_4btoul(cdb->length);
10861 		break;
10862 	}
10863 	case READ_16:
10864 	case WRITE_16: {
10865 		struct scsi_rw_16 *cdb;
10866 
10867 		cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10868 
10869 		*lba = scsi_8btou64(cdb->addr);
10870 		*len = scsi_4btoul(cdb->length);
10871 		break;
10872 	}
10873 	case WRITE_VERIFY_16: {
10874 		struct scsi_write_verify_16 *cdb;
10875 
10876 		cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10877 
10878 
10879 		*lba = scsi_8btou64(cdb->addr);
10880 		*len = scsi_4btoul(cdb->length);
10881 		break;
10882 	}
10883 	case WRITE_SAME_10: {
10884 		struct scsi_write_same_10 *cdb;
10885 
10886 		cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10887 
10888 		*lba = scsi_4btoul(cdb->addr);
10889 		*len = scsi_2btoul(cdb->length);
10890 		break;
10891 	}
10892 	case WRITE_SAME_16: {
10893 		struct scsi_write_same_16 *cdb;
10894 
10895 		cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10896 
10897 		*lba = scsi_8btou64(cdb->addr);
10898 		*len = scsi_4btoul(cdb->length);
10899 		break;
10900 	}
10901 	case VERIFY_10: {
10902 		struct scsi_verify_10 *cdb;
10903 
10904 		cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10905 
10906 		*lba = scsi_4btoul(cdb->addr);
10907 		*len = scsi_2btoul(cdb->length);
10908 		break;
10909 	}
10910 	case VERIFY_12: {
10911 		struct scsi_verify_12 *cdb;
10912 
10913 		cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10914 
10915 		*lba = scsi_4btoul(cdb->addr);
10916 		*len = scsi_4btoul(cdb->length);
10917 		break;
10918 	}
10919 	case VERIFY_16: {
10920 		struct scsi_verify_16 *cdb;
10921 
10922 		cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10923 
10924 		*lba = scsi_8btou64(cdb->addr);
10925 		*len = scsi_4btoul(cdb->length);
10926 		break;
10927 	}
10928 	default:
10929 		return (1);
10930 		break; /* NOTREACHED */
10931 	}
10932 
10933 	return (0);
10934 }
10935 
10936 static ctl_action
10937 ctl_extent_check_lba(uint64_t lba1, uint32_t len1, uint64_t lba2, uint32_t len2)
10938 {
10939 	uint64_t endlba1, endlba2;
10940 
10941 	endlba1 = lba1 + len1 - 1;
10942 	endlba2 = lba2 + len2 - 1;
10943 
10944 	if ((endlba1 < lba2)
10945 	 || (endlba2 < lba1))
10946 		return (CTL_ACTION_PASS);
10947 	else
10948 		return (CTL_ACTION_BLOCK);
10949 }
10950 
10951 static ctl_action
10952 ctl_extent_check(union ctl_io *io1, union ctl_io *io2)
10953 {
10954 	uint64_t lba1, lba2;
10955 	uint32_t len1, len2;
10956 	int retval;
10957 
10958 	retval = ctl_get_lba_len(io1, &lba1, &len1);
10959 	if (retval != 0)
10960 		return (CTL_ACTION_ERROR);
10961 
10962 	retval = ctl_get_lba_len(io2, &lba2, &len2);
10963 	if (retval != 0)
10964 		return (CTL_ACTION_ERROR);
10965 
10966 	return (ctl_extent_check_lba(lba1, len1, lba2, len2));
10967 }
10968 
10969 static ctl_action
10970 ctl_check_for_blockage(union ctl_io *pending_io, union ctl_io *ooa_io)
10971 {
10972 	const struct ctl_cmd_entry *pending_entry, *ooa_entry;
10973 	ctl_serialize_action *serialize_row;
10974 
10975 	/*
10976 	 * The initiator attempted multiple untagged commands at the same
10977 	 * time.  Can't do that.
10978 	 */
10979 	if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10980 	 && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10981 	 && ((pending_io->io_hdr.nexus.targ_port ==
10982 	      ooa_io->io_hdr.nexus.targ_port)
10983 	  && (pending_io->io_hdr.nexus.initid.id ==
10984 	      ooa_io->io_hdr.nexus.initid.id))
10985 	 && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
10986 		return (CTL_ACTION_OVERLAP);
10987 
10988 	/*
10989 	 * The initiator attempted to send multiple tagged commands with
10990 	 * the same ID.  (It's fine if different initiators have the same
10991 	 * tag ID.)
10992 	 *
10993 	 * Even if all of those conditions are true, we don't kill the I/O
10994 	 * if the command ahead of us has been aborted.  We won't end up
10995 	 * sending it to the FETD, and it's perfectly legal to resend a
10996 	 * command with the same tag number as long as the previous
10997 	 * instance of this tag number has been aborted somehow.
10998 	 */
10999 	if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
11000 	 && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
11001 	 && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
11002 	 && ((pending_io->io_hdr.nexus.targ_port ==
11003 	      ooa_io->io_hdr.nexus.targ_port)
11004 	  && (pending_io->io_hdr.nexus.initid.id ==
11005 	      ooa_io->io_hdr.nexus.initid.id))
11006 	 && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
11007 		return (CTL_ACTION_OVERLAP_TAG);
11008 
11009 	/*
11010 	 * If we get a head of queue tag, SAM-3 says that we should
11011 	 * immediately execute it.
11012 	 *
11013 	 * What happens if this command would normally block for some other
11014 	 * reason?  e.g. a request sense with a head of queue tag
11015 	 * immediately after a write.  Normally that would block, but this
11016 	 * will result in its getting executed immediately...
11017 	 *
11018 	 * We currently return "pass" instead of "skip", so we'll end up
11019 	 * going through the rest of the queue to check for overlapped tags.
11020 	 *
11021 	 * XXX KDM check for other types of blockage first??
11022 	 */
11023 	if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
11024 		return (CTL_ACTION_PASS);
11025 
11026 	/*
11027 	 * Ordered tags have to block until all items ahead of them
11028 	 * have completed.  If we get called with an ordered tag, we always
11029 	 * block, if something else is ahead of us in the queue.
11030 	 */
11031 	if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
11032 		return (CTL_ACTION_BLOCK);
11033 
11034 	/*
11035 	 * Simple tags get blocked until all head of queue and ordered tags
11036 	 * ahead of them have completed.  I'm lumping untagged commands in
11037 	 * with simple tags here.  XXX KDM is that the right thing to do?
11038 	 */
11039 	if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
11040 	  || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
11041 	 && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
11042 	  || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
11043 		return (CTL_ACTION_BLOCK);
11044 
11045 	pending_entry = ctl_get_cmd_entry(&pending_io->scsiio);
11046 	ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio);
11047 
11048 	serialize_row = ctl_serialize_table[ooa_entry->seridx];
11049 
11050 	switch (serialize_row[pending_entry->seridx]) {
11051 	case CTL_SER_BLOCK:
11052 		return (CTL_ACTION_BLOCK);
11053 		break; /* NOTREACHED */
11054 	case CTL_SER_EXTENT:
11055 		return (ctl_extent_check(pending_io, ooa_io));
11056 		break; /* NOTREACHED */
11057 	case CTL_SER_PASS:
11058 		return (CTL_ACTION_PASS);
11059 		break; /* NOTREACHED */
11060 	case CTL_SER_SKIP:
11061 		return (CTL_ACTION_SKIP);
11062 		break;
11063 	default:
11064 		panic("invalid serialization value %d",
11065 		      serialize_row[pending_entry->seridx]);
11066 		break; /* NOTREACHED */
11067 	}
11068 
11069 	return (CTL_ACTION_ERROR);
11070 }
11071 
11072 /*
11073  * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
11074  * Assumptions:
11075  * - pending_io is generally either incoming, or on the blocked queue
11076  * - starting I/O is the I/O we want to start the check with.
11077  */
11078 static ctl_action
11079 ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
11080 	      union ctl_io *starting_io)
11081 {
11082 	union ctl_io *ooa_io;
11083 	ctl_action action;
11084 
11085 	mtx_assert(&lun->lun_lock, MA_OWNED);
11086 
11087 	/*
11088 	 * Run back along the OOA queue, starting with the current
11089 	 * blocked I/O and going through every I/O before it on the
11090 	 * queue.  If starting_io is NULL, we'll just end up returning
11091 	 * CTL_ACTION_PASS.
11092 	 */
11093 	for (ooa_io = starting_io; ooa_io != NULL;
11094 	     ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
11095 	     ooa_links)){
11096 
11097 		/*
11098 		 * This routine just checks to see whether
11099 		 * cur_blocked is blocked by ooa_io, which is ahead
11100 		 * of it in the queue.  It doesn't queue/dequeue
11101 		 * cur_blocked.
11102 		 */
11103 		action = ctl_check_for_blockage(pending_io, ooa_io);
11104 		switch (action) {
11105 		case CTL_ACTION_BLOCK:
11106 		case CTL_ACTION_OVERLAP:
11107 		case CTL_ACTION_OVERLAP_TAG:
11108 		case CTL_ACTION_SKIP:
11109 		case CTL_ACTION_ERROR:
11110 			return (action);
11111 			break; /* NOTREACHED */
11112 		case CTL_ACTION_PASS:
11113 			break;
11114 		default:
11115 			panic("invalid action %d", action);
11116 			break;  /* NOTREACHED */
11117 		}
11118 	}
11119 
11120 	return (CTL_ACTION_PASS);
11121 }
11122 
11123 /*
11124  * Assumptions:
11125  * - An I/O has just completed, and has been removed from the per-LUN OOA
11126  *   queue, so some items on the blocked queue may now be unblocked.
11127  */
11128 static int
11129 ctl_check_blocked(struct ctl_lun *lun)
11130 {
11131 	union ctl_io *cur_blocked, *next_blocked;
11132 
11133 	mtx_assert(&lun->lun_lock, MA_OWNED);
11134 
11135 	/*
11136 	 * Run forward from the head of the blocked queue, checking each
11137 	 * entry against the I/Os prior to it on the OOA queue to see if
11138 	 * there is still any blockage.
11139 	 *
11140 	 * We cannot use the TAILQ_FOREACH() macro, because it can't deal
11141 	 * with our removing a variable on it while it is traversing the
11142 	 * list.
11143 	 */
11144 	for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
11145 	     cur_blocked != NULL; cur_blocked = next_blocked) {
11146 		union ctl_io *prev_ooa;
11147 		ctl_action action;
11148 
11149 		next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
11150 							  blocked_links);
11151 
11152 		prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
11153 						      ctl_ooaq, ooa_links);
11154 
11155 		/*
11156 		 * If cur_blocked happens to be the first item in the OOA
11157 		 * queue now, prev_ooa will be NULL, and the action
11158 		 * returned will just be CTL_ACTION_PASS.
11159 		 */
11160 		action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
11161 
11162 		switch (action) {
11163 		case CTL_ACTION_BLOCK:
11164 			/* Nothing to do here, still blocked */
11165 			break;
11166 		case CTL_ACTION_OVERLAP:
11167 		case CTL_ACTION_OVERLAP_TAG:
11168 			/*
11169 			 * This shouldn't happen!  In theory we've already
11170 			 * checked this command for overlap...
11171 			 */
11172 			break;
11173 		case CTL_ACTION_PASS:
11174 		case CTL_ACTION_SKIP: {
11175 			struct ctl_softc *softc;
11176 			const struct ctl_cmd_entry *entry;
11177 			uint32_t initidx;
11178 			int isc_retval;
11179 
11180 			/*
11181 			 * The skip case shouldn't happen, this transaction
11182 			 * should have never made it onto the blocked queue.
11183 			 */
11184 			/*
11185 			 * This I/O is no longer blocked, we can remove it
11186 			 * from the blocked queue.  Since this is a TAILQ
11187 			 * (doubly linked list), we can do O(1) removals
11188 			 * from any place on the list.
11189 			 */
11190 			TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
11191 				     blocked_links);
11192 			cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11193 
11194 			if (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC){
11195 				/*
11196 				 * Need to send IO back to original side to
11197 				 * run
11198 				 */
11199 				union ctl_ha_msg msg_info;
11200 
11201 				msg_info.hdr.original_sc =
11202 					cur_blocked->io_hdr.original_sc;
11203 				msg_info.hdr.serializing_sc = cur_blocked;
11204 				msg_info.hdr.msg_type = CTL_MSG_R2R;
11205 				if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11206 				     &msg_info, sizeof(msg_info), 0)) >
11207 				     CTL_HA_STATUS_SUCCESS) {
11208 					printf("CTL:Check Blocked error from "
11209 					       "ctl_ha_msg_send %d\n",
11210 					       isc_retval);
11211 				}
11212 				break;
11213 			}
11214 			entry = ctl_get_cmd_entry(&cur_blocked->scsiio);
11215 			softc = control_softc;
11216 
11217 			initidx = ctl_get_initindex(&cur_blocked->io_hdr.nexus);
11218 
11219 			/*
11220 			 * Check this I/O for LUN state changes that may
11221 			 * have happened while this command was blocked.
11222 			 * The LUN state may have been changed by a command
11223 			 * ahead of us in the queue, so we need to re-check
11224 			 * for any states that can be caused by SCSI
11225 			 * commands.
11226 			 */
11227 			if (ctl_scsiio_lun_check(softc, lun, entry,
11228 						 &cur_blocked->scsiio) == 0) {
11229 				cur_blocked->io_hdr.flags |=
11230 				                      CTL_FLAG_IS_WAS_ON_RTR;
11231 				ctl_enqueue_rtr(cur_blocked);
11232 			} else
11233 				ctl_done(cur_blocked);
11234 			break;
11235 		}
11236 		default:
11237 			/*
11238 			 * This probably shouldn't happen -- we shouldn't
11239 			 * get CTL_ACTION_ERROR, or anything else.
11240 			 */
11241 			break;
11242 		}
11243 	}
11244 
11245 	return (CTL_RETVAL_COMPLETE);
11246 }
11247 
11248 /*
11249  * This routine (with one exception) checks LUN flags that can be set by
11250  * commands ahead of us in the OOA queue.  These flags have to be checked
11251  * when a command initially comes in, and when we pull a command off the
11252  * blocked queue and are preparing to execute it.  The reason we have to
11253  * check these flags for commands on the blocked queue is that the LUN
11254  * state may have been changed by a command ahead of us while we're on the
11255  * blocked queue.
11256  *
11257  * Ordering is somewhat important with these checks, so please pay
11258  * careful attention to the placement of any new checks.
11259  */
11260 static int
11261 ctl_scsiio_lun_check(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
11262     const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11263 {
11264 	int retval;
11265 
11266 	retval = 0;
11267 
11268 	mtx_assert(&lun->lun_lock, MA_OWNED);
11269 
11270 	/*
11271 	 * If this shelf is a secondary shelf controller, we have to reject
11272 	 * any media access commands.
11273 	 */
11274 #if 0
11275 	/* No longer needed for HA */
11276 	if (((ctl_softc->flags & CTL_FLAG_MASTER_SHELF) == 0)
11277 	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_SECONDARY) == 0)) {
11278 		ctl_set_lun_standby(ctsio);
11279 		retval = 1;
11280 		goto bailout;
11281 	}
11282 #endif
11283 
11284 	/*
11285 	 * Check for a reservation conflict.  If this command isn't allowed
11286 	 * even on reserved LUNs, and if this initiator isn't the one who
11287 	 * reserved us, reject the command with a reservation conflict.
11288 	 */
11289 	if ((lun->flags & CTL_LUN_RESERVED)
11290 	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11291 		if ((ctsio->io_hdr.nexus.initid.id != lun->rsv_nexus.initid.id)
11292 		 || (ctsio->io_hdr.nexus.targ_port != lun->rsv_nexus.targ_port)
11293 		 || (ctsio->io_hdr.nexus.targ_target.id !=
11294 		     lun->rsv_nexus.targ_target.id)) {
11295 			ctsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
11296 			ctsio->io_hdr.status = CTL_SCSI_ERROR;
11297 			retval = 1;
11298 			goto bailout;
11299 		}
11300 	}
11301 
11302 	if ( (lun->flags & CTL_LUN_PR_RESERVED)
11303 	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV) == 0)) {
11304 		uint32_t residx;
11305 
11306 		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
11307 		/*
11308 		 * if we aren't registered or it's a res holder type
11309 		 * reservation and this isn't the res holder then set a
11310 		 * conflict.
11311 		 * NOTE: Commands which might be allowed on write exclusive
11312 		 * type reservations are checked in the particular command
11313 		 * for a conflict. Read and SSU are the only ones.
11314 		 */
11315 		if (!lun->per_res[residx].registered
11316 		 || (residx != lun->pr_res_idx && lun->res_type < 4)) {
11317 			ctsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
11318 			ctsio->io_hdr.status = CTL_SCSI_ERROR;
11319 			retval = 1;
11320 			goto bailout;
11321 		}
11322 
11323 	}
11324 
11325 	if ((lun->flags & CTL_LUN_OFFLINE)
11326 	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_OFFLINE) == 0)) {
11327 		ctl_set_lun_not_ready(ctsio);
11328 		retval = 1;
11329 		goto bailout;
11330 	}
11331 
11332 	/*
11333 	 * If the LUN is stopped, see if this particular command is allowed
11334 	 * for a stopped lun.  Otherwise, reject it with 0x04,0x02.
11335 	 */
11336 	if ((lun->flags & CTL_LUN_STOPPED)
11337 	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_STOPPED) == 0)) {
11338 		/* "Logical unit not ready, initializing cmd. required" */
11339 		ctl_set_lun_stopped(ctsio);
11340 		retval = 1;
11341 		goto bailout;
11342 	}
11343 
11344 	if ((lun->flags & CTL_LUN_INOPERABLE)
11345 	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_INOPERABLE) == 0)) {
11346 		/* "Medium format corrupted" */
11347 		ctl_set_medium_format_corrupted(ctsio);
11348 		retval = 1;
11349 		goto bailout;
11350 	}
11351 
11352 bailout:
11353 	return (retval);
11354 
11355 }
11356 
11357 static void
11358 ctl_failover_io(union ctl_io *io, int have_lock)
11359 {
11360 	ctl_set_busy(&io->scsiio);
11361 	ctl_done(io);
11362 }
11363 
11364 static void
11365 ctl_failover(void)
11366 {
11367 	struct ctl_lun *lun;
11368 	struct ctl_softc *ctl_softc;
11369 	union ctl_io *next_io, *pending_io;
11370 	union ctl_io *io;
11371 	int lun_idx;
11372 	int i;
11373 
11374 	ctl_softc = control_softc;
11375 
11376 	mtx_lock(&ctl_softc->ctl_lock);
11377 	/*
11378 	 * Remove any cmds from the other SC from the rtr queue.  These
11379 	 * will obviously only be for LUNs for which we're the primary.
11380 	 * We can't send status or get/send data for these commands.
11381 	 * Since they haven't been executed yet, we can just remove them.
11382 	 * We'll either abort them or delete them below, depending on
11383 	 * which HA mode we're in.
11384 	 */
11385 #ifdef notyet
11386 	mtx_lock(&ctl_softc->queue_lock);
11387 	for (io = (union ctl_io *)STAILQ_FIRST(&ctl_softc->rtr_queue);
11388 	     io != NULL; io = next_io) {
11389 		next_io = (union ctl_io *)STAILQ_NEXT(&io->io_hdr, links);
11390 		if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11391 			STAILQ_REMOVE(&ctl_softc->rtr_queue, &io->io_hdr,
11392 				      ctl_io_hdr, links);
11393 	}
11394 	mtx_unlock(&ctl_softc->queue_lock);
11395 #endif
11396 
11397 	for (lun_idx=0; lun_idx < ctl_softc->num_luns; lun_idx++) {
11398 		lun = ctl_softc->ctl_luns[lun_idx];
11399 		if (lun==NULL)
11400 			continue;
11401 
11402 		/*
11403 		 * Processor LUNs are primary on both sides.
11404 		 * XXX will this always be true?
11405 		 */
11406 		if (lun->be_lun->lun_type == T_PROCESSOR)
11407 			continue;
11408 
11409 		if ((lun->flags & CTL_LUN_PRIMARY_SC)
11410 		 && (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11411 			printf("FAILOVER: primary lun %d\n", lun_idx);
11412 		        /*
11413 			 * Remove all commands from the other SC. First from the
11414 			 * blocked queue then from the ooa queue. Once we have
11415 			 * removed them. Call ctl_check_blocked to see if there
11416 			 * is anything that can run.
11417 			 */
11418 			for (io = (union ctl_io *)TAILQ_FIRST(
11419 			     &lun->blocked_queue); io != NULL; io = next_io) {
11420 
11421 		        	next_io = (union ctl_io *)TAILQ_NEXT(
11422 				    &io->io_hdr, blocked_links);
11423 
11424 				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11425 					TAILQ_REMOVE(&lun->blocked_queue,
11426 						     &io->io_hdr,blocked_links);
11427 					io->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11428 					TAILQ_REMOVE(&lun->ooa_queue,
11429 						     &io->io_hdr, ooa_links);
11430 
11431 					ctl_free_io(io);
11432 				}
11433 			}
11434 
11435 			for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11436 	     		     io != NULL; io = next_io) {
11437 
11438 		        	next_io = (union ctl_io *)TAILQ_NEXT(
11439 				    &io->io_hdr, ooa_links);
11440 
11441 				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11442 
11443 					TAILQ_REMOVE(&lun->ooa_queue,
11444 						&io->io_hdr,
11445 					     	ooa_links);
11446 
11447 					ctl_free_io(io);
11448 				}
11449 			}
11450 			ctl_check_blocked(lun);
11451 		} else if ((lun->flags & CTL_LUN_PRIMARY_SC)
11452 			&& (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
11453 
11454 			printf("FAILOVER: primary lun %d\n", lun_idx);
11455 			/*
11456 			 * Abort all commands from the other SC.  We can't
11457 			 * send status back for them now.  These should get
11458 			 * cleaned up when they are completed or come out
11459 			 * for a datamove operation.
11460 			 */
11461 			for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11462 	     		     io != NULL; io = next_io) {
11463 		        	next_io = (union ctl_io *)TAILQ_NEXT(
11464 					&io->io_hdr, ooa_links);
11465 
11466 				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11467 					io->io_hdr.flags |= CTL_FLAG_ABORT;
11468 			}
11469 		} else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11470 			&& (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
11471 
11472 			printf("FAILOVER: secondary lun %d\n", lun_idx);
11473 
11474 			lun->flags |= CTL_LUN_PRIMARY_SC;
11475 
11476 			/*
11477 			 * We send all I/O that was sent to this controller
11478 			 * and redirected to the other side back with
11479 			 * busy status, and have the initiator retry it.
11480 			 * Figuring out how much data has been transferred,
11481 			 * etc. and picking up where we left off would be
11482 			 * very tricky.
11483 			 *
11484 			 * XXX KDM need to remove I/O from the blocked
11485 			 * queue as well!
11486 			 */
11487 			for (pending_io = (union ctl_io *)TAILQ_FIRST(
11488 			     &lun->ooa_queue); pending_io != NULL;
11489 			     pending_io = next_io) {
11490 
11491 				next_io =  (union ctl_io *)TAILQ_NEXT(
11492 					&pending_io->io_hdr, ooa_links);
11493 
11494 				pending_io->io_hdr.flags &=
11495 					~CTL_FLAG_SENT_2OTHER_SC;
11496 
11497 				if (pending_io->io_hdr.flags &
11498 				    CTL_FLAG_IO_ACTIVE) {
11499 					pending_io->io_hdr.flags |=
11500 						CTL_FLAG_FAILOVER;
11501 				} else {
11502 					ctl_set_busy(&pending_io->scsiio);
11503 					ctl_done(pending_io);
11504 				}
11505 			}
11506 
11507 			/*
11508 			 * Build Unit Attention
11509 			 */
11510 			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11511 				lun->pending_ua[i] |=
11512 				                     CTL_UA_ASYM_ACC_CHANGE;
11513 			}
11514 		} else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11515 			&& (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11516 			printf("FAILOVER: secondary lun %d\n", lun_idx);
11517 			/*
11518 			 * if the first io on the OOA is not on the RtR queue
11519 			 * add it.
11520 			 */
11521 			lun->flags |= CTL_LUN_PRIMARY_SC;
11522 
11523 			pending_io = (union ctl_io *)TAILQ_FIRST(
11524 			    &lun->ooa_queue);
11525 			if (pending_io==NULL) {
11526 				printf("Nothing on OOA queue\n");
11527 				continue;
11528 			}
11529 
11530 			pending_io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11531 			if ((pending_io->io_hdr.flags &
11532 			     CTL_FLAG_IS_WAS_ON_RTR) == 0) {
11533 				pending_io->io_hdr.flags |=
11534 				    CTL_FLAG_IS_WAS_ON_RTR;
11535 				ctl_enqueue_rtr(pending_io);
11536 			}
11537 #if 0
11538 			else
11539 			{
11540 				printf("Tag 0x%04x is running\n",
11541 				      pending_io->scsiio.tag_num);
11542 			}
11543 #endif
11544 
11545 			next_io = (union ctl_io *)TAILQ_NEXT(
11546 			    &pending_io->io_hdr, ooa_links);
11547 			for (pending_io=next_io; pending_io != NULL;
11548 			     pending_io = next_io) {
11549 				pending_io->io_hdr.flags &=
11550 				    ~CTL_FLAG_SENT_2OTHER_SC;
11551 				next_io = (union ctl_io *)TAILQ_NEXT(
11552 					&pending_io->io_hdr, ooa_links);
11553 				if (pending_io->io_hdr.flags &
11554 				    CTL_FLAG_IS_WAS_ON_RTR) {
11555 #if 0
11556 				        printf("Tag 0x%04x is running\n",
11557 				      		pending_io->scsiio.tag_num);
11558 #endif
11559 					continue;
11560 				}
11561 
11562 				switch (ctl_check_ooa(lun, pending_io,
11563 			            (union ctl_io *)TAILQ_PREV(
11564 				    &pending_io->io_hdr, ctl_ooaq,
11565 				    ooa_links))) {
11566 
11567 				case CTL_ACTION_BLOCK:
11568 					TAILQ_INSERT_TAIL(&lun->blocked_queue,
11569 							  &pending_io->io_hdr,
11570 							  blocked_links);
11571 					pending_io->io_hdr.flags |=
11572 					    CTL_FLAG_BLOCKED;
11573 					break;
11574 				case CTL_ACTION_PASS:
11575 				case CTL_ACTION_SKIP:
11576 					pending_io->io_hdr.flags |=
11577 					    CTL_FLAG_IS_WAS_ON_RTR;
11578 					ctl_enqueue_rtr(pending_io);
11579 					break;
11580 				case CTL_ACTION_OVERLAP:
11581 					ctl_set_overlapped_cmd(
11582 					    (struct ctl_scsiio *)pending_io);
11583 					ctl_done(pending_io);
11584 					break;
11585 				case CTL_ACTION_OVERLAP_TAG:
11586 					ctl_set_overlapped_tag(
11587 					    (struct ctl_scsiio *)pending_io,
11588 					    pending_io->scsiio.tag_num & 0xff);
11589 					ctl_done(pending_io);
11590 					break;
11591 				case CTL_ACTION_ERROR:
11592 				default:
11593 					ctl_set_internal_failure(
11594 						(struct ctl_scsiio *)pending_io,
11595 						0,  // sks_valid
11596 						0); //retry count
11597 					ctl_done(pending_io);
11598 					break;
11599 				}
11600 			}
11601 
11602 			/*
11603 			 * Build Unit Attention
11604 			 */
11605 			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11606 				lun->pending_ua[i] |=
11607 				                     CTL_UA_ASYM_ACC_CHANGE;
11608 			}
11609 		} else {
11610 			panic("Unhandled HA mode failover, LUN flags = %#x, "
11611 			      "ha_mode = #%x", lun->flags, ctl_softc->ha_mode);
11612 		}
11613 	}
11614 	ctl_pause_rtr = 0;
11615 	mtx_unlock(&ctl_softc->ctl_lock);
11616 }
11617 
11618 static int
11619 ctl_scsiio_precheck(struct ctl_softc *ctl_softc, struct ctl_scsiio *ctsio)
11620 {
11621 	struct ctl_lun *lun;
11622 	const struct ctl_cmd_entry *entry;
11623 	uint32_t initidx, targ_lun;
11624 	int retval;
11625 
11626 	retval = 0;
11627 
11628 	lun = NULL;
11629 
11630 	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11631 	if ((targ_lun < CTL_MAX_LUNS)
11632 	 && (ctl_softc->ctl_luns[targ_lun] != NULL)) {
11633 		lun = ctl_softc->ctl_luns[targ_lun];
11634 		/*
11635 		 * If the LUN is invalid, pretend that it doesn't exist.
11636 		 * It will go away as soon as all pending I/O has been
11637 		 * completed.
11638 		 */
11639 		if (lun->flags & CTL_LUN_DISABLED) {
11640 			lun = NULL;
11641 		} else {
11642 			ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
11643 			ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr =
11644 				lun->be_lun;
11645 			if (lun->be_lun->lun_type == T_PROCESSOR) {
11646 				ctsio->io_hdr.flags |= CTL_FLAG_CONTROL_DEV;
11647 			}
11648 
11649 			/*
11650 			 * Every I/O goes into the OOA queue for a
11651 			 * particular LUN, and stays there until completion.
11652 			 */
11653 			mtx_lock(&lun->lun_lock);
11654 			TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr,
11655 			    ooa_links);
11656 		}
11657 	} else {
11658 		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11659 		ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11660 	}
11661 
11662 	/* Get command entry and return error if it is unsuppotyed. */
11663 	entry = ctl_validate_command(ctsio);
11664 	if (entry == NULL) {
11665 		if (lun)
11666 			mtx_unlock(&lun->lun_lock);
11667 		return (retval);
11668 	}
11669 
11670 	ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11671 	ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11672 
11673 	/*
11674 	 * Check to see whether we can send this command to LUNs that don't
11675 	 * exist.  This should pretty much only be the case for inquiry
11676 	 * and request sense.  Further checks, below, really require having
11677 	 * a LUN, so we can't really check the command anymore.  Just put
11678 	 * it on the rtr queue.
11679 	 */
11680 	if (lun == NULL) {
11681 		if (entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) {
11682 			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11683 			ctl_enqueue_rtr((union ctl_io *)ctsio);
11684 			return (retval);
11685 		}
11686 
11687 		ctl_set_unsupported_lun(ctsio);
11688 		ctl_done((union ctl_io *)ctsio);
11689 		CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11690 		return (retval);
11691 	} else {
11692 		/*
11693 		 * Make sure we support this particular command on this LUN.
11694 		 * e.g., we don't support writes to the control LUN.
11695 		 */
11696 		if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11697 			mtx_unlock(&lun->lun_lock);
11698 			ctl_set_invalid_opcode(ctsio);
11699 			ctl_done((union ctl_io *)ctsio);
11700 			return (retval);
11701 		}
11702 	}
11703 
11704 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11705 
11706 #ifdef CTL_WITH_CA
11707 	/*
11708 	 * If we've got a request sense, it'll clear the contingent
11709 	 * allegiance condition.  Otherwise, if we have a CA condition for
11710 	 * this initiator, clear it, because it sent down a command other
11711 	 * than request sense.
11712 	 */
11713 	if ((ctsio->cdb[0] != REQUEST_SENSE)
11714 	 && (ctl_is_set(lun->have_ca, initidx)))
11715 		ctl_clear_mask(lun->have_ca, initidx);
11716 #endif
11717 
11718 	/*
11719 	 * If the command has this flag set, it handles its own unit
11720 	 * attention reporting, we shouldn't do anything.  Otherwise we
11721 	 * check for any pending unit attentions, and send them back to the
11722 	 * initiator.  We only do this when a command initially comes in,
11723 	 * not when we pull it off the blocked queue.
11724 	 *
11725 	 * According to SAM-3, section 5.3.2, the order that things get
11726 	 * presented back to the host is basically unit attentions caused
11727 	 * by some sort of reset event, busy status, reservation conflicts
11728 	 * or task set full, and finally any other status.
11729 	 *
11730 	 * One issue here is that some of the unit attentions we report
11731 	 * don't fall into the "reset" category (e.g. "reported luns data
11732 	 * has changed").  So reporting it here, before the reservation
11733 	 * check, may be technically wrong.  I guess the only thing to do
11734 	 * would be to check for and report the reset events here, and then
11735 	 * check for the other unit attention types after we check for a
11736 	 * reservation conflict.
11737 	 *
11738 	 * XXX KDM need to fix this
11739 	 */
11740 	if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11741 		ctl_ua_type ua_type;
11742 
11743 		ua_type = lun->pending_ua[initidx];
11744 		if (ua_type != CTL_UA_NONE) {
11745 			scsi_sense_data_type sense_format;
11746 
11747 			if (lun != NULL)
11748 				sense_format = (lun->flags &
11749 				    CTL_LUN_SENSE_DESC) ? SSD_TYPE_DESC :
11750 				    SSD_TYPE_FIXED;
11751 			else
11752 				sense_format = SSD_TYPE_FIXED;
11753 
11754 			ua_type = ctl_build_ua(ua_type, &ctsio->sense_data,
11755 					       sense_format);
11756 			if (ua_type != CTL_UA_NONE) {
11757 				ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11758 				ctsio->io_hdr.status = CTL_SCSI_ERROR |
11759 						       CTL_AUTOSENSE;
11760 				ctsio->sense_len = SSD_FULL_SIZE;
11761 				lun->pending_ua[initidx] &= ~ua_type;
11762 				mtx_unlock(&lun->lun_lock);
11763 				ctl_done((union ctl_io *)ctsio);
11764 				return (retval);
11765 			}
11766 		}
11767 	}
11768 
11769 
11770 	if (ctl_scsiio_lun_check(ctl_softc, lun, entry, ctsio) != 0) {
11771 		mtx_unlock(&lun->lun_lock);
11772 		ctl_done((union ctl_io *)ctsio);
11773 		return (retval);
11774 	}
11775 
11776 	/*
11777 	 * XXX CHD this is where we want to send IO to other side if
11778 	 * this LUN is secondary on this SC. We will need to make a copy
11779 	 * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11780 	 * the copy we send as FROM_OTHER.
11781 	 * We also need to stuff the address of the original IO so we can
11782 	 * find it easily. Something similar will need be done on the other
11783 	 * side so when we are done we can find the copy.
11784 	 */
11785 	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11786 		union ctl_ha_msg msg_info;
11787 		int isc_retval;
11788 
11789 		ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11790 
11791 		msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11792 		msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11793 #if 0
11794 		printf("1. ctsio %p\n", ctsio);
11795 #endif
11796 		msg_info.hdr.serializing_sc = NULL;
11797 		msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11798 		msg_info.scsi.tag_num = ctsio->tag_num;
11799 		msg_info.scsi.tag_type = ctsio->tag_type;
11800 		memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11801 
11802 		ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11803 
11804 		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11805 		    (void *)&msg_info, sizeof(msg_info), 0)) >
11806 		    CTL_HA_STATUS_SUCCESS) {
11807 			printf("CTL:precheck, ctl_ha_msg_send returned %d\n",
11808 			       isc_retval);
11809 			printf("CTL:opcode is %x\n", ctsio->cdb[0]);
11810 		} else {
11811 #if 0
11812 			printf("CTL:Precheck sent msg, opcode is %x\n",opcode);
11813 #endif
11814 		}
11815 
11816 		/*
11817 		 * XXX KDM this I/O is off the incoming queue, but hasn't
11818 		 * been inserted on any other queue.  We may need to come
11819 		 * up with a holding queue while we wait for serialization
11820 		 * so that we have an idea of what we're waiting for from
11821 		 * the other side.
11822 		 */
11823 		mtx_unlock(&lun->lun_lock);
11824 		return (retval);
11825 	}
11826 
11827 	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11828 			      (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11829 			      ctl_ooaq, ooa_links))) {
11830 	case CTL_ACTION_BLOCK:
11831 		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11832 		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11833 				  blocked_links);
11834 		mtx_unlock(&lun->lun_lock);
11835 		return (retval);
11836 	case CTL_ACTION_PASS:
11837 	case CTL_ACTION_SKIP:
11838 		ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11839 		mtx_unlock(&lun->lun_lock);
11840 		ctl_enqueue_rtr((union ctl_io *)ctsio);
11841 		break;
11842 	case CTL_ACTION_OVERLAP:
11843 		mtx_unlock(&lun->lun_lock);
11844 		ctl_set_overlapped_cmd(ctsio);
11845 		ctl_done((union ctl_io *)ctsio);
11846 		break;
11847 	case CTL_ACTION_OVERLAP_TAG:
11848 		mtx_unlock(&lun->lun_lock);
11849 		ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11850 		ctl_done((union ctl_io *)ctsio);
11851 		break;
11852 	case CTL_ACTION_ERROR:
11853 	default:
11854 		mtx_unlock(&lun->lun_lock);
11855 		ctl_set_internal_failure(ctsio,
11856 					 /*sks_valid*/ 0,
11857 					 /*retry_count*/ 0);
11858 		ctl_done((union ctl_io *)ctsio);
11859 		break;
11860 	}
11861 	return (retval);
11862 }
11863 
11864 const struct ctl_cmd_entry *
11865 ctl_get_cmd_entry(struct ctl_scsiio *ctsio)
11866 {
11867 	const struct ctl_cmd_entry *entry;
11868 	int service_action;
11869 
11870 	entry = &ctl_cmd_table[ctsio->cdb[0]];
11871 	if (entry->flags & CTL_CMD_FLAG_SA5) {
11872 		service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11873 		entry = &((const struct ctl_cmd_entry *)
11874 		    entry->execute)[service_action];
11875 	}
11876 	return (entry);
11877 }
11878 
11879 const struct ctl_cmd_entry *
11880 ctl_validate_command(struct ctl_scsiio *ctsio)
11881 {
11882 	const struct ctl_cmd_entry *entry;
11883 	int i;
11884 	uint8_t diff;
11885 
11886 	entry = ctl_get_cmd_entry(ctsio);
11887 	if (entry->execute == NULL) {
11888 		ctl_set_invalid_opcode(ctsio);
11889 		ctl_done((union ctl_io *)ctsio);
11890 		return (NULL);
11891 	}
11892 	KASSERT(entry->length > 0,
11893 	    ("Not defined length for command 0x%02x/0x%02x",
11894 	     ctsio->cdb[0], ctsio->cdb[1]));
11895 	for (i = 1; i < entry->length; i++) {
11896 		diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11897 		if (diff == 0)
11898 			continue;
11899 		ctl_set_invalid_field(ctsio,
11900 				      /*sks_valid*/ 1,
11901 				      /*command*/ 1,
11902 				      /*field*/ i,
11903 				      /*bit_valid*/ 1,
11904 				      /*bit*/ fls(diff) - 1);
11905 		ctl_done((union ctl_io *)ctsio);
11906 		return (NULL);
11907 	}
11908 	return (entry);
11909 }
11910 
11911 static int
11912 ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11913 {
11914 
11915 	switch (lun_type) {
11916 	case T_PROCESSOR:
11917 		if (((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0) &&
11918 		    ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11919 			return (0);
11920 		break;
11921 	case T_DIRECT:
11922 		if (((entry->flags & CTL_CMD_FLAG_OK_ON_SLUN) == 0) &&
11923 		    ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11924 			return (0);
11925 		break;
11926 	default:
11927 		return (0);
11928 	}
11929 	return (1);
11930 }
11931 
11932 static int
11933 ctl_scsiio(struct ctl_scsiio *ctsio)
11934 {
11935 	int retval;
11936 	const struct ctl_cmd_entry *entry;
11937 
11938 	retval = CTL_RETVAL_COMPLETE;
11939 
11940 	CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11941 
11942 	entry = ctl_get_cmd_entry(ctsio);
11943 
11944 	/*
11945 	 * If this I/O has been aborted, just send it straight to
11946 	 * ctl_done() without executing it.
11947 	 */
11948 	if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11949 		ctl_done((union ctl_io *)ctsio);
11950 		goto bailout;
11951 	}
11952 
11953 	/*
11954 	 * All the checks should have been handled by ctl_scsiio_precheck().
11955 	 * We should be clear now to just execute the I/O.
11956 	 */
11957 	retval = entry->execute(ctsio);
11958 
11959 bailout:
11960 	return (retval);
11961 }
11962 
11963 /*
11964  * Since we only implement one target right now, a bus reset simply resets
11965  * our single target.
11966  */
11967 static int
11968 ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io)
11969 {
11970 	return(ctl_target_reset(ctl_softc, io, CTL_UA_BUS_RESET));
11971 }
11972 
11973 static int
11974 ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
11975 		 ctl_ua_type ua_type)
11976 {
11977 	struct ctl_lun *lun;
11978 	int retval;
11979 
11980 	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11981 		union ctl_ha_msg msg_info;
11982 
11983 		io->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11984 		msg_info.hdr.nexus = io->io_hdr.nexus;
11985 		if (ua_type==CTL_UA_TARG_RESET)
11986 			msg_info.task.task_action = CTL_TASK_TARGET_RESET;
11987 		else
11988 			msg_info.task.task_action = CTL_TASK_BUS_RESET;
11989 		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11990 		msg_info.hdr.original_sc = NULL;
11991 		msg_info.hdr.serializing_sc = NULL;
11992 		if (CTL_HA_STATUS_SUCCESS != ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11993 		    (void *)&msg_info, sizeof(msg_info), 0)) {
11994 		}
11995 	}
11996 	retval = 0;
11997 
11998 	mtx_lock(&ctl_softc->ctl_lock);
11999 	STAILQ_FOREACH(lun, &ctl_softc->lun_list, links)
12000 		retval += ctl_lun_reset(lun, io, ua_type);
12001 	mtx_unlock(&ctl_softc->ctl_lock);
12002 
12003 	return (retval);
12004 }
12005 
12006 /*
12007  * The LUN should always be set.  The I/O is optional, and is used to
12008  * distinguish between I/Os sent by this initiator, and by other
12009  * initiators.  We set unit attention for initiators other than this one.
12010  * SAM-3 is vague on this point.  It does say that a unit attention should
12011  * be established for other initiators when a LUN is reset (see section
12012  * 5.7.3), but it doesn't specifically say that the unit attention should
12013  * be established for this particular initiator when a LUN is reset.  Here
12014  * is the relevant text, from SAM-3 rev 8:
12015  *
12016  * 5.7.2 When a SCSI initiator port aborts its own tasks
12017  *
12018  * When a SCSI initiator port causes its own task(s) to be aborted, no
12019  * notification that the task(s) have been aborted shall be returned to
12020  * the SCSI initiator port other than the completion response for the
12021  * command or task management function action that caused the task(s) to
12022  * be aborted and notification(s) associated with related effects of the
12023  * action (e.g., a reset unit attention condition).
12024  *
12025  * XXX KDM for now, we're setting unit attention for all initiators.
12026  */
12027 static int
12028 ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
12029 {
12030 	union ctl_io *xio;
12031 #if 0
12032 	uint32_t initindex;
12033 #endif
12034 	int i;
12035 
12036 	mtx_lock(&lun->lun_lock);
12037 	/*
12038 	 * Run through the OOA queue and abort each I/O.
12039 	 */
12040 #if 0
12041 	TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
12042 #endif
12043 	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12044 	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12045 		xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
12046 	}
12047 
12048 	/*
12049 	 * This version sets unit attention for every
12050 	 */
12051 #if 0
12052 	initindex = ctl_get_initindex(&io->io_hdr.nexus);
12053 	for (i = 0; i < CTL_MAX_INITIATORS; i++) {
12054 		if (initindex == i)
12055 			continue;
12056 		lun->pending_ua[i] |= ua_type;
12057 	}
12058 #endif
12059 
12060 	/*
12061 	 * A reset (any kind, really) clears reservations established with
12062 	 * RESERVE/RELEASE.  It does not clear reservations established
12063 	 * with PERSISTENT RESERVE OUT, but we don't support that at the
12064 	 * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
12065 	 * reservations made with the RESERVE/RELEASE commands, because
12066 	 * those commands are obsolete in SPC-3.
12067 	 */
12068 	lun->flags &= ~CTL_LUN_RESERVED;
12069 
12070 	for (i = 0; i < CTL_MAX_INITIATORS; i++) {
12071 #ifdef CTL_WITH_CA
12072 		ctl_clear_mask(lun->have_ca, i);
12073 #endif
12074 		lun->pending_ua[i] |= ua_type;
12075 	}
12076 	mtx_unlock(&lun->lun_lock);
12077 
12078 	return (0);
12079 }
12080 
12081 static void
12082 ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
12083     int other_sc)
12084 {
12085 	union ctl_io *xio;
12086 
12087 	mtx_assert(&lun->lun_lock, MA_OWNED);
12088 
12089 	/*
12090 	 * Run through the OOA queue and attempt to find the given I/O.
12091 	 * The target port, initiator ID, tag type and tag number have to
12092 	 * match the values that we got from the initiator.  If we have an
12093 	 * untagged command to abort, simply abort the first untagged command
12094 	 * we come to.  We only allow one untagged command at a time of course.
12095 	 */
12096 	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12097 	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12098 
12099 		if ((targ_port == UINT32_MAX ||
12100 		     targ_port == xio->io_hdr.nexus.targ_port) &&
12101 		    (init_id == UINT32_MAX ||
12102 		     init_id == xio->io_hdr.nexus.initid.id)) {
12103 			if (targ_port != xio->io_hdr.nexus.targ_port ||
12104 			    init_id != xio->io_hdr.nexus.initid.id)
12105 				xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
12106 			xio->io_hdr.flags |= CTL_FLAG_ABORT;
12107 			if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12108 				union ctl_ha_msg msg_info;
12109 
12110 				msg_info.hdr.nexus = xio->io_hdr.nexus;
12111 				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
12112 				msg_info.task.tag_num = xio->scsiio.tag_num;
12113 				msg_info.task.tag_type = xio->scsiio.tag_type;
12114 				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12115 				msg_info.hdr.original_sc = NULL;
12116 				msg_info.hdr.serializing_sc = NULL;
12117 				ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12118 				    (void *)&msg_info, sizeof(msg_info), 0);
12119 			}
12120 		}
12121 	}
12122 }
12123 
12124 static int
12125 ctl_abort_task_set(union ctl_io *io)
12126 {
12127 	struct ctl_softc *softc = control_softc;
12128 	struct ctl_lun *lun;
12129 	uint32_t targ_lun;
12130 
12131 	/*
12132 	 * Look up the LUN.
12133 	 */
12134 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12135 	mtx_lock(&softc->ctl_lock);
12136 	if ((targ_lun < CTL_MAX_LUNS) && (softc->ctl_luns[targ_lun] != NULL))
12137 		lun = softc->ctl_luns[targ_lun];
12138 	else {
12139 		mtx_unlock(&softc->ctl_lock);
12140 		return (1);
12141 	}
12142 
12143 	mtx_lock(&lun->lun_lock);
12144 	mtx_unlock(&softc->ctl_lock);
12145 	if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
12146 		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12147 		    io->io_hdr.nexus.initid.id,
12148 		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12149 	} else { /* CTL_TASK_CLEAR_TASK_SET */
12150 		ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
12151 		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12152 	}
12153 	mtx_unlock(&lun->lun_lock);
12154 	return (0);
12155 }
12156 
12157 static int
12158 ctl_i_t_nexus_reset(union ctl_io *io)
12159 {
12160 	struct ctl_softc *softc = control_softc;
12161 	struct ctl_lun *lun;
12162 	uint32_t initindex;
12163 
12164 	initindex = ctl_get_initindex(&io->io_hdr.nexus);
12165 	mtx_lock(&softc->ctl_lock);
12166 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
12167 		mtx_lock(&lun->lun_lock);
12168 		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12169 		    io->io_hdr.nexus.initid.id,
12170 		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12171 #ifdef CTL_WITH_CA
12172 		ctl_clear_mask(lun->have_ca, initindex);
12173 #endif
12174 		lun->pending_ua[initindex] |= CTL_UA_I_T_NEXUS_LOSS;
12175 		mtx_unlock(&lun->lun_lock);
12176 	}
12177 	mtx_unlock(&softc->ctl_lock);
12178 	return (0);
12179 }
12180 
12181 static int
12182 ctl_abort_task(union ctl_io *io)
12183 {
12184 	union ctl_io *xio;
12185 	struct ctl_lun *lun;
12186 	struct ctl_softc *ctl_softc;
12187 #if 0
12188 	struct sbuf sb;
12189 	char printbuf[128];
12190 #endif
12191 	int found;
12192 	uint32_t targ_lun;
12193 
12194 	ctl_softc = control_softc;
12195 	found = 0;
12196 
12197 	/*
12198 	 * Look up the LUN.
12199 	 */
12200 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12201 	mtx_lock(&ctl_softc->ctl_lock);
12202 	if ((targ_lun < CTL_MAX_LUNS)
12203 	 && (ctl_softc->ctl_luns[targ_lun] != NULL))
12204 		lun = ctl_softc->ctl_luns[targ_lun];
12205 	else {
12206 		mtx_unlock(&ctl_softc->ctl_lock);
12207 		return (1);
12208 	}
12209 
12210 #if 0
12211 	printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
12212 	       lun->lun, io->taskio.tag_num, io->taskio.tag_type);
12213 #endif
12214 
12215 	mtx_lock(&lun->lun_lock);
12216 	mtx_unlock(&ctl_softc->ctl_lock);
12217 	/*
12218 	 * Run through the OOA queue and attempt to find the given I/O.
12219 	 * The target port, initiator ID, tag type and tag number have to
12220 	 * match the values that we got from the initiator.  If we have an
12221 	 * untagged command to abort, simply abort the first untagged command
12222 	 * we come to.  We only allow one untagged command at a time of course.
12223 	 */
12224 #if 0
12225 	TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
12226 #endif
12227 	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12228 	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12229 #if 0
12230 		sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
12231 
12232 		sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
12233 			    lun->lun, xio->scsiio.tag_num,
12234 			    xio->scsiio.tag_type,
12235 			    (xio->io_hdr.blocked_links.tqe_prev
12236 			    == NULL) ? "" : " BLOCKED",
12237 			    (xio->io_hdr.flags &
12238 			    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
12239 			    (xio->io_hdr.flags &
12240 			    CTL_FLAG_ABORT) ? " ABORT" : "",
12241 			    (xio->io_hdr.flags &
12242 			    CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
12243 		ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
12244 		sbuf_finish(&sb);
12245 		printf("%s\n", sbuf_data(&sb));
12246 #endif
12247 
12248 		if ((xio->io_hdr.nexus.targ_port == io->io_hdr.nexus.targ_port)
12249 		 && (xio->io_hdr.nexus.initid.id ==
12250 		     io->io_hdr.nexus.initid.id)) {
12251 			/*
12252 			 * If the abort says that the task is untagged, the
12253 			 * task in the queue must be untagged.  Otherwise,
12254 			 * we just check to see whether the tag numbers
12255 			 * match.  This is because the QLogic firmware
12256 			 * doesn't pass back the tag type in an abort
12257 			 * request.
12258 			 */
12259 #if 0
12260 			if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
12261 			  && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
12262 			 || (xio->scsiio.tag_num == io->taskio.tag_num)) {
12263 #endif
12264 			/*
12265 			 * XXX KDM we've got problems with FC, because it
12266 			 * doesn't send down a tag type with aborts.  So we
12267 			 * can only really go by the tag number...
12268 			 * This may cause problems with parallel SCSI.
12269 			 * Need to figure that out!!
12270 			 */
12271 			if (xio->scsiio.tag_num == io->taskio.tag_num) {
12272 				xio->io_hdr.flags |= CTL_FLAG_ABORT;
12273 				found = 1;
12274 				if ((io->io_hdr.flags &
12275 				     CTL_FLAG_FROM_OTHER_SC) == 0 &&
12276 				    !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12277 					union ctl_ha_msg msg_info;
12278 
12279 					io->io_hdr.flags |=
12280 					                CTL_FLAG_SENT_2OTHER_SC;
12281 					msg_info.hdr.nexus = io->io_hdr.nexus;
12282 					msg_info.task.task_action =
12283 						CTL_TASK_ABORT_TASK;
12284 					msg_info.task.tag_num =
12285 						io->taskio.tag_num;
12286 					msg_info.task.tag_type =
12287 						io->taskio.tag_type;
12288 					msg_info.hdr.msg_type =
12289 						CTL_MSG_MANAGE_TASKS;
12290 					msg_info.hdr.original_sc = NULL;
12291 					msg_info.hdr.serializing_sc = NULL;
12292 #if 0
12293 					printf("Sent Abort to other side\n");
12294 #endif
12295 					if (CTL_HA_STATUS_SUCCESS !=
12296 					        ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12297 		    				(void *)&msg_info,
12298 						sizeof(msg_info), 0)) {
12299 					}
12300 				}
12301 #if 0
12302 				printf("ctl_abort_task: found I/O to abort\n");
12303 #endif
12304 				break;
12305 			}
12306 		}
12307 	}
12308 	mtx_unlock(&lun->lun_lock);
12309 
12310 	if (found == 0) {
12311 		/*
12312 		 * This isn't really an error.  It's entirely possible for
12313 		 * the abort and command completion to cross on the wire.
12314 		 * This is more of an informative/diagnostic error.
12315 		 */
12316 #if 0
12317 		printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
12318 		       "%d:%d:%d:%d tag %d type %d\n",
12319 		       io->io_hdr.nexus.initid.id,
12320 		       io->io_hdr.nexus.targ_port,
12321 		       io->io_hdr.nexus.targ_target.id,
12322 		       io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
12323 		       io->taskio.tag_type);
12324 #endif
12325 	}
12326 	return (0);
12327 }
12328 
12329 static void
12330 ctl_run_task(union ctl_io *io)
12331 {
12332 	struct ctl_softc *ctl_softc = control_softc;
12333 	int retval = 1;
12334 	const char *task_desc;
12335 
12336 	CTL_DEBUG_PRINT(("ctl_run_task\n"));
12337 
12338 	KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12339 	    ("ctl_run_task: Unextected io_type %d\n",
12340 	     io->io_hdr.io_type));
12341 
12342 	task_desc = ctl_scsi_task_string(&io->taskio);
12343 	if (task_desc != NULL) {
12344 #ifdef NEEDTOPORT
12345 		csevent_log(CSC_CTL | CSC_SHELF_SW |
12346 			    CTL_TASK_REPORT,
12347 			    csevent_LogType_Trace,
12348 			    csevent_Severity_Information,
12349 			    csevent_AlertLevel_Green,
12350 			    csevent_FRU_Firmware,
12351 			    csevent_FRU_Unknown,
12352 			    "CTL: received task: %s",task_desc);
12353 #endif
12354 	} else {
12355 #ifdef NEEDTOPORT
12356 		csevent_log(CSC_CTL | CSC_SHELF_SW |
12357 			    CTL_TASK_REPORT,
12358 			    csevent_LogType_Trace,
12359 			    csevent_Severity_Information,
12360 			    csevent_AlertLevel_Green,
12361 			    csevent_FRU_Firmware,
12362 			    csevent_FRU_Unknown,
12363 			    "CTL: received unknown task "
12364 			    "type: %d (%#x)",
12365 			    io->taskio.task_action,
12366 			    io->taskio.task_action);
12367 #endif
12368 	}
12369 	switch (io->taskio.task_action) {
12370 	case CTL_TASK_ABORT_TASK:
12371 		retval = ctl_abort_task(io);
12372 		break;
12373 	case CTL_TASK_ABORT_TASK_SET:
12374 	case CTL_TASK_CLEAR_TASK_SET:
12375 		retval = ctl_abort_task_set(io);
12376 		break;
12377 	case CTL_TASK_CLEAR_ACA:
12378 		break;
12379 	case CTL_TASK_I_T_NEXUS_RESET:
12380 		retval = ctl_i_t_nexus_reset(io);
12381 		break;
12382 	case CTL_TASK_LUN_RESET: {
12383 		struct ctl_lun *lun;
12384 		uint32_t targ_lun;
12385 
12386 		targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12387 		mtx_lock(&ctl_softc->ctl_lock);
12388 		if ((targ_lun < CTL_MAX_LUNS)
12389 		 && (ctl_softc->ctl_luns[targ_lun] != NULL))
12390 			lun = ctl_softc->ctl_luns[targ_lun];
12391 		else {
12392 			mtx_unlock(&ctl_softc->ctl_lock);
12393 			retval = 1;
12394 			break;
12395 		}
12396 
12397 		if (!(io->io_hdr.flags &
12398 		    CTL_FLAG_FROM_OTHER_SC)) {
12399 			union ctl_ha_msg msg_info;
12400 
12401 			io->io_hdr.flags |=
12402 				CTL_FLAG_SENT_2OTHER_SC;
12403 			msg_info.hdr.msg_type =
12404 				CTL_MSG_MANAGE_TASKS;
12405 			msg_info.hdr.nexus = io->io_hdr.nexus;
12406 			msg_info.task.task_action =
12407 				CTL_TASK_LUN_RESET;
12408 			msg_info.hdr.original_sc = NULL;
12409 			msg_info.hdr.serializing_sc = NULL;
12410 			if (CTL_HA_STATUS_SUCCESS !=
12411 			    ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12412 			    (void *)&msg_info,
12413 			    sizeof(msg_info), 0)) {
12414 			}
12415 		}
12416 
12417 		retval = ctl_lun_reset(lun, io,
12418 				       CTL_UA_LUN_RESET);
12419 		mtx_unlock(&ctl_softc->ctl_lock);
12420 		break;
12421 	}
12422 	case CTL_TASK_TARGET_RESET:
12423 		retval = ctl_target_reset(ctl_softc, io, CTL_UA_TARG_RESET);
12424 		break;
12425 	case CTL_TASK_BUS_RESET:
12426 		retval = ctl_bus_reset(ctl_softc, io);
12427 		break;
12428 	case CTL_TASK_PORT_LOGIN:
12429 		break;
12430 	case CTL_TASK_PORT_LOGOUT:
12431 		break;
12432 	default:
12433 		printf("ctl_run_task: got unknown task management event %d\n",
12434 		       io->taskio.task_action);
12435 		break;
12436 	}
12437 	if (retval == 0)
12438 		io->io_hdr.status = CTL_SUCCESS;
12439 	else
12440 		io->io_hdr.status = CTL_ERROR;
12441 	ctl_done(io);
12442 }
12443 
12444 /*
12445  * For HA operation.  Handle commands that come in from the other
12446  * controller.
12447  */
12448 static void
12449 ctl_handle_isc(union ctl_io *io)
12450 {
12451 	int free_io;
12452 	struct ctl_lun *lun;
12453 	struct ctl_softc *ctl_softc;
12454 	uint32_t targ_lun;
12455 
12456 	ctl_softc = control_softc;
12457 
12458 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12459 	lun = ctl_softc->ctl_luns[targ_lun];
12460 
12461 	switch (io->io_hdr.msg_type) {
12462 	case CTL_MSG_SERIALIZE:
12463 		free_io = ctl_serialize_other_sc_cmd(&io->scsiio);
12464 		break;
12465 	case CTL_MSG_R2R: {
12466 		const struct ctl_cmd_entry *entry;
12467 
12468 		/*
12469 		 * This is only used in SER_ONLY mode.
12470 		 */
12471 		free_io = 0;
12472 		entry = ctl_get_cmd_entry(&io->scsiio);
12473 		mtx_lock(&lun->lun_lock);
12474 		if (ctl_scsiio_lun_check(ctl_softc, lun,
12475 		    entry, (struct ctl_scsiio *)io) != 0) {
12476 			mtx_unlock(&lun->lun_lock);
12477 			ctl_done(io);
12478 			break;
12479 		}
12480 		io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12481 		mtx_unlock(&lun->lun_lock);
12482 		ctl_enqueue_rtr(io);
12483 		break;
12484 	}
12485 	case CTL_MSG_FINISH_IO:
12486 		if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
12487 			free_io = 0;
12488 			ctl_done(io);
12489 		} else {
12490 			free_io = 1;
12491 			mtx_lock(&lun->lun_lock);
12492 			TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr,
12493 				     ooa_links);
12494 			ctl_check_blocked(lun);
12495 			mtx_unlock(&lun->lun_lock);
12496 		}
12497 		break;
12498 	case CTL_MSG_PERS_ACTION:
12499 		ctl_hndl_per_res_out_on_other_sc(
12500 			(union ctl_ha_msg *)&io->presio.pr_msg);
12501 		free_io = 1;
12502 		break;
12503 	case CTL_MSG_BAD_JUJU:
12504 		free_io = 0;
12505 		ctl_done(io);
12506 		break;
12507 	case CTL_MSG_DATAMOVE:
12508 		/* Only used in XFER mode */
12509 		free_io = 0;
12510 		ctl_datamove_remote(io);
12511 		break;
12512 	case CTL_MSG_DATAMOVE_DONE:
12513 		/* Only used in XFER mode */
12514 		free_io = 0;
12515 		io->scsiio.be_move_done(io);
12516 		break;
12517 	default:
12518 		free_io = 1;
12519 		printf("%s: Invalid message type %d\n",
12520 		       __func__, io->io_hdr.msg_type);
12521 		break;
12522 	}
12523 	if (free_io)
12524 		ctl_free_io(io);
12525 
12526 }
12527 
12528 
12529 /*
12530  * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12531  * there is no match.
12532  */
12533 static ctl_lun_error_pattern
12534 ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12535 {
12536 	const struct ctl_cmd_entry *entry;
12537 	ctl_lun_error_pattern filtered_pattern, pattern;
12538 
12539 	pattern = desc->error_pattern;
12540 
12541 	/*
12542 	 * XXX KDM we need more data passed into this function to match a
12543 	 * custom pattern, and we actually need to implement custom pattern
12544 	 * matching.
12545 	 */
12546 	if (pattern & CTL_LUN_PAT_CMD)
12547 		return (CTL_LUN_PAT_CMD);
12548 
12549 	if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12550 		return (CTL_LUN_PAT_ANY);
12551 
12552 	entry = ctl_get_cmd_entry(ctsio);
12553 
12554 	filtered_pattern = entry->pattern & pattern;
12555 
12556 	/*
12557 	 * If the user requested specific flags in the pattern (e.g.
12558 	 * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12559 	 * flags.
12560 	 *
12561 	 * If the user did not specify any flags, it doesn't matter whether
12562 	 * or not the command supports the flags.
12563 	 */
12564 	if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12565 	     (pattern & ~CTL_LUN_PAT_MASK))
12566 		return (CTL_LUN_PAT_NONE);
12567 
12568 	/*
12569 	 * If the user asked for a range check, see if the requested LBA
12570 	 * range overlaps with this command's LBA range.
12571 	 */
12572 	if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12573 		uint64_t lba1;
12574 		uint32_t len1;
12575 		ctl_action action;
12576 		int retval;
12577 
12578 		retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12579 		if (retval != 0)
12580 			return (CTL_LUN_PAT_NONE);
12581 
12582 		action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12583 					      desc->lba_range.len);
12584 		/*
12585 		 * A "pass" means that the LBA ranges don't overlap, so
12586 		 * this doesn't match the user's range criteria.
12587 		 */
12588 		if (action == CTL_ACTION_PASS)
12589 			return (CTL_LUN_PAT_NONE);
12590 	}
12591 
12592 	return (filtered_pattern);
12593 }
12594 
12595 static void
12596 ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12597 {
12598 	struct ctl_error_desc *desc, *desc2;
12599 
12600 	mtx_assert(&lun->lun_lock, MA_OWNED);
12601 
12602 	STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12603 		ctl_lun_error_pattern pattern;
12604 		/*
12605 		 * Check to see whether this particular command matches
12606 		 * the pattern in the descriptor.
12607 		 */
12608 		pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12609 		if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12610 			continue;
12611 
12612 		switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12613 		case CTL_LUN_INJ_ABORTED:
12614 			ctl_set_aborted(&io->scsiio);
12615 			break;
12616 		case CTL_LUN_INJ_MEDIUM_ERR:
12617 			ctl_set_medium_error(&io->scsiio);
12618 			break;
12619 		case CTL_LUN_INJ_UA:
12620 			/* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12621 			 * OCCURRED */
12622 			ctl_set_ua(&io->scsiio, 0x29, 0x00);
12623 			break;
12624 		case CTL_LUN_INJ_CUSTOM:
12625 			/*
12626 			 * We're assuming the user knows what he is doing.
12627 			 * Just copy the sense information without doing
12628 			 * checks.
12629 			 */
12630 			bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12631 			      ctl_min(sizeof(desc->custom_sense),
12632 				      sizeof(io->scsiio.sense_data)));
12633 			io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12634 			io->scsiio.sense_len = SSD_FULL_SIZE;
12635 			io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12636 			break;
12637 		case CTL_LUN_INJ_NONE:
12638 		default:
12639 			/*
12640 			 * If this is an error injection type we don't know
12641 			 * about, clear the continuous flag (if it is set)
12642 			 * so it will get deleted below.
12643 			 */
12644 			desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12645 			break;
12646 		}
12647 		/*
12648 		 * By default, each error injection action is a one-shot
12649 		 */
12650 		if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12651 			continue;
12652 
12653 		STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12654 
12655 		free(desc, M_CTL);
12656 	}
12657 }
12658 
12659 #ifdef CTL_IO_DELAY
12660 static void
12661 ctl_datamove_timer_wakeup(void *arg)
12662 {
12663 	union ctl_io *io;
12664 
12665 	io = (union ctl_io *)arg;
12666 
12667 	ctl_datamove(io);
12668 }
12669 #endif /* CTL_IO_DELAY */
12670 
12671 void
12672 ctl_datamove(union ctl_io *io)
12673 {
12674 	void (*fe_datamove)(union ctl_io *io);
12675 
12676 	mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12677 
12678 	CTL_DEBUG_PRINT(("ctl_datamove\n"));
12679 
12680 #ifdef CTL_TIME_IO
12681 	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12682 		char str[256];
12683 		char path_str[64];
12684 		struct sbuf sb;
12685 
12686 		ctl_scsi_path_string(io, path_str, sizeof(path_str));
12687 		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12688 
12689 		sbuf_cat(&sb, path_str);
12690 		switch (io->io_hdr.io_type) {
12691 		case CTL_IO_SCSI:
12692 			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12693 			sbuf_printf(&sb, "\n");
12694 			sbuf_cat(&sb, path_str);
12695 			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12696 				    io->scsiio.tag_num, io->scsiio.tag_type);
12697 			break;
12698 		case CTL_IO_TASK:
12699 			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12700 				    "Tag Type: %d\n", io->taskio.task_action,
12701 				    io->taskio.tag_num, io->taskio.tag_type);
12702 			break;
12703 		default:
12704 			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12705 			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12706 			break;
12707 		}
12708 		sbuf_cat(&sb, path_str);
12709 		sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12710 			    (intmax_t)time_uptime - io->io_hdr.start_time);
12711 		sbuf_finish(&sb);
12712 		printf("%s", sbuf_data(&sb));
12713 	}
12714 #endif /* CTL_TIME_IO */
12715 
12716 #ifdef CTL_IO_DELAY
12717 	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12718 		struct ctl_lun *lun;
12719 
12720 		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12721 
12722 		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12723 	} else {
12724 		struct ctl_lun *lun;
12725 
12726 		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12727 		if ((lun != NULL)
12728 		 && (lun->delay_info.datamove_delay > 0)) {
12729 			struct callout *callout;
12730 
12731 			callout = (struct callout *)&io->io_hdr.timer_bytes;
12732 			callout_init(callout, /*mpsafe*/ 1);
12733 			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12734 			callout_reset(callout,
12735 				      lun->delay_info.datamove_delay * hz,
12736 				      ctl_datamove_timer_wakeup, io);
12737 			if (lun->delay_info.datamove_type ==
12738 			    CTL_DELAY_TYPE_ONESHOT)
12739 				lun->delay_info.datamove_delay = 0;
12740 			return;
12741 		}
12742 	}
12743 #endif
12744 
12745 	/*
12746 	 * This command has been aborted.  Set the port status, so we fail
12747 	 * the data move.
12748 	 */
12749 	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12750 		printf("ctl_datamove: tag 0x%04x on (%ju:%d:%ju:%d) aborted\n",
12751 		       io->scsiio.tag_num,(uintmax_t)io->io_hdr.nexus.initid.id,
12752 		       io->io_hdr.nexus.targ_port,
12753 		       (uintmax_t)io->io_hdr.nexus.targ_target.id,
12754 		       io->io_hdr.nexus.targ_lun);
12755 		io->io_hdr.port_status = 31337;
12756 		/*
12757 		 * Note that the backend, in this case, will get the
12758 		 * callback in its context.  In other cases it may get
12759 		 * called in the frontend's interrupt thread context.
12760 		 */
12761 		io->scsiio.be_move_done(io);
12762 		return;
12763 	}
12764 
12765 	/*
12766 	 * If we're in XFER mode and this I/O is from the other shelf
12767 	 * controller, we need to send the DMA to the other side to
12768 	 * actually transfer the data to/from the host.  In serialize only
12769 	 * mode the transfer happens below CTL and ctl_datamove() is only
12770 	 * called on the machine that originally received the I/O.
12771 	 */
12772 	if ((control_softc->ha_mode == CTL_HA_MODE_XFER)
12773 	 && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12774 		union ctl_ha_msg msg;
12775 		uint32_t sg_entries_sent;
12776 		int do_sg_copy;
12777 		int i;
12778 
12779 		memset(&msg, 0, sizeof(msg));
12780 		msg.hdr.msg_type = CTL_MSG_DATAMOVE;
12781 		msg.hdr.original_sc = io->io_hdr.original_sc;
12782 		msg.hdr.serializing_sc = io;
12783 		msg.hdr.nexus = io->io_hdr.nexus;
12784 		msg.dt.flags = io->io_hdr.flags;
12785 		/*
12786 		 * We convert everything into a S/G list here.  We can't
12787 		 * pass by reference, only by value between controllers.
12788 		 * So we can't pass a pointer to the S/G list, only as many
12789 		 * S/G entries as we can fit in here.  If it's possible for
12790 		 * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
12791 		 * then we need to break this up into multiple transfers.
12792 		 */
12793 		if (io->scsiio.kern_sg_entries == 0) {
12794 			msg.dt.kern_sg_entries = 1;
12795 			/*
12796 			 * If this is in cached memory, flush the cache
12797 			 * before we send the DMA request to the other
12798 			 * controller.  We want to do this in either the
12799 			 * read or the write case.  The read case is
12800 			 * straightforward.  In the write case, we want to
12801 			 * make sure nothing is in the local cache that
12802 			 * could overwrite the DMAed data.
12803 			 */
12804 			if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12805 				/*
12806 				 * XXX KDM use bus_dmamap_sync() here.
12807 				 */
12808 			}
12809 
12810 			/*
12811 			 * Convert to a physical address if this is a
12812 			 * virtual address.
12813 			 */
12814 			if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
12815 				msg.dt.sg_list[0].addr =
12816 					io->scsiio.kern_data_ptr;
12817 			} else {
12818 				/*
12819 				 * XXX KDM use busdma here!
12820 				 */
12821 #if 0
12822 				msg.dt.sg_list[0].addr = (void *)
12823 					vtophys(io->scsiio.kern_data_ptr);
12824 #endif
12825 			}
12826 
12827 			msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
12828 			do_sg_copy = 0;
12829 		} else {
12830 			struct ctl_sg_entry *sgl;
12831 
12832 			do_sg_copy = 1;
12833 			msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
12834 			sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
12835 			if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12836 				/*
12837 				 * XXX KDM use bus_dmamap_sync() here.
12838 				 */
12839 			}
12840 		}
12841 
12842 		msg.dt.kern_data_len = io->scsiio.kern_data_len;
12843 		msg.dt.kern_total_len = io->scsiio.kern_total_len;
12844 		msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
12845 		msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
12846 		msg.dt.sg_sequence = 0;
12847 
12848 		/*
12849 		 * Loop until we've sent all of the S/G entries.  On the
12850 		 * other end, we'll recompose these S/G entries into one
12851 		 * contiguous list before passing it to the
12852 		 */
12853 		for (sg_entries_sent = 0; sg_entries_sent <
12854 		     msg.dt.kern_sg_entries; msg.dt.sg_sequence++) {
12855 			msg.dt.cur_sg_entries = ctl_min((sizeof(msg.dt.sg_list)/
12856 				sizeof(msg.dt.sg_list[0])),
12857 				msg.dt.kern_sg_entries - sg_entries_sent);
12858 
12859 			if (do_sg_copy != 0) {
12860 				struct ctl_sg_entry *sgl;
12861 				int j;
12862 
12863 				sgl = (struct ctl_sg_entry *)
12864 					io->scsiio.kern_data_ptr;
12865 				/*
12866 				 * If this is in cached memory, flush the cache
12867 				 * before we send the DMA request to the other
12868 				 * controller.  We want to do this in either
12869 				 * the * read or the write case.  The read
12870 				 * case is straightforward.  In the write
12871 				 * case, we want to make sure nothing is
12872 				 * in the local cache that could overwrite
12873 				 * the DMAed data.
12874 				 */
12875 
12876 				for (i = sg_entries_sent, j = 0;
12877 				     i < msg.dt.cur_sg_entries; i++, j++) {
12878 					if ((io->io_hdr.flags &
12879 					     CTL_FLAG_NO_DATASYNC) == 0) {
12880 						/*
12881 						 * XXX KDM use bus_dmamap_sync()
12882 						 */
12883 					}
12884 					if ((io->io_hdr.flags &
12885 					     CTL_FLAG_BUS_ADDR) == 0) {
12886 						/*
12887 						 * XXX KDM use busdma.
12888 						 */
12889 #if 0
12890 						msg.dt.sg_list[j].addr =(void *)
12891 						       vtophys(sgl[i].addr);
12892 #endif
12893 					} else {
12894 						msg.dt.sg_list[j].addr =
12895 							sgl[i].addr;
12896 					}
12897 					msg.dt.sg_list[j].len = sgl[i].len;
12898 				}
12899 			}
12900 
12901 			sg_entries_sent += msg.dt.cur_sg_entries;
12902 			if (sg_entries_sent >= msg.dt.kern_sg_entries)
12903 				msg.dt.sg_last = 1;
12904 			else
12905 				msg.dt.sg_last = 0;
12906 
12907 			/*
12908 			 * XXX KDM drop and reacquire the lock here?
12909 			 */
12910 			if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12911 			    sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
12912 				/*
12913 				 * XXX do something here.
12914 				 */
12915 			}
12916 
12917 			msg.dt.sent_sg_entries = sg_entries_sent;
12918 		}
12919 		io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12920 		if (io->io_hdr.flags & CTL_FLAG_FAILOVER)
12921 			ctl_failover_io(io, /*have_lock*/ 0);
12922 
12923 	} else {
12924 
12925 		/*
12926 		 * Lookup the fe_datamove() function for this particular
12927 		 * front end.
12928 		 */
12929 		fe_datamove =
12930 		    control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12931 
12932 		fe_datamove(io);
12933 	}
12934 }
12935 
12936 static void
12937 ctl_send_datamove_done(union ctl_io *io, int have_lock)
12938 {
12939 	union ctl_ha_msg msg;
12940 	int isc_status;
12941 
12942 	memset(&msg, 0, sizeof(msg));
12943 
12944 	msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12945 	msg.hdr.original_sc = io;
12946 	msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12947 	msg.hdr.nexus = io->io_hdr.nexus;
12948 	msg.hdr.status = io->io_hdr.status;
12949 	msg.scsi.tag_num = io->scsiio.tag_num;
12950 	msg.scsi.tag_type = io->scsiio.tag_type;
12951 	msg.scsi.scsi_status = io->scsiio.scsi_status;
12952 	memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12953 	       sizeof(io->scsiio.sense_data));
12954 	msg.scsi.sense_len = io->scsiio.sense_len;
12955 	msg.scsi.sense_residual = io->scsiio.sense_residual;
12956 	msg.scsi.fetd_status = io->io_hdr.port_status;
12957 	msg.scsi.residual = io->scsiio.residual;
12958 	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12959 
12960 	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12961 		ctl_failover_io(io, /*have_lock*/ have_lock);
12962 		return;
12963 	}
12964 
12965 	isc_status = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0);
12966 	if (isc_status > CTL_HA_STATUS_SUCCESS) {
12967 		/* XXX do something if this fails */
12968 	}
12969 
12970 }
12971 
12972 /*
12973  * The DMA to the remote side is done, now we need to tell the other side
12974  * we're done so it can continue with its data movement.
12975  */
12976 static void
12977 ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12978 {
12979 	union ctl_io *io;
12980 
12981 	io = rq->context;
12982 
12983 	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12984 		printf("%s: ISC DMA write failed with error %d", __func__,
12985 		       rq->ret);
12986 		ctl_set_internal_failure(&io->scsiio,
12987 					 /*sks_valid*/ 1,
12988 					 /*retry_count*/ rq->ret);
12989 	}
12990 
12991 	ctl_dt_req_free(rq);
12992 
12993 	/*
12994 	 * In this case, we had to malloc the memory locally.  Free it.
12995 	 */
12996 	if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
12997 		int i;
12998 		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12999 			free(io->io_hdr.local_sglist[i].addr, M_CTL);
13000 	}
13001 	/*
13002 	 * The data is in local and remote memory, so now we need to send
13003 	 * status (good or back) back to the other side.
13004 	 */
13005 	ctl_send_datamove_done(io, /*have_lock*/ 0);
13006 }
13007 
13008 /*
13009  * We've moved the data from the host/controller into local memory.  Now we
13010  * need to push it over to the remote controller's memory.
13011  */
13012 static int
13013 ctl_datamove_remote_dm_write_cb(union ctl_io *io)
13014 {
13015 	int retval;
13016 
13017 	retval = 0;
13018 
13019 	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
13020 					  ctl_datamove_remote_write_cb);
13021 
13022 	return (retval);
13023 }
13024 
13025 static void
13026 ctl_datamove_remote_write(union ctl_io *io)
13027 {
13028 	int retval;
13029 	void (*fe_datamove)(union ctl_io *io);
13030 
13031 	/*
13032 	 * - Get the data from the host/HBA into local memory.
13033 	 * - DMA memory from the local controller to the remote controller.
13034 	 * - Send status back to the remote controller.
13035 	 */
13036 
13037 	retval = ctl_datamove_remote_sgl_setup(io);
13038 	if (retval != 0)
13039 		return;
13040 
13041 	/* Switch the pointer over so the FETD knows what to do */
13042 	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
13043 
13044 	/*
13045 	 * Use a custom move done callback, since we need to send completion
13046 	 * back to the other controller, not to the backend on this side.
13047 	 */
13048 	io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
13049 
13050 	fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
13051 
13052 	fe_datamove(io);
13053 
13054 	return;
13055 
13056 }
13057 
13058 static int
13059 ctl_datamove_remote_dm_read_cb(union ctl_io *io)
13060 {
13061 #if 0
13062 	char str[256];
13063 	char path_str[64];
13064 	struct sbuf sb;
13065 #endif
13066 
13067 	/*
13068 	 * In this case, we had to malloc the memory locally.  Free it.
13069 	 */
13070 	if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
13071 		int i;
13072 		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13073 			free(io->io_hdr.local_sglist[i].addr, M_CTL);
13074 	}
13075 
13076 #if 0
13077 	scsi_path_string(io, path_str, sizeof(path_str));
13078 	sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13079 	sbuf_cat(&sb, path_str);
13080 	scsi_command_string(&io->scsiio, NULL, &sb);
13081 	sbuf_printf(&sb, "\n");
13082 	sbuf_cat(&sb, path_str);
13083 	sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13084 		    io->scsiio.tag_num, io->scsiio.tag_type);
13085 	sbuf_cat(&sb, path_str);
13086 	sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
13087 		    io->io_hdr.flags, io->io_hdr.status);
13088 	sbuf_finish(&sb);
13089 	printk("%s", sbuf_data(&sb));
13090 #endif
13091 
13092 
13093 	/*
13094 	 * The read is done, now we need to send status (good or bad) back
13095 	 * to the other side.
13096 	 */
13097 	ctl_send_datamove_done(io, /*have_lock*/ 0);
13098 
13099 	return (0);
13100 }
13101 
13102 static void
13103 ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
13104 {
13105 	union ctl_io *io;
13106 	void (*fe_datamove)(union ctl_io *io);
13107 
13108 	io = rq->context;
13109 
13110 	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
13111 		printf("%s: ISC DMA read failed with error %d", __func__,
13112 		       rq->ret);
13113 		ctl_set_internal_failure(&io->scsiio,
13114 					 /*sks_valid*/ 1,
13115 					 /*retry_count*/ rq->ret);
13116 	}
13117 
13118 	ctl_dt_req_free(rq);
13119 
13120 	/* Switch the pointer over so the FETD knows what to do */
13121 	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
13122 
13123 	/*
13124 	 * Use a custom move done callback, since we need to send completion
13125 	 * back to the other controller, not to the backend on this side.
13126 	 */
13127 	io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
13128 
13129 	/* XXX KDM add checks like the ones in ctl_datamove? */
13130 
13131 	fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
13132 
13133 	fe_datamove(io);
13134 }
13135 
13136 static int
13137 ctl_datamove_remote_sgl_setup(union ctl_io *io)
13138 {
13139 	struct ctl_sg_entry *local_sglist, *remote_sglist;
13140 	struct ctl_sg_entry *local_dma_sglist, *remote_dma_sglist;
13141 	struct ctl_softc *softc;
13142 	int retval;
13143 	int i;
13144 
13145 	retval = 0;
13146 	softc = control_softc;
13147 
13148 	local_sglist = io->io_hdr.local_sglist;
13149 	local_dma_sglist = io->io_hdr.local_dma_sglist;
13150 	remote_sglist = io->io_hdr.remote_sglist;
13151 	remote_dma_sglist = io->io_hdr.remote_dma_sglist;
13152 
13153 	if (io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) {
13154 		for (i = 0; i < io->scsiio.kern_sg_entries; i++) {
13155 			local_sglist[i].len = remote_sglist[i].len;
13156 
13157 			/*
13158 			 * XXX Detect the situation where the RS-level I/O
13159 			 * redirector on the other side has already read the
13160 			 * data off of the AOR RS on this side, and
13161 			 * transferred it to remote (mirror) memory on the
13162 			 * other side.  Since we already have the data in
13163 			 * memory here, we just need to use it.
13164 			 *
13165 			 * XXX KDM this can probably be removed once we
13166 			 * get the cache device code in and take the
13167 			 * current AOR implementation out.
13168 			 */
13169 #ifdef NEEDTOPORT
13170 			if ((remote_sglist[i].addr >=
13171 			     (void *)vtophys(softc->mirr->addr))
13172 			 && (remote_sglist[i].addr <
13173 			     ((void *)vtophys(softc->mirr->addr) +
13174 			     CacheMirrorOffset))) {
13175 				local_sglist[i].addr = remote_sglist[i].addr -
13176 					CacheMirrorOffset;
13177 				if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13178 				     CTL_FLAG_DATA_IN)
13179 					io->io_hdr.flags |= CTL_FLAG_REDIR_DONE;
13180 			} else {
13181 				local_sglist[i].addr = remote_sglist[i].addr +
13182 					CacheMirrorOffset;
13183 			}
13184 #endif
13185 #if 0
13186 			printf("%s: local %p, remote %p, len %d\n",
13187 			       __func__, local_sglist[i].addr,
13188 			       remote_sglist[i].addr, local_sglist[i].len);
13189 #endif
13190 		}
13191 	} else {
13192 		uint32_t len_to_go;
13193 
13194 		/*
13195 		 * In this case, we don't have automatically allocated
13196 		 * memory for this I/O on this controller.  This typically
13197 		 * happens with internal CTL I/O -- e.g. inquiry, mode
13198 		 * sense, etc.  Anything coming from RAIDCore will have
13199 		 * a mirror area available.
13200 		 */
13201 		len_to_go = io->scsiio.kern_data_len;
13202 
13203 		/*
13204 		 * Clear the no datasync flag, we have to use malloced
13205 		 * buffers.
13206 		 */
13207 		io->io_hdr.flags &= ~CTL_FLAG_NO_DATASYNC;
13208 
13209 		/*
13210 		 * The difficult thing here is that the size of the various
13211 		 * S/G segments may be different than the size from the
13212 		 * remote controller.  That'll make it harder when DMAing
13213 		 * the data back to the other side.
13214 		 */
13215 		for (i = 0; (i < sizeof(io->io_hdr.remote_sglist) /
13216 		     sizeof(io->io_hdr.remote_sglist[0])) &&
13217 		     (len_to_go > 0); i++) {
13218 			local_sglist[i].len = ctl_min(len_to_go, 131072);
13219 			CTL_SIZE_8B(local_dma_sglist[i].len,
13220 				    local_sglist[i].len);
13221 			local_sglist[i].addr =
13222 				malloc(local_dma_sglist[i].len, M_CTL,M_WAITOK);
13223 
13224 			local_dma_sglist[i].addr = local_sglist[i].addr;
13225 
13226 			if (local_sglist[i].addr == NULL) {
13227 				int j;
13228 
13229 				printf("malloc failed for %zd bytes!",
13230 				       local_dma_sglist[i].len);
13231 				for (j = 0; j < i; j++) {
13232 					free(local_sglist[j].addr, M_CTL);
13233 				}
13234 				ctl_set_internal_failure(&io->scsiio,
13235 							 /*sks_valid*/ 1,
13236 							 /*retry_count*/ 4857);
13237 				retval = 1;
13238 				goto bailout_error;
13239 
13240 			}
13241 			/* XXX KDM do we need a sync here? */
13242 
13243 			len_to_go -= local_sglist[i].len;
13244 		}
13245 		/*
13246 		 * Reset the number of S/G entries accordingly.  The
13247 		 * original number of S/G entries is available in
13248 		 * rem_sg_entries.
13249 		 */
13250 		io->scsiio.kern_sg_entries = i;
13251 
13252 #if 0
13253 		printf("%s: kern_sg_entries = %d\n", __func__,
13254 		       io->scsiio.kern_sg_entries);
13255 		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13256 			printf("%s: sg[%d] = %p, %d (DMA: %d)\n", __func__, i,
13257 			       local_sglist[i].addr, local_sglist[i].len,
13258 			       local_dma_sglist[i].len);
13259 #endif
13260 	}
13261 
13262 
13263 	return (retval);
13264 
13265 bailout_error:
13266 
13267 	ctl_send_datamove_done(io, /*have_lock*/ 0);
13268 
13269 	return (retval);
13270 }
13271 
13272 static int
13273 ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
13274 			 ctl_ha_dt_cb callback)
13275 {
13276 	struct ctl_ha_dt_req *rq;
13277 	struct ctl_sg_entry *remote_sglist, *local_sglist;
13278 	struct ctl_sg_entry *remote_dma_sglist, *local_dma_sglist;
13279 	uint32_t local_used, remote_used, total_used;
13280 	int retval;
13281 	int i, j;
13282 
13283 	retval = 0;
13284 
13285 	rq = ctl_dt_req_alloc();
13286 
13287 	/*
13288 	 * If we failed to allocate the request, and if the DMA didn't fail
13289 	 * anyway, set busy status.  This is just a resource allocation
13290 	 * failure.
13291 	 */
13292 	if ((rq == NULL)
13293 	 && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE))
13294 		ctl_set_busy(&io->scsiio);
13295 
13296 	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE) {
13297 
13298 		if (rq != NULL)
13299 			ctl_dt_req_free(rq);
13300 
13301 		/*
13302 		 * The data move failed.  We need to return status back
13303 		 * to the other controller.  No point in trying to DMA
13304 		 * data to the remote controller.
13305 		 */
13306 
13307 		ctl_send_datamove_done(io, /*have_lock*/ 0);
13308 
13309 		retval = 1;
13310 
13311 		goto bailout;
13312 	}
13313 
13314 	local_sglist = io->io_hdr.local_sglist;
13315 	local_dma_sglist = io->io_hdr.local_dma_sglist;
13316 	remote_sglist = io->io_hdr.remote_sglist;
13317 	remote_dma_sglist = io->io_hdr.remote_dma_sglist;
13318 	local_used = 0;
13319 	remote_used = 0;
13320 	total_used = 0;
13321 
13322 	if (io->io_hdr.flags & CTL_FLAG_REDIR_DONE) {
13323 		rq->ret = CTL_HA_STATUS_SUCCESS;
13324 		rq->context = io;
13325 		callback(rq);
13326 		goto bailout;
13327 	}
13328 
13329 	/*
13330 	 * Pull/push the data over the wire from/to the other controller.
13331 	 * This takes into account the possibility that the local and
13332 	 * remote sglists may not be identical in terms of the size of
13333 	 * the elements and the number of elements.
13334 	 *
13335 	 * One fundamental assumption here is that the length allocated for
13336 	 * both the local and remote sglists is identical.  Otherwise, we've
13337 	 * essentially got a coding error of some sort.
13338 	 */
13339 	for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
13340 		int isc_ret;
13341 		uint32_t cur_len, dma_length;
13342 		uint8_t *tmp_ptr;
13343 
13344 		rq->id = CTL_HA_DATA_CTL;
13345 		rq->command = command;
13346 		rq->context = io;
13347 
13348 		/*
13349 		 * Both pointers should be aligned.  But it is possible
13350 		 * that the allocation length is not.  They should both
13351 		 * also have enough slack left over at the end, though,
13352 		 * to round up to the next 8 byte boundary.
13353 		 */
13354 		cur_len = ctl_min(local_sglist[i].len - local_used,
13355 				  remote_sglist[j].len - remote_used);
13356 
13357 		/*
13358 		 * In this case, we have a size issue and need to decrease
13359 		 * the size, except in the case where we actually have less
13360 		 * than 8 bytes left.  In that case, we need to increase
13361 		 * the DMA length to get the last bit.
13362 		 */
13363 		if ((cur_len & 0x7) != 0) {
13364 			if (cur_len > 0x7) {
13365 				cur_len = cur_len - (cur_len & 0x7);
13366 				dma_length = cur_len;
13367 			} else {
13368 				CTL_SIZE_8B(dma_length, cur_len);
13369 			}
13370 
13371 		} else
13372 			dma_length = cur_len;
13373 
13374 		/*
13375 		 * If we had to allocate memory for this I/O, instead of using
13376 		 * the non-cached mirror memory, we'll need to flush the cache
13377 		 * before trying to DMA to the other controller.
13378 		 *
13379 		 * We could end up doing this multiple times for the same
13380 		 * segment if we have a larger local segment than remote
13381 		 * segment.  That shouldn't be an issue.
13382 		 */
13383 		if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
13384 			/*
13385 			 * XXX KDM use bus_dmamap_sync() here.
13386 			 */
13387 		}
13388 
13389 		rq->size = dma_length;
13390 
13391 		tmp_ptr = (uint8_t *)local_sglist[i].addr;
13392 		tmp_ptr += local_used;
13393 
13394 		/* Use physical addresses when talking to ISC hardware */
13395 		if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
13396 			/* XXX KDM use busdma */
13397 #if 0
13398 			rq->local = vtophys(tmp_ptr);
13399 #endif
13400 		} else
13401 			rq->local = tmp_ptr;
13402 
13403 		tmp_ptr = (uint8_t *)remote_sglist[j].addr;
13404 		tmp_ptr += remote_used;
13405 		rq->remote = tmp_ptr;
13406 
13407 		rq->callback = NULL;
13408 
13409 		local_used += cur_len;
13410 		if (local_used >= local_sglist[i].len) {
13411 			i++;
13412 			local_used = 0;
13413 		}
13414 
13415 		remote_used += cur_len;
13416 		if (remote_used >= remote_sglist[j].len) {
13417 			j++;
13418 			remote_used = 0;
13419 		}
13420 		total_used += cur_len;
13421 
13422 		if (total_used >= io->scsiio.kern_data_len)
13423 			rq->callback = callback;
13424 
13425 		if ((rq->size & 0x7) != 0) {
13426 			printf("%s: warning: size %d is not on 8b boundary\n",
13427 			       __func__, rq->size);
13428 		}
13429 		if (((uintptr_t)rq->local & 0x7) != 0) {
13430 			printf("%s: warning: local %p not on 8b boundary\n",
13431 			       __func__, rq->local);
13432 		}
13433 		if (((uintptr_t)rq->remote & 0x7) != 0) {
13434 			printf("%s: warning: remote %p not on 8b boundary\n",
13435 			       __func__, rq->local);
13436 		}
13437 #if 0
13438 		printf("%s: %s: local %#x remote %#x size %d\n", __func__,
13439 		       (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
13440 		       rq->local, rq->remote, rq->size);
13441 #endif
13442 
13443 		isc_ret = ctl_dt_single(rq);
13444 		if (isc_ret == CTL_HA_STATUS_WAIT)
13445 			continue;
13446 
13447 		if (isc_ret == CTL_HA_STATUS_DISCONNECT) {
13448 			rq->ret = CTL_HA_STATUS_SUCCESS;
13449 		} else {
13450 			rq->ret = isc_ret;
13451 		}
13452 		callback(rq);
13453 		goto bailout;
13454 	}
13455 
13456 bailout:
13457 	return (retval);
13458 
13459 }
13460 
13461 static void
13462 ctl_datamove_remote_read(union ctl_io *io)
13463 {
13464 	int retval;
13465 	int i;
13466 
13467 	/*
13468 	 * This will send an error to the other controller in the case of a
13469 	 * failure.
13470 	 */
13471 	retval = ctl_datamove_remote_sgl_setup(io);
13472 	if (retval != 0)
13473 		return;
13474 
13475 	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
13476 					  ctl_datamove_remote_read_cb);
13477 	if ((retval != 0)
13478 	 && ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0)) {
13479 		/*
13480 		 * Make sure we free memory if there was an error..  The
13481 		 * ctl_datamove_remote_xfer() function will send the
13482 		 * datamove done message, or call the callback with an
13483 		 * error if there is a problem.
13484 		 */
13485 		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13486 			free(io->io_hdr.local_sglist[i].addr, M_CTL);
13487 	}
13488 
13489 	return;
13490 }
13491 
13492 /*
13493  * Process a datamove request from the other controller.  This is used for
13494  * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
13495  * first.  Once that is complete, the data gets DMAed into the remote
13496  * controller's memory.  For reads, we DMA from the remote controller's
13497  * memory into our memory first, and then move it out to the FETD.
13498  */
13499 static void
13500 ctl_datamove_remote(union ctl_io *io)
13501 {
13502 	struct ctl_softc *softc;
13503 
13504 	softc = control_softc;
13505 
13506 	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
13507 
13508 	/*
13509 	 * Note that we look for an aborted I/O here, but don't do some of
13510 	 * the other checks that ctl_datamove() normally does.
13511 	 * We don't need to run the datamove delay code, since that should
13512 	 * have been done if need be on the other controller.
13513 	 */
13514 	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
13515 		printf("%s: tag 0x%04x on (%d:%d:%d:%d) aborted\n", __func__,
13516 		       io->scsiio.tag_num, io->io_hdr.nexus.initid.id,
13517 		       io->io_hdr.nexus.targ_port,
13518 		       io->io_hdr.nexus.targ_target.id,
13519 		       io->io_hdr.nexus.targ_lun);
13520 		io->io_hdr.port_status = 31338;
13521 		ctl_send_datamove_done(io, /*have_lock*/ 0);
13522 		return;
13523 	}
13524 
13525 	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT) {
13526 		ctl_datamove_remote_write(io);
13527 	} else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN){
13528 		ctl_datamove_remote_read(io);
13529 	} else {
13530 		union ctl_ha_msg msg;
13531 		struct scsi_sense_data *sense;
13532 		uint8_t sks[3];
13533 		int retry_count;
13534 
13535 		memset(&msg, 0, sizeof(msg));
13536 
13537 		msg.hdr.msg_type = CTL_MSG_BAD_JUJU;
13538 		msg.hdr.status = CTL_SCSI_ERROR;
13539 		msg.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
13540 
13541 		retry_count = 4243;
13542 
13543 		sense = &msg.scsi.sense_data;
13544 		sks[0] = SSD_SCS_VALID;
13545 		sks[1] = (retry_count >> 8) & 0xff;
13546 		sks[2] = retry_count & 0xff;
13547 
13548 		/* "Internal target failure" */
13549 		scsi_set_sense_data(sense,
13550 				    /*sense_format*/ SSD_TYPE_NONE,
13551 				    /*current_error*/ 1,
13552 				    /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
13553 				    /*asc*/ 0x44,
13554 				    /*ascq*/ 0x00,
13555 				    /*type*/ SSD_ELEM_SKS,
13556 				    /*size*/ sizeof(sks),
13557 				    /*data*/ sks,
13558 				    SSD_ELEM_NONE);
13559 
13560 		io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
13561 		if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13562 			ctl_failover_io(io, /*have_lock*/ 1);
13563 			return;
13564 		}
13565 
13566 		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0) >
13567 		    CTL_HA_STATUS_SUCCESS) {
13568 			/* XXX KDM what to do if this fails? */
13569 		}
13570 		return;
13571 	}
13572 
13573 }
13574 
13575 static int
13576 ctl_process_done(union ctl_io *io)
13577 {
13578 	struct ctl_lun *lun;
13579 	struct ctl_softc *ctl_softc;
13580 	void (*fe_done)(union ctl_io *io);
13581 	uint32_t targ_port = ctl_port_idx(io->io_hdr.nexus.targ_port);
13582 
13583 	CTL_DEBUG_PRINT(("ctl_process_done\n"));
13584 
13585 	fe_done =
13586 	    control_softc->ctl_ports[targ_port]->fe_done;
13587 
13588 #ifdef CTL_TIME_IO
13589 	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
13590 		char str[256];
13591 		char path_str[64];
13592 		struct sbuf sb;
13593 
13594 		ctl_scsi_path_string(io, path_str, sizeof(path_str));
13595 		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13596 
13597 		sbuf_cat(&sb, path_str);
13598 		switch (io->io_hdr.io_type) {
13599 		case CTL_IO_SCSI:
13600 			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
13601 			sbuf_printf(&sb, "\n");
13602 			sbuf_cat(&sb, path_str);
13603 			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13604 				    io->scsiio.tag_num, io->scsiio.tag_type);
13605 			break;
13606 		case CTL_IO_TASK:
13607 			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
13608 				    "Tag Type: %d\n", io->taskio.task_action,
13609 				    io->taskio.tag_num, io->taskio.tag_type);
13610 			break;
13611 		default:
13612 			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13613 			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13614 			break;
13615 		}
13616 		sbuf_cat(&sb, path_str);
13617 		sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
13618 			    (intmax_t)time_uptime - io->io_hdr.start_time);
13619 		sbuf_finish(&sb);
13620 		printf("%s", sbuf_data(&sb));
13621 	}
13622 #endif /* CTL_TIME_IO */
13623 
13624 	switch (io->io_hdr.io_type) {
13625 	case CTL_IO_SCSI:
13626 		break;
13627 	case CTL_IO_TASK:
13628 		if (bootverbose || verbose > 0)
13629 			ctl_io_error_print(io, NULL);
13630 		if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
13631 			ctl_free_io(io);
13632 		else
13633 			fe_done(io);
13634 		return (CTL_RETVAL_COMPLETE);
13635 		break;
13636 	default:
13637 		printf("ctl_process_done: invalid io type %d\n",
13638 		       io->io_hdr.io_type);
13639 		panic("ctl_process_done: invalid io type %d\n",
13640 		      io->io_hdr.io_type);
13641 		break; /* NOTREACHED */
13642 	}
13643 
13644 	lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13645 	if (lun == NULL) {
13646 		CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13647 				 io->io_hdr.nexus.targ_mapped_lun));
13648 		fe_done(io);
13649 		goto bailout;
13650 	}
13651 	ctl_softc = lun->ctl_softc;
13652 
13653 	mtx_lock(&lun->lun_lock);
13654 
13655 	/*
13656 	 * Check to see if we have any errors to inject here.  We only
13657 	 * inject errors for commands that don't already have errors set.
13658 	 */
13659 	if ((STAILQ_FIRST(&lun->error_list) != NULL)
13660 	 && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS))
13661 		ctl_inject_error(lun, io);
13662 
13663 	/*
13664 	 * XXX KDM how do we treat commands that aren't completed
13665 	 * successfully?
13666 	 *
13667 	 * XXX KDM should we also track I/O latency?
13668 	 */
13669 	if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13670 	    io->io_hdr.io_type == CTL_IO_SCSI) {
13671 #ifdef CTL_TIME_IO
13672 		struct bintime cur_bt;
13673 #endif
13674 		int type;
13675 
13676 		if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13677 		    CTL_FLAG_DATA_IN)
13678 			type = CTL_STATS_READ;
13679 		else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13680 		    CTL_FLAG_DATA_OUT)
13681 			type = CTL_STATS_WRITE;
13682 		else
13683 			type = CTL_STATS_NO_IO;
13684 
13685 		lun->stats.ports[targ_port].bytes[type] +=
13686 		    io->scsiio.kern_total_len;
13687 		lun->stats.ports[targ_port].operations[type]++;
13688 #ifdef CTL_TIME_IO
13689 		bintime_add(&lun->stats.ports[targ_port].dma_time[type],
13690 		   &io->io_hdr.dma_bt);
13691 		lun->stats.ports[targ_port].num_dmas[type] +=
13692 		    io->io_hdr.num_dmas;
13693 		getbintime(&cur_bt);
13694 		bintime_sub(&cur_bt, &io->io_hdr.start_bt);
13695 		bintime_add(&lun->stats.ports[targ_port].time[type], &cur_bt);
13696 #endif
13697 	}
13698 
13699 	/*
13700 	 * Remove this from the OOA queue.
13701 	 */
13702 	TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13703 
13704 	/*
13705 	 * Run through the blocked queue on this LUN and see if anything
13706 	 * has become unblocked, now that this transaction is done.
13707 	 */
13708 	ctl_check_blocked(lun);
13709 
13710 	/*
13711 	 * If the LUN has been invalidated, free it if there is nothing
13712 	 * left on its OOA queue.
13713 	 */
13714 	if ((lun->flags & CTL_LUN_INVALID)
13715 	 && TAILQ_EMPTY(&lun->ooa_queue)) {
13716 		mtx_unlock(&lun->lun_lock);
13717 		mtx_lock(&ctl_softc->ctl_lock);
13718 		ctl_free_lun(lun);
13719 		mtx_unlock(&ctl_softc->ctl_lock);
13720 	} else
13721 		mtx_unlock(&lun->lun_lock);
13722 
13723 	/*
13724 	 * If this command has been aborted, make sure we set the status
13725 	 * properly.  The FETD is responsible for freeing the I/O and doing
13726 	 * whatever it needs to do to clean up its state.
13727 	 */
13728 	if (io->io_hdr.flags & CTL_FLAG_ABORT)
13729 		ctl_set_task_aborted(&io->scsiio);
13730 
13731 	/*
13732 	 * We print out status for every task management command.  For SCSI
13733 	 * commands, we filter out any unit attention errors; they happen
13734 	 * on every boot, and would clutter up the log.  Note:  task
13735 	 * management commands aren't printed here, they are printed above,
13736 	 * since they should never even make it down here.
13737 	 */
13738 	switch (io->io_hdr.io_type) {
13739 	case CTL_IO_SCSI: {
13740 		int error_code, sense_key, asc, ascq;
13741 
13742 		sense_key = 0;
13743 
13744 		if (((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SCSI_ERROR)
13745 		 && (io->scsiio.scsi_status == SCSI_STATUS_CHECK_COND)) {
13746 			/*
13747 			 * Since this is just for printing, no need to
13748 			 * show errors here.
13749 			 */
13750 			scsi_extract_sense_len(&io->scsiio.sense_data,
13751 					       io->scsiio.sense_len,
13752 					       &error_code,
13753 					       &sense_key,
13754 					       &asc,
13755 					       &ascq,
13756 					       /*show_errors*/ 0);
13757 		}
13758 
13759 		if (((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)
13760 		 && (((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SCSI_ERROR)
13761 		  || (io->scsiio.scsi_status != SCSI_STATUS_CHECK_COND)
13762 		  || (sense_key != SSD_KEY_UNIT_ATTENTION))) {
13763 
13764 			if ((time_uptime - ctl_softc->last_print_jiffies) <= 0){
13765 				ctl_softc->skipped_prints++;
13766 			} else {
13767 				uint32_t skipped_prints;
13768 
13769 				skipped_prints = ctl_softc->skipped_prints;
13770 
13771 				ctl_softc->skipped_prints = 0;
13772 				ctl_softc->last_print_jiffies = time_uptime;
13773 
13774 				if (skipped_prints > 0) {
13775 #ifdef NEEDTOPORT
13776 					csevent_log(CSC_CTL | CSC_SHELF_SW |
13777 					    CTL_ERROR_REPORT,
13778 					    csevent_LogType_Trace,
13779 					    csevent_Severity_Information,
13780 					    csevent_AlertLevel_Green,
13781 					    csevent_FRU_Firmware,
13782 					    csevent_FRU_Unknown,
13783 					    "High CTL error volume, %d prints "
13784 					    "skipped", skipped_prints);
13785 #endif
13786 				}
13787 				if (bootverbose || verbose > 0)
13788 					ctl_io_error_print(io, NULL);
13789 			}
13790 		}
13791 		break;
13792 	}
13793 	case CTL_IO_TASK:
13794 		if (bootverbose || verbose > 0)
13795 			ctl_io_error_print(io, NULL);
13796 		break;
13797 	default:
13798 		break;
13799 	}
13800 
13801 	/*
13802 	 * Tell the FETD or the other shelf controller we're done with this
13803 	 * command.  Note that only SCSI commands get to this point.  Task
13804 	 * management commands are completed above.
13805 	 *
13806 	 * We only send status to the other controller if we're in XFER
13807 	 * mode.  In SER_ONLY mode, the I/O is done on the controller that
13808 	 * received the I/O (from CTL's perspective), and so the status is
13809 	 * generated there.
13810 	 *
13811 	 * XXX KDM if we hold the lock here, we could cause a deadlock
13812 	 * if the frontend comes back in in this context to queue
13813 	 * something.
13814 	 */
13815 	if ((ctl_softc->ha_mode == CTL_HA_MODE_XFER)
13816 	 && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
13817 		union ctl_ha_msg msg;
13818 
13819 		memset(&msg, 0, sizeof(msg));
13820 		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13821 		msg.hdr.original_sc = io->io_hdr.original_sc;
13822 		msg.hdr.nexus = io->io_hdr.nexus;
13823 		msg.hdr.status = io->io_hdr.status;
13824 		msg.scsi.scsi_status = io->scsiio.scsi_status;
13825 		msg.scsi.tag_num = io->scsiio.tag_num;
13826 		msg.scsi.tag_type = io->scsiio.tag_type;
13827 		msg.scsi.sense_len = io->scsiio.sense_len;
13828 		msg.scsi.sense_residual = io->scsiio.sense_residual;
13829 		msg.scsi.residual = io->scsiio.residual;
13830 		memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
13831 		       sizeof(io->scsiio.sense_data));
13832 		/*
13833 		 * We copy this whether or not this is an I/O-related
13834 		 * command.  Otherwise, we'd have to go and check to see
13835 		 * whether it's a read/write command, and it really isn't
13836 		 * worth it.
13837 		 */
13838 		memcpy(&msg.scsi.lbalen,
13839 		       &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
13840 		       sizeof(msg.scsi.lbalen));
13841 
13842 		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13843 				sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
13844 			/* XXX do something here */
13845 		}
13846 
13847 		ctl_free_io(io);
13848 	} else
13849 		fe_done(io);
13850 
13851 bailout:
13852 
13853 	return (CTL_RETVAL_COMPLETE);
13854 }
13855 
13856 #ifdef CTL_WITH_CA
13857 /*
13858  * Front end should call this if it doesn't do autosense.  When the request
13859  * sense comes back in from the initiator, we'll dequeue this and send it.
13860  */
13861 int
13862 ctl_queue_sense(union ctl_io *io)
13863 {
13864 	struct ctl_lun *lun;
13865 	struct ctl_softc *ctl_softc;
13866 	uint32_t initidx, targ_lun;
13867 
13868 	ctl_softc = control_softc;
13869 
13870 	CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13871 
13872 	/*
13873 	 * LUN lookup will likely move to the ctl_work_thread() once we
13874 	 * have our new queueing infrastructure (that doesn't put things on
13875 	 * a per-LUN queue initially).  That is so that we can handle
13876 	 * things like an INQUIRY to a LUN that we don't have enabled.  We
13877 	 * can't deal with that right now.
13878 	 */
13879 	mtx_lock(&ctl_softc->ctl_lock);
13880 
13881 	/*
13882 	 * If we don't have a LUN for this, just toss the sense
13883 	 * information.
13884 	 */
13885 	targ_lun = io->io_hdr.nexus.targ_lun;
13886 	targ_lun = ctl_map_lun(io->io_hdr.nexus.targ_port, targ_lun);
13887 	if ((targ_lun < CTL_MAX_LUNS)
13888 	 && (ctl_softc->ctl_luns[targ_lun] != NULL))
13889 		lun = ctl_softc->ctl_luns[targ_lun];
13890 	else
13891 		goto bailout;
13892 
13893 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
13894 
13895 	mtx_lock(&lun->lun_lock);
13896 	/*
13897 	 * Already have CA set for this LUN...toss the sense information.
13898 	 */
13899 	if (ctl_is_set(lun->have_ca, initidx)) {
13900 		mtx_unlock(&lun->lun_lock);
13901 		goto bailout;
13902 	}
13903 
13904 	memcpy(&lun->pending_sense[initidx], &io->scsiio.sense_data,
13905 	       ctl_min(sizeof(lun->pending_sense[initidx]),
13906 	       sizeof(io->scsiio.sense_data)));
13907 	ctl_set_mask(lun->have_ca, initidx);
13908 	mtx_unlock(&lun->lun_lock);
13909 
13910 bailout:
13911 	mtx_unlock(&ctl_softc->ctl_lock);
13912 
13913 	ctl_free_io(io);
13914 
13915 	return (CTL_RETVAL_COMPLETE);
13916 }
13917 #endif
13918 
13919 /*
13920  * Primary command inlet from frontend ports.  All SCSI and task I/O
13921  * requests must go through this function.
13922  */
13923 int
13924 ctl_queue(union ctl_io *io)
13925 {
13926 	struct ctl_softc *ctl_softc;
13927 
13928 	CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13929 
13930 	ctl_softc = control_softc;
13931 
13932 #ifdef CTL_TIME_IO
13933 	io->io_hdr.start_time = time_uptime;
13934 	getbintime(&io->io_hdr.start_bt);
13935 #endif /* CTL_TIME_IO */
13936 
13937 	/* Map FE-specific LUN ID into global one. */
13938 	io->io_hdr.nexus.targ_mapped_lun =
13939 	    ctl_map_lun(io->io_hdr.nexus.targ_port, io->io_hdr.nexus.targ_lun);
13940 
13941 	switch (io->io_hdr.io_type) {
13942 	case CTL_IO_SCSI:
13943 	case CTL_IO_TASK:
13944 		ctl_enqueue_incoming(io);
13945 		break;
13946 	default:
13947 		printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13948 		return (EINVAL);
13949 	}
13950 
13951 	return (CTL_RETVAL_COMPLETE);
13952 }
13953 
13954 #ifdef CTL_IO_DELAY
13955 static void
13956 ctl_done_timer_wakeup(void *arg)
13957 {
13958 	union ctl_io *io;
13959 
13960 	io = (union ctl_io *)arg;
13961 	ctl_done(io);
13962 }
13963 #endif /* CTL_IO_DELAY */
13964 
13965 void
13966 ctl_done(union ctl_io *io)
13967 {
13968 	struct ctl_softc *ctl_softc;
13969 
13970 	ctl_softc = control_softc;
13971 
13972 	/*
13973 	 * Enable this to catch duplicate completion issues.
13974 	 */
13975 #if 0
13976 	if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13977 		printf("%s: type %d msg %d cdb %x iptl: "
13978 		       "%d:%d:%d:%d tag 0x%04x "
13979 		       "flag %#x status %x\n",
13980 			__func__,
13981 			io->io_hdr.io_type,
13982 			io->io_hdr.msg_type,
13983 			io->scsiio.cdb[0],
13984 			io->io_hdr.nexus.initid.id,
13985 			io->io_hdr.nexus.targ_port,
13986 			io->io_hdr.nexus.targ_target.id,
13987 			io->io_hdr.nexus.targ_lun,
13988 			(io->io_hdr.io_type ==
13989 			CTL_IO_TASK) ?
13990 			io->taskio.tag_num :
13991 			io->scsiio.tag_num,
13992 		        io->io_hdr.flags,
13993 			io->io_hdr.status);
13994 	} else
13995 		io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13996 #endif
13997 
13998 	/*
13999 	 * This is an internal copy of an I/O, and should not go through
14000 	 * the normal done processing logic.
14001 	 */
14002 	if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
14003 		return;
14004 
14005 	/*
14006 	 * We need to send a msg to the serializing shelf to finish the IO
14007 	 * as well.  We don't send a finish message to the other shelf if
14008 	 * this is a task management command.  Task management commands
14009 	 * aren't serialized in the OOA queue, but rather just executed on
14010 	 * both shelf controllers for commands that originated on that
14011 	 * controller.
14012 	 */
14013 	if ((io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)
14014 	 && (io->io_hdr.io_type != CTL_IO_TASK)) {
14015 		union ctl_ha_msg msg_io;
14016 
14017 		msg_io.hdr.msg_type = CTL_MSG_FINISH_IO;
14018 		msg_io.hdr.serializing_sc = io->io_hdr.serializing_sc;
14019 		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_io,
14020 		    sizeof(msg_io), 0 ) != CTL_HA_STATUS_SUCCESS) {
14021 		}
14022 		/* continue on to finish IO */
14023 	}
14024 #ifdef CTL_IO_DELAY
14025 	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
14026 		struct ctl_lun *lun;
14027 
14028 		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
14029 
14030 		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
14031 	} else {
14032 		struct ctl_lun *lun;
14033 
14034 		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
14035 
14036 		if ((lun != NULL)
14037 		 && (lun->delay_info.done_delay > 0)) {
14038 			struct callout *callout;
14039 
14040 			callout = (struct callout *)&io->io_hdr.timer_bytes;
14041 			callout_init(callout, /*mpsafe*/ 1);
14042 			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
14043 			callout_reset(callout,
14044 				      lun->delay_info.done_delay * hz,
14045 				      ctl_done_timer_wakeup, io);
14046 			if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
14047 				lun->delay_info.done_delay = 0;
14048 			return;
14049 		}
14050 	}
14051 #endif /* CTL_IO_DELAY */
14052 
14053 	ctl_enqueue_done(io);
14054 }
14055 
14056 int
14057 ctl_isc(struct ctl_scsiio *ctsio)
14058 {
14059 	struct ctl_lun *lun;
14060 	int retval;
14061 
14062 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
14063 
14064 	CTL_DEBUG_PRINT(("ctl_isc: command: %02x\n", ctsio->cdb[0]));
14065 
14066 	CTL_DEBUG_PRINT(("ctl_isc: calling data_submit()\n"));
14067 
14068 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
14069 
14070 	return (retval);
14071 }
14072 
14073 
14074 static void
14075 ctl_work_thread(void *arg)
14076 {
14077 	struct ctl_thread *thr = (struct ctl_thread *)arg;
14078 	struct ctl_softc *softc = thr->ctl_softc;
14079 	union ctl_io *io;
14080 	int retval;
14081 
14082 	CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
14083 
14084 	for (;;) {
14085 		retval = 0;
14086 
14087 		/*
14088 		 * We handle the queues in this order:
14089 		 * - ISC
14090 		 * - done queue (to free up resources, unblock other commands)
14091 		 * - RtR queue
14092 		 * - incoming queue
14093 		 *
14094 		 * If those queues are empty, we break out of the loop and
14095 		 * go to sleep.
14096 		 */
14097 		mtx_lock(&thr->queue_lock);
14098 		io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
14099 		if (io != NULL) {
14100 			STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
14101 			mtx_unlock(&thr->queue_lock);
14102 			ctl_handle_isc(io);
14103 			continue;
14104 		}
14105 		io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
14106 		if (io != NULL) {
14107 			STAILQ_REMOVE_HEAD(&thr->done_queue, links);
14108 			/* clear any blocked commands, call fe_done */
14109 			mtx_unlock(&thr->queue_lock);
14110 			retval = ctl_process_done(io);
14111 			continue;
14112 		}
14113 		io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
14114 		if (io != NULL) {
14115 			STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
14116 			mtx_unlock(&thr->queue_lock);
14117 			if (io->io_hdr.io_type == CTL_IO_TASK)
14118 				ctl_run_task(io);
14119 			else
14120 				ctl_scsiio_precheck(softc, &io->scsiio);
14121 			continue;
14122 		}
14123 		if (!ctl_pause_rtr) {
14124 			io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
14125 			if (io != NULL) {
14126 				STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
14127 				mtx_unlock(&thr->queue_lock);
14128 				retval = ctl_scsiio(&io->scsiio);
14129 				if (retval != CTL_RETVAL_COMPLETE)
14130 					CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
14131 				continue;
14132 			}
14133 		}
14134 
14135 		/* Sleep until we have something to do. */
14136 		mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
14137 	}
14138 }
14139 
14140 static void
14141 ctl_lun_thread(void *arg)
14142 {
14143 	struct ctl_softc *softc = (struct ctl_softc *)arg;
14144 	struct ctl_be_lun *be_lun;
14145 	int retval;
14146 
14147 	CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
14148 
14149 	for (;;) {
14150 		retval = 0;
14151 		mtx_lock(&softc->ctl_lock);
14152 		be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
14153 		if (be_lun != NULL) {
14154 			STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
14155 			mtx_unlock(&softc->ctl_lock);
14156 			ctl_create_lun(be_lun);
14157 			continue;
14158 		}
14159 
14160 		/* Sleep until we have something to do. */
14161 		mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
14162 		    PDROP | PRIBIO, "-", 0);
14163 	}
14164 }
14165 
14166 static void
14167 ctl_enqueue_incoming(union ctl_io *io)
14168 {
14169 	struct ctl_softc *softc = control_softc;
14170 	struct ctl_thread *thr;
14171 	u_int idx;
14172 
14173 	idx = (io->io_hdr.nexus.targ_port * 127 +
14174 	       io->io_hdr.nexus.initid.id) % worker_threads;
14175 	thr = &softc->threads[idx];
14176 	mtx_lock(&thr->queue_lock);
14177 	STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
14178 	mtx_unlock(&thr->queue_lock);
14179 	wakeup(thr);
14180 }
14181 
14182 static void
14183 ctl_enqueue_rtr(union ctl_io *io)
14184 {
14185 	struct ctl_softc *softc = control_softc;
14186 	struct ctl_thread *thr;
14187 
14188 	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14189 	mtx_lock(&thr->queue_lock);
14190 	STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
14191 	mtx_unlock(&thr->queue_lock);
14192 	wakeup(thr);
14193 }
14194 
14195 static void
14196 ctl_enqueue_done(union ctl_io *io)
14197 {
14198 	struct ctl_softc *softc = control_softc;
14199 	struct ctl_thread *thr;
14200 
14201 	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14202 	mtx_lock(&thr->queue_lock);
14203 	STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
14204 	mtx_unlock(&thr->queue_lock);
14205 	wakeup(thr);
14206 }
14207 
14208 static void
14209 ctl_enqueue_isc(union ctl_io *io)
14210 {
14211 	struct ctl_softc *softc = control_softc;
14212 	struct ctl_thread *thr;
14213 
14214 	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14215 	mtx_lock(&thr->queue_lock);
14216 	STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
14217 	mtx_unlock(&thr->queue_lock);
14218 	wakeup(thr);
14219 }
14220 
14221 /* Initialization and failover */
14222 
14223 void
14224 ctl_init_isc_msg(void)
14225 {
14226 	printf("CTL: Still calling this thing\n");
14227 }
14228 
14229 /*
14230  * Init component
14231  * 	Initializes component into configuration defined by bootMode
14232  *	(see hasc-sv.c)
14233  *  	returns hasc_Status:
14234  * 		OK
14235  *		ERROR - fatal error
14236  */
14237 static ctl_ha_comp_status
14238 ctl_isc_init(struct ctl_ha_component *c)
14239 {
14240 	ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14241 
14242 	c->status = ret;
14243 	return ret;
14244 }
14245 
14246 /* Start component
14247  * 	Starts component in state requested. If component starts successfully,
14248  *	it must set its own state to the requestrd state
14249  *	When requested state is HASC_STATE_HA, the component may refine it
14250  * 	by adding _SLAVE or _MASTER flags.
14251  *	Currently allowed state transitions are:
14252  *	UNKNOWN->HA		- initial startup
14253  *	UNKNOWN->SINGLE - initial startup when no parter detected
14254  *	HA->SINGLE		- failover
14255  * returns ctl_ha_comp_status:
14256  * 		OK	- component successfully started in requested state
14257  *		FAILED  - could not start the requested state, failover may
14258  * 			  be possible
14259  *		ERROR	- fatal error detected, no future startup possible
14260  */
14261 static ctl_ha_comp_status
14262 ctl_isc_start(struct ctl_ha_component *c, ctl_ha_state state)
14263 {
14264 	ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14265 
14266 	printf("%s: go\n", __func__);
14267 
14268 	// UNKNOWN->HA or UNKNOWN->SINGLE (bootstrap)
14269 	if (c->state == CTL_HA_STATE_UNKNOWN ) {
14270 		ctl_is_single = 0;
14271 		if (ctl_ha_msg_create(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
14272 		    != CTL_HA_STATUS_SUCCESS) {
14273 			printf("ctl_isc_start: ctl_ha_msg_create failed.\n");
14274 			ret = CTL_HA_COMP_STATUS_ERROR;
14275 		}
14276 	} else if (CTL_HA_STATE_IS_HA(c->state)
14277 		&& CTL_HA_STATE_IS_SINGLE(state)){
14278 		// HA->SINGLE transition
14279 	        ctl_failover();
14280 		ctl_is_single = 1;
14281 	} else {
14282 		printf("ctl_isc_start:Invalid state transition %X->%X\n",
14283 		       c->state, state);
14284 		ret = CTL_HA_COMP_STATUS_ERROR;
14285 	}
14286 	if (CTL_HA_STATE_IS_SINGLE(state))
14287 		ctl_is_single = 1;
14288 
14289 	c->state = state;
14290 	c->status = ret;
14291 	return ret;
14292 }
14293 
14294 /*
14295  * Quiesce component
14296  * The component must clear any error conditions (set status to OK) and
14297  * prepare itself to another Start call
14298  * returns ctl_ha_comp_status:
14299  * 	OK
14300  *	ERROR
14301  */
14302 static ctl_ha_comp_status
14303 ctl_isc_quiesce(struct ctl_ha_component *c)
14304 {
14305 	int ret = CTL_HA_COMP_STATUS_OK;
14306 
14307 	ctl_pause_rtr = 1;
14308 	c->status = ret;
14309 	return ret;
14310 }
14311 
14312 struct ctl_ha_component ctl_ha_component_ctlisc =
14313 {
14314 	.name = "CTL ISC",
14315 	.state = CTL_HA_STATE_UNKNOWN,
14316 	.init = ctl_isc_init,
14317 	.start = ctl_isc_start,
14318 	.quiesce = ctl_isc_quiesce
14319 };
14320 
14321 /*
14322  *  vim: ts=8
14323  */
14324