xref: /freebsd/sys/cam/ctl/ctl.c (revision 38d120bc13ac1de5b739b67b87016b9122149374)
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/ctype.h>
50 #include <sys/kernel.h>
51 #include <sys/types.h>
52 #include <sys/kthread.h>
53 #include <sys/bio.h>
54 #include <sys/fcntl.h>
55 #include <sys/lock.h>
56 #include <sys/module.h>
57 #include <sys/mutex.h>
58 #include <sys/condvar.h>
59 #include <sys/malloc.h>
60 #include <sys/conf.h>
61 #include <sys/ioccom.h>
62 #include <sys/queue.h>
63 #include <sys/sbuf.h>
64 #include <sys/smp.h>
65 #include <sys/endian.h>
66 #include <sys/sysctl.h>
67 #include <vm/uma.h>
68 
69 #include <cam/cam.h>
70 #include <cam/scsi/scsi_all.h>
71 #include <cam/scsi/scsi_da.h>
72 #include <cam/ctl/ctl_io.h>
73 #include <cam/ctl/ctl.h>
74 #include <cam/ctl/ctl_frontend.h>
75 #include <cam/ctl/ctl_frontend_internal.h>
76 #include <cam/ctl/ctl_util.h>
77 #include <cam/ctl/ctl_backend.h>
78 #include <cam/ctl/ctl_ioctl.h>
79 #include <cam/ctl/ctl_ha.h>
80 #include <cam/ctl/ctl_private.h>
81 #include <cam/ctl/ctl_debug.h>
82 #include <cam/ctl/ctl_scsi_all.h>
83 #include <cam/ctl/ctl_error.h>
84 
85 struct ctl_softc *control_softc = NULL;
86 
87 /*
88  * Size and alignment macros needed for Copan-specific HA hardware.  These
89  * can go away when the HA code is re-written, and uses busdma for any
90  * hardware.
91  */
92 #define	CTL_ALIGN_8B(target, source, type)				\
93 	if (((uint32_t)source & 0x7) != 0)				\
94 		target = (type)(source + (0x8 - ((uint32_t)source & 0x7)));\
95 	else								\
96 		target = (type)source;
97 
98 #define	CTL_SIZE_8B(target, size)					\
99 	if ((size & 0x7) != 0)						\
100 		target = size + (0x8 - (size & 0x7));			\
101 	else								\
102 		target = size;
103 
104 #define CTL_ALIGN_8B_MARGIN	16
105 
106 /*
107  * Template mode pages.
108  */
109 
110 /*
111  * Note that these are default values only.  The actual values will be
112  * filled in when the user does a mode sense.
113  */
114 static struct copan_debugconf_subpage debugconf_page_default = {
115 	DBGCNF_PAGE_CODE | SMPH_SPF,	/* page_code */
116 	DBGCNF_SUBPAGE_CODE,		/* subpage */
117 	{(sizeof(struct copan_debugconf_subpage) - 4) >> 8,
118 	 (sizeof(struct copan_debugconf_subpage) - 4) >> 0}, /* page_length */
119 	DBGCNF_VERSION,			/* page_version */
120 	{CTL_TIME_IO_DEFAULT_SECS>>8,
121 	 CTL_TIME_IO_DEFAULT_SECS>>0},	/* ctl_time_io_secs */
122 };
123 
124 static struct copan_debugconf_subpage debugconf_page_changeable = {
125 	DBGCNF_PAGE_CODE | SMPH_SPF,	/* page_code */
126 	DBGCNF_SUBPAGE_CODE,		/* subpage */
127 	{(sizeof(struct copan_debugconf_subpage) - 4) >> 8,
128 	 (sizeof(struct copan_debugconf_subpage) - 4) >> 0}, /* page_length */
129 	0,				/* page_version */
130 	{0xff,0xff},			/* ctl_time_io_secs */
131 };
132 
133 static struct scsi_da_rw_recovery_page rw_er_page_default = {
134 	/*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
135 	/*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
136 	/*byte3*/SMS_RWER_AWRE|SMS_RWER_ARRE,
137 	/*read_retry_count*/0,
138 	/*correction_span*/0,
139 	/*head_offset_count*/0,
140 	/*data_strobe_offset_cnt*/0,
141 	/*byte8*/SMS_RWER_LBPERE,
142 	/*write_retry_count*/0,
143 	/*reserved2*/0,
144 	/*recovery_time_limit*/{0, 0},
145 };
146 
147 static struct scsi_da_rw_recovery_page rw_er_page_changeable = {
148 	/*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
149 	/*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
150 	/*byte3*/0,
151 	/*read_retry_count*/0,
152 	/*correction_span*/0,
153 	/*head_offset_count*/0,
154 	/*data_strobe_offset_cnt*/0,
155 	/*byte8*/0,
156 	/*write_retry_count*/0,
157 	/*reserved2*/0,
158 	/*recovery_time_limit*/{0, 0},
159 };
160 
161 static struct scsi_format_page format_page_default = {
162 	/*page_code*/SMS_FORMAT_DEVICE_PAGE,
163 	/*page_length*/sizeof(struct scsi_format_page) - 2,
164 	/*tracks_per_zone*/ {0, 0},
165 	/*alt_sectors_per_zone*/ {0, 0},
166 	/*alt_tracks_per_zone*/ {0, 0},
167 	/*alt_tracks_per_lun*/ {0, 0},
168 	/*sectors_per_track*/ {(CTL_DEFAULT_SECTORS_PER_TRACK >> 8) & 0xff,
169 			        CTL_DEFAULT_SECTORS_PER_TRACK & 0xff},
170 	/*bytes_per_sector*/ {0, 0},
171 	/*interleave*/ {0, 0},
172 	/*track_skew*/ {0, 0},
173 	/*cylinder_skew*/ {0, 0},
174 	/*flags*/ SFP_HSEC,
175 	/*reserved*/ {0, 0, 0}
176 };
177 
178 static struct scsi_format_page format_page_changeable = {
179 	/*page_code*/SMS_FORMAT_DEVICE_PAGE,
180 	/*page_length*/sizeof(struct scsi_format_page) - 2,
181 	/*tracks_per_zone*/ {0, 0},
182 	/*alt_sectors_per_zone*/ {0, 0},
183 	/*alt_tracks_per_zone*/ {0, 0},
184 	/*alt_tracks_per_lun*/ {0, 0},
185 	/*sectors_per_track*/ {0, 0},
186 	/*bytes_per_sector*/ {0, 0},
187 	/*interleave*/ {0, 0},
188 	/*track_skew*/ {0, 0},
189 	/*cylinder_skew*/ {0, 0},
190 	/*flags*/ 0,
191 	/*reserved*/ {0, 0, 0}
192 };
193 
194 static struct scsi_rigid_disk_page rigid_disk_page_default = {
195 	/*page_code*/SMS_RIGID_DISK_PAGE,
196 	/*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
197 	/*cylinders*/ {0, 0, 0},
198 	/*heads*/ CTL_DEFAULT_HEADS,
199 	/*start_write_precomp*/ {0, 0, 0},
200 	/*start_reduced_current*/ {0, 0, 0},
201 	/*step_rate*/ {0, 0},
202 	/*landing_zone_cylinder*/ {0, 0, 0},
203 	/*rpl*/ SRDP_RPL_DISABLED,
204 	/*rotational_offset*/ 0,
205 	/*reserved1*/ 0,
206 	/*rotation_rate*/ {(CTL_DEFAULT_ROTATION_RATE >> 8) & 0xff,
207 			   CTL_DEFAULT_ROTATION_RATE & 0xff},
208 	/*reserved2*/ {0, 0}
209 };
210 
211 static struct scsi_rigid_disk_page rigid_disk_page_changeable = {
212 	/*page_code*/SMS_RIGID_DISK_PAGE,
213 	/*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
214 	/*cylinders*/ {0, 0, 0},
215 	/*heads*/ 0,
216 	/*start_write_precomp*/ {0, 0, 0},
217 	/*start_reduced_current*/ {0, 0, 0},
218 	/*step_rate*/ {0, 0},
219 	/*landing_zone_cylinder*/ {0, 0, 0},
220 	/*rpl*/ 0,
221 	/*rotational_offset*/ 0,
222 	/*reserved1*/ 0,
223 	/*rotation_rate*/ {0, 0},
224 	/*reserved2*/ {0, 0}
225 };
226 
227 static struct scsi_caching_page caching_page_default = {
228 	/*page_code*/SMS_CACHING_PAGE,
229 	/*page_length*/sizeof(struct scsi_caching_page) - 2,
230 	/*flags1*/ SCP_DISC | SCP_WCE,
231 	/*ret_priority*/ 0,
232 	/*disable_pf_transfer_len*/ {0xff, 0xff},
233 	/*min_prefetch*/ {0, 0},
234 	/*max_prefetch*/ {0xff, 0xff},
235 	/*max_pf_ceiling*/ {0xff, 0xff},
236 	/*flags2*/ 0,
237 	/*cache_segments*/ 0,
238 	/*cache_seg_size*/ {0, 0},
239 	/*reserved*/ 0,
240 	/*non_cache_seg_size*/ {0, 0, 0}
241 };
242 
243 static struct scsi_caching_page caching_page_changeable = {
244 	/*page_code*/SMS_CACHING_PAGE,
245 	/*page_length*/sizeof(struct scsi_caching_page) - 2,
246 	/*flags1*/ SCP_WCE | SCP_RCD,
247 	/*ret_priority*/ 0,
248 	/*disable_pf_transfer_len*/ {0, 0},
249 	/*min_prefetch*/ {0, 0},
250 	/*max_prefetch*/ {0, 0},
251 	/*max_pf_ceiling*/ {0, 0},
252 	/*flags2*/ 0,
253 	/*cache_segments*/ 0,
254 	/*cache_seg_size*/ {0, 0},
255 	/*reserved*/ 0,
256 	/*non_cache_seg_size*/ {0, 0, 0}
257 };
258 
259 static struct scsi_control_page control_page_default = {
260 	/*page_code*/SMS_CONTROL_MODE_PAGE,
261 	/*page_length*/sizeof(struct scsi_control_page) - 2,
262 	/*rlec*/0,
263 	/*queue_flags*/SCP_QUEUE_ALG_RESTRICTED,
264 	/*eca_and_aen*/0,
265 	/*flags4*/SCP_TAS,
266 	/*aen_holdoff_period*/{0, 0},
267 	/*busy_timeout_period*/{0, 0},
268 	/*extended_selftest_completion_time*/{0, 0}
269 };
270 
271 static struct scsi_control_page control_page_changeable = {
272 	/*page_code*/SMS_CONTROL_MODE_PAGE,
273 	/*page_length*/sizeof(struct scsi_control_page) - 2,
274 	/*rlec*/SCP_DSENSE,
275 	/*queue_flags*/SCP_QUEUE_ALG_MASK,
276 	/*eca_and_aen*/SCP_SWP,
277 	/*flags4*/0,
278 	/*aen_holdoff_period*/{0, 0},
279 	/*busy_timeout_period*/{0, 0},
280 	/*extended_selftest_completion_time*/{0, 0}
281 };
282 
283 static struct scsi_info_exceptions_page ie_page_default = {
284 	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
285 	/*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
286 	/*info_flags*/SIEP_FLAGS_DEXCPT,
287 	/*mrie*/0,
288 	/*interval_timer*/{0, 0, 0, 0},
289 	/*report_count*/{0, 0, 0, 0}
290 };
291 
292 static struct scsi_info_exceptions_page ie_page_changeable = {
293 	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
294 	/*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
295 	/*info_flags*/0,
296 	/*mrie*/0,
297 	/*interval_timer*/{0, 0, 0, 0},
298 	/*report_count*/{0, 0, 0, 0}
299 };
300 
301 #define CTL_LBPM_LEN	(sizeof(struct ctl_logical_block_provisioning_page) - 4)
302 
303 static struct ctl_logical_block_provisioning_page lbp_page_default = {{
304 	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
305 	/*subpage_code*/0x02,
306 	/*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
307 	/*flags*/0,
308 	/*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
309 	/*descr*/{}},
310 	{{/*flags*/0,
311 	  /*resource*/0x01,
312 	  /*reserved*/{0, 0},
313 	  /*count*/{0, 0, 0, 0}},
314 	 {/*flags*/0,
315 	  /*resource*/0x02,
316 	  /*reserved*/{0, 0},
317 	  /*count*/{0, 0, 0, 0}},
318 	 {/*flags*/0,
319 	  /*resource*/0xf1,
320 	  /*reserved*/{0, 0},
321 	  /*count*/{0, 0, 0, 0}},
322 	 {/*flags*/0,
323 	  /*resource*/0xf2,
324 	  /*reserved*/{0, 0},
325 	  /*count*/{0, 0, 0, 0}}
326 	}
327 };
328 
329 static struct ctl_logical_block_provisioning_page lbp_page_changeable = {{
330 	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
331 	/*subpage_code*/0x02,
332 	/*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
333 	/*flags*/0,
334 	/*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
335 	/*descr*/{}},
336 	{{/*flags*/0,
337 	  /*resource*/0,
338 	  /*reserved*/{0, 0},
339 	  /*count*/{0, 0, 0, 0}},
340 	 {/*flags*/0,
341 	  /*resource*/0,
342 	  /*reserved*/{0, 0},
343 	  /*count*/{0, 0, 0, 0}},
344 	 {/*flags*/0,
345 	  /*resource*/0,
346 	  /*reserved*/{0, 0},
347 	  /*count*/{0, 0, 0, 0}},
348 	 {/*flags*/0,
349 	  /*resource*/0,
350 	  /*reserved*/{0, 0},
351 	  /*count*/{0, 0, 0, 0}}
352 	}
353 };
354 
355 /*
356  * XXX KDM move these into the softc.
357  */
358 static int rcv_sync_msg;
359 static uint8_t ctl_pause_rtr;
360 
361 SYSCTL_NODE(_kern_cam, OID_AUTO, ctl, CTLFLAG_RD, 0, "CAM Target Layer");
362 static int worker_threads = -1;
363 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, worker_threads, CTLFLAG_RDTUN,
364     &worker_threads, 1, "Number of worker threads");
365 static int ctl_debug = CTL_DEBUG_NONE;
366 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, debug, CTLFLAG_RWTUN,
367     &ctl_debug, 0, "Enabled debug flags");
368 
369 /*
370  * Supported pages (0x00), Serial number (0x80), Device ID (0x83),
371  * Extended INQUIRY Data (0x86), Mode Page Policy (0x87),
372  * SCSI Ports (0x88), Third-party Copy (0x8F), Block limits (0xB0),
373  * Block Device Characteristics (0xB1) and Logical Block Provisioning (0xB2)
374  */
375 #define SCSI_EVPD_NUM_SUPPORTED_PAGES	10
376 
377 static void ctl_isc_event_handler(ctl_ha_channel chanel, ctl_ha_event event,
378 				  int param);
379 static void ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest);
380 static int ctl_init(void);
381 void ctl_shutdown(void);
382 static int ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td);
383 static int ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td);
384 static void ctl_ioctl_online(void *arg);
385 static void ctl_ioctl_offline(void *arg);
386 static int ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id);
387 static int ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id);
388 static int ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio);
389 static int ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio);
390 static int ctl_ioctl_submit_wait(union ctl_io *io);
391 static void ctl_ioctl_datamove(union ctl_io *io);
392 static void ctl_ioctl_done(union ctl_io *io);
393 static void ctl_ioctl_hard_startstop_callback(void *arg,
394 					      struct cfi_metatask *metatask);
395 static void ctl_ioctl_bbrread_callback(void *arg,struct cfi_metatask *metatask);
396 static int ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
397 			      struct ctl_ooa *ooa_hdr,
398 			      struct ctl_ooa_entry *kern_entries);
399 static int ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
400 		     struct thread *td);
401 static uint32_t ctl_map_lun(int port_num, uint32_t lun);
402 static uint32_t ctl_map_lun_back(int port_num, uint32_t lun);
403 static int ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
404 			 struct ctl_be_lun *be_lun, struct ctl_id target_id);
405 static int ctl_free_lun(struct ctl_lun *lun);
406 static void ctl_create_lun(struct ctl_be_lun *be_lun);
407 /**
408 static void ctl_failover_change_pages(struct ctl_softc *softc,
409 				      struct ctl_scsiio *ctsio, int master);
410 **/
411 
412 static int ctl_do_mode_select(union ctl_io *io);
413 static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
414 			   uint64_t res_key, uint64_t sa_res_key,
415 			   uint8_t type, uint32_t residx,
416 			   struct ctl_scsiio *ctsio,
417 			   struct scsi_per_res_out *cdb,
418 			   struct scsi_per_res_out_parms* param);
419 static void ctl_pro_preempt_other(struct ctl_lun *lun,
420 				  union ctl_ha_msg *msg);
421 static void ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg);
422 static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
423 static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
424 static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
425 static int ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len);
426 static int ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len);
427 static int ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio,
428 					 int alloc_len);
429 static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
430 					 int alloc_len);
431 static int ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len);
432 static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
433 static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
434 static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
435 static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len);
436 static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2,
437     bool seq);
438 static ctl_action ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2);
439 static ctl_action ctl_check_for_blockage(struct ctl_lun *lun,
440     union ctl_io *pending_io, union ctl_io *ooa_io);
441 static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
442 				union ctl_io *starting_io);
443 static int ctl_check_blocked(struct ctl_lun *lun);
444 static int ctl_scsiio_lun_check(struct ctl_softc *ctl_softc,
445 				struct ctl_lun *lun,
446 				const struct ctl_cmd_entry *entry,
447 				struct ctl_scsiio *ctsio);
448 //static int ctl_check_rtr(union ctl_io *pending_io, struct ctl_softc *softc);
449 static void ctl_failover(void);
450 static int ctl_scsiio_precheck(struct ctl_softc *ctl_softc,
451 			       struct ctl_scsiio *ctsio);
452 static int ctl_scsiio(struct ctl_scsiio *ctsio);
453 
454 static int ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
455 static int ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
456 			    ctl_ua_type ua_type);
457 static int ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io,
458 			 ctl_ua_type ua_type);
459 static int ctl_abort_task(union ctl_io *io);
460 static int ctl_abort_task_set(union ctl_io *io);
461 static int ctl_i_t_nexus_reset(union ctl_io *io);
462 static void ctl_run_task(union ctl_io *io);
463 #ifdef CTL_IO_DELAY
464 static void ctl_datamove_timer_wakeup(void *arg);
465 static void ctl_done_timer_wakeup(void *arg);
466 #endif /* CTL_IO_DELAY */
467 
468 static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
469 static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
470 static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
471 static void ctl_datamove_remote_write(union ctl_io *io);
472 static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
473 static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
474 static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
475 static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
476 				    ctl_ha_dt_cb callback);
477 static void ctl_datamove_remote_read(union ctl_io *io);
478 static void ctl_datamove_remote(union ctl_io *io);
479 static int ctl_process_done(union ctl_io *io);
480 static void ctl_lun_thread(void *arg);
481 static void ctl_thresh_thread(void *arg);
482 static void ctl_work_thread(void *arg);
483 static void ctl_enqueue_incoming(union ctl_io *io);
484 static void ctl_enqueue_rtr(union ctl_io *io);
485 static void ctl_enqueue_done(union ctl_io *io);
486 static void ctl_enqueue_isc(union ctl_io *io);
487 static const struct ctl_cmd_entry *
488     ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa);
489 static const struct ctl_cmd_entry *
490     ctl_validate_command(struct ctl_scsiio *ctsio);
491 static int ctl_cmd_applicable(uint8_t lun_type,
492     const struct ctl_cmd_entry *entry);
493 
494 /*
495  * Load the serialization table.  This isn't very pretty, but is probably
496  * the easiest way to do it.
497  */
498 #include "ctl_ser_table.c"
499 
500 /*
501  * We only need to define open, close and ioctl routines for this driver.
502  */
503 static struct cdevsw ctl_cdevsw = {
504 	.d_version =	D_VERSION,
505 	.d_flags =	0,
506 	.d_open =	ctl_open,
507 	.d_close =	ctl_close,
508 	.d_ioctl =	ctl_ioctl,
509 	.d_name =	"ctl",
510 };
511 
512 
513 MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
514 MALLOC_DEFINE(M_CTLIO, "ctlio", "Memory used for CTL requests");
515 
516 static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
517 
518 static moduledata_t ctl_moduledata = {
519 	"ctl",
520 	ctl_module_event_handler,
521 	NULL
522 };
523 
524 DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
525 MODULE_VERSION(ctl, 1);
526 
527 static struct ctl_frontend ioctl_frontend =
528 {
529 	.name = "ioctl",
530 };
531 
532 static void
533 ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
534 			    union ctl_ha_msg *msg_info)
535 {
536 	struct ctl_scsiio *ctsio;
537 
538 	if (msg_info->hdr.original_sc == NULL) {
539 		printf("%s: original_sc == NULL!\n", __func__);
540 		/* XXX KDM now what? */
541 		return;
542 	}
543 
544 	ctsio = &msg_info->hdr.original_sc->scsiio;
545 	ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
546 	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
547 	ctsio->io_hdr.status = msg_info->hdr.status;
548 	ctsio->scsi_status = msg_info->scsi.scsi_status;
549 	ctsio->sense_len = msg_info->scsi.sense_len;
550 	ctsio->sense_residual = msg_info->scsi.sense_residual;
551 	ctsio->residual = msg_info->scsi.residual;
552 	memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
553 	       sizeof(ctsio->sense_data));
554 	memcpy(&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
555 	       &msg_info->scsi.lbalen, sizeof(msg_info->scsi.lbalen));
556 	ctl_enqueue_isc((union ctl_io *)ctsio);
557 }
558 
559 static void
560 ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
561 				union ctl_ha_msg *msg_info)
562 {
563 	struct ctl_scsiio *ctsio;
564 
565 	if (msg_info->hdr.serializing_sc == NULL) {
566 		printf("%s: serializing_sc == NULL!\n", __func__);
567 		/* XXX KDM now what? */
568 		return;
569 	}
570 
571 	ctsio = &msg_info->hdr.serializing_sc->scsiio;
572 #if 0
573 	/*
574 	 * Attempt to catch the situation where an I/O has
575 	 * been freed, and we're using it again.
576 	 */
577 	if (ctsio->io_hdr.io_type == 0xff) {
578 		union ctl_io *tmp_io;
579 		tmp_io = (union ctl_io *)ctsio;
580 		printf("%s: %p use after free!\n", __func__,
581 		       ctsio);
582 		printf("%s: type %d msg %d cdb %x iptl: "
583 		       "%d:%d:%d:%d tag 0x%04x "
584 		       "flag %#x status %x\n",
585 			__func__,
586 			tmp_io->io_hdr.io_type,
587 			tmp_io->io_hdr.msg_type,
588 			tmp_io->scsiio.cdb[0],
589 			tmp_io->io_hdr.nexus.initid.id,
590 			tmp_io->io_hdr.nexus.targ_port,
591 			tmp_io->io_hdr.nexus.targ_target.id,
592 			tmp_io->io_hdr.nexus.targ_lun,
593 			(tmp_io->io_hdr.io_type ==
594 			CTL_IO_TASK) ?
595 			tmp_io->taskio.tag_num :
596 			tmp_io->scsiio.tag_num,
597 		        tmp_io->io_hdr.flags,
598 			tmp_io->io_hdr.status);
599 	}
600 #endif
601 	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
602 	ctl_enqueue_isc((union ctl_io *)ctsio);
603 }
604 
605 /*
606  * ISC (Inter Shelf Communication) event handler.  Events from the HA
607  * subsystem come in here.
608  */
609 static void
610 ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
611 {
612 	struct ctl_softc *ctl_softc;
613 	union ctl_io *io;
614 	struct ctl_prio *presio;
615 	ctl_ha_status isc_status;
616 
617 	ctl_softc = control_softc;
618 	io = NULL;
619 
620 
621 #if 0
622 	printf("CTL: Isc Msg event %d\n", event);
623 #endif
624 	if (event == CTL_HA_EVT_MSG_RECV) {
625 		union ctl_ha_msg msg_info;
626 
627 		isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
628 					     sizeof(msg_info), /*wait*/ 0);
629 #if 0
630 		printf("CTL: msg_type %d\n", msg_info.msg_type);
631 #endif
632 		if (isc_status != 0) {
633 			printf("Error receiving message, status = %d\n",
634 			       isc_status);
635 			return;
636 		}
637 
638 		switch (msg_info.hdr.msg_type) {
639 		case CTL_MSG_SERIALIZE:
640 #if 0
641 			printf("Serialize\n");
642 #endif
643 			io = ctl_alloc_io_nowait(ctl_softc->othersc_pool);
644 			if (io == NULL) {
645 				printf("ctl_isc_event_handler: can't allocate "
646 				       "ctl_io!\n");
647 				/* Bad Juju */
648 				/* Need to set busy and send msg back */
649 				msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
650 				msg_info.hdr.status = CTL_SCSI_ERROR;
651 				msg_info.scsi.scsi_status = SCSI_STATUS_BUSY;
652 				msg_info.scsi.sense_len = 0;
653 			        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
654 				    sizeof(msg_info), 0) > CTL_HA_STATUS_SUCCESS){
655 				}
656 				goto bailout;
657 			}
658 			ctl_zero_io(io);
659 			// populate ctsio from msg_info
660 			io->io_hdr.io_type = CTL_IO_SCSI;
661 			io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
662 			io->io_hdr.original_sc = msg_info.hdr.original_sc;
663 #if 0
664 			printf("pOrig %x\n", (int)msg_info.original_sc);
665 #endif
666 			io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
667 					    CTL_FLAG_IO_ACTIVE;
668 			/*
669 			 * If we're in serialization-only mode, we don't
670 			 * want to go through full done processing.  Thus
671 			 * the COPY flag.
672 			 *
673 			 * XXX KDM add another flag that is more specific.
674 			 */
675 			if (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)
676 				io->io_hdr.flags |= CTL_FLAG_INT_COPY;
677 			io->io_hdr.nexus = msg_info.hdr.nexus;
678 #if 0
679 			printf("targ %d, port %d, iid %d, lun %d\n",
680 			       io->io_hdr.nexus.targ_target.id,
681 			       io->io_hdr.nexus.targ_port,
682 			       io->io_hdr.nexus.initid.id,
683 			       io->io_hdr.nexus.targ_lun);
684 #endif
685 			io->scsiio.tag_num = msg_info.scsi.tag_num;
686 			io->scsiio.tag_type = msg_info.scsi.tag_type;
687 			memcpy(io->scsiio.cdb, msg_info.scsi.cdb,
688 			       CTL_MAX_CDBLEN);
689 			if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
690 				const struct ctl_cmd_entry *entry;
691 
692 				entry = ctl_get_cmd_entry(&io->scsiio, NULL);
693 				io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
694 				io->io_hdr.flags |=
695 					entry->flags & CTL_FLAG_DATA_MASK;
696 			}
697 			ctl_enqueue_isc(io);
698 			break;
699 
700 		/* Performed on the Originating SC, XFER mode only */
701 		case CTL_MSG_DATAMOVE: {
702 			struct ctl_sg_entry *sgl;
703 			int i, j;
704 
705 			io = msg_info.hdr.original_sc;
706 			if (io == NULL) {
707 				printf("%s: original_sc == NULL!\n", __func__);
708 				/* XXX KDM do something here */
709 				break;
710 			}
711 			io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
712 			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
713 			/*
714 			 * Keep track of this, we need to send it back over
715 			 * when the datamove is complete.
716 			 */
717 			io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
718 
719 			if (msg_info.dt.sg_sequence == 0) {
720 				/*
721 				 * XXX KDM we use the preallocated S/G list
722 				 * here, but we'll need to change this to
723 				 * dynamic allocation if we need larger S/G
724 				 * lists.
725 				 */
726 				if (msg_info.dt.kern_sg_entries >
727 				    sizeof(io->io_hdr.remote_sglist) /
728 				    sizeof(io->io_hdr.remote_sglist[0])) {
729 					printf("%s: number of S/G entries "
730 					    "needed %u > allocated num %zd\n",
731 					    __func__,
732 					    msg_info.dt.kern_sg_entries,
733 					    sizeof(io->io_hdr.remote_sglist)/
734 					    sizeof(io->io_hdr.remote_sglist[0]));
735 
736 					/*
737 					 * XXX KDM send a message back to
738 					 * the other side to shut down the
739 					 * DMA.  The error will come back
740 					 * through via the normal channel.
741 					 */
742 					break;
743 				}
744 				sgl = io->io_hdr.remote_sglist;
745 				memset(sgl, 0,
746 				       sizeof(io->io_hdr.remote_sglist));
747 
748 				io->scsiio.kern_data_ptr = (uint8_t *)sgl;
749 
750 				io->scsiio.kern_sg_entries =
751 					msg_info.dt.kern_sg_entries;
752 				io->scsiio.rem_sg_entries =
753 					msg_info.dt.kern_sg_entries;
754 				io->scsiio.kern_data_len =
755 					msg_info.dt.kern_data_len;
756 				io->scsiio.kern_total_len =
757 					msg_info.dt.kern_total_len;
758 				io->scsiio.kern_data_resid =
759 					msg_info.dt.kern_data_resid;
760 				io->scsiio.kern_rel_offset =
761 					msg_info.dt.kern_rel_offset;
762 				/*
763 				 * Clear out per-DMA flags.
764 				 */
765 				io->io_hdr.flags &= ~CTL_FLAG_RDMA_MASK;
766 				/*
767 				 * Add per-DMA flags that are set for this
768 				 * particular DMA request.
769 				 */
770 				io->io_hdr.flags |= msg_info.dt.flags &
771 						    CTL_FLAG_RDMA_MASK;
772 			} else
773 				sgl = (struct ctl_sg_entry *)
774 					io->scsiio.kern_data_ptr;
775 
776 			for (i = msg_info.dt.sent_sg_entries, j = 0;
777 			     i < (msg_info.dt.sent_sg_entries +
778 			     msg_info.dt.cur_sg_entries); i++, j++) {
779 				sgl[i].addr = msg_info.dt.sg_list[j].addr;
780 				sgl[i].len = msg_info.dt.sg_list[j].len;
781 
782 #if 0
783 				printf("%s: L: %p,%d -> %p,%d j=%d, i=%d\n",
784 				       __func__,
785 				       msg_info.dt.sg_list[j].addr,
786 				       msg_info.dt.sg_list[j].len,
787 				       sgl[i].addr, sgl[i].len, j, i);
788 #endif
789 			}
790 #if 0
791 			memcpy(&sgl[msg_info.dt.sent_sg_entries],
792 			       msg_info.dt.sg_list,
793 			       sizeof(*sgl) * msg_info.dt.cur_sg_entries);
794 #endif
795 
796 			/*
797 			 * If this is the last piece of the I/O, we've got
798 			 * the full S/G list.  Queue processing in the thread.
799 			 * Otherwise wait for the next piece.
800 			 */
801 			if (msg_info.dt.sg_last != 0)
802 				ctl_enqueue_isc(io);
803 			break;
804 		}
805 		/* Performed on the Serializing (primary) SC, XFER mode only */
806 		case CTL_MSG_DATAMOVE_DONE: {
807 			if (msg_info.hdr.serializing_sc == NULL) {
808 				printf("%s: serializing_sc == NULL!\n",
809 				       __func__);
810 				/* XXX KDM now what? */
811 				break;
812 			}
813 			/*
814 			 * We grab the sense information here in case
815 			 * there was a failure, so we can return status
816 			 * back to the initiator.
817 			 */
818 			io = msg_info.hdr.serializing_sc;
819 			io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
820 			io->io_hdr.status = msg_info.hdr.status;
821 			io->scsiio.scsi_status = msg_info.scsi.scsi_status;
822 			io->scsiio.sense_len = msg_info.scsi.sense_len;
823 			io->scsiio.sense_residual =msg_info.scsi.sense_residual;
824 			io->io_hdr.port_status = msg_info.scsi.fetd_status;
825 			io->scsiio.residual = msg_info.scsi.residual;
826 			memcpy(&io->scsiio.sense_data,&msg_info.scsi.sense_data,
827 			       sizeof(io->scsiio.sense_data));
828 			ctl_enqueue_isc(io);
829 			break;
830 		}
831 
832 		/* Preformed on Originating SC, SER_ONLY mode */
833 		case CTL_MSG_R2R:
834 			io = msg_info.hdr.original_sc;
835 			if (io == NULL) {
836 				printf("%s: Major Bummer\n", __func__);
837 				return;
838 			} else {
839 #if 0
840 				printf("pOrig %x\n",(int) ctsio);
841 #endif
842 			}
843 			io->io_hdr.msg_type = CTL_MSG_R2R;
844 			io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
845 			ctl_enqueue_isc(io);
846 			break;
847 
848 		/*
849 		 * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
850 		 * mode.
851 		 * Performed on the Originating (i.e. secondary) SC in XFER
852 		 * mode
853 		 */
854 		case CTL_MSG_FINISH_IO:
855 			if (ctl_softc->ha_mode == CTL_HA_MODE_XFER)
856 				ctl_isc_handler_finish_xfer(ctl_softc,
857 							    &msg_info);
858 			else
859 				ctl_isc_handler_finish_ser_only(ctl_softc,
860 								&msg_info);
861 			break;
862 
863 		/* Preformed on Originating SC */
864 		case CTL_MSG_BAD_JUJU:
865 			io = msg_info.hdr.original_sc;
866 			if (io == NULL) {
867 				printf("%s: Bad JUJU!, original_sc is NULL!\n",
868 				       __func__);
869 				break;
870 			}
871 			ctl_copy_sense_data(&msg_info, io);
872 			/*
873 			 * IO should have already been cleaned up on other
874 			 * SC so clear this flag so we won't send a message
875 			 * back to finish the IO there.
876 			 */
877 			io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
878 			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
879 
880 			/* io = msg_info.hdr.serializing_sc; */
881 			io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
882 			ctl_enqueue_isc(io);
883 			break;
884 
885 		/* Handle resets sent from the other side */
886 		case CTL_MSG_MANAGE_TASKS: {
887 			struct ctl_taskio *taskio;
888 			taskio = (struct ctl_taskio *)ctl_alloc_io_nowait(
889 			    ctl_softc->othersc_pool);
890 			if (taskio == NULL) {
891 				printf("ctl_isc_event_handler: can't allocate "
892 				       "ctl_io!\n");
893 				/* Bad Juju */
894 				/* should I just call the proper reset func
895 				   here??? */
896 				goto bailout;
897 			}
898 			ctl_zero_io((union ctl_io *)taskio);
899 			taskio->io_hdr.io_type = CTL_IO_TASK;
900 			taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
901 			taskio->io_hdr.nexus = msg_info.hdr.nexus;
902 			taskio->task_action = msg_info.task.task_action;
903 			taskio->tag_num = msg_info.task.tag_num;
904 			taskio->tag_type = msg_info.task.tag_type;
905 #ifdef CTL_TIME_IO
906 			taskio->io_hdr.start_time = time_uptime;
907 			getbintime(&taskio->io_hdr.start_bt);
908 #if 0
909 			cs_prof_gettime(&taskio->io_hdr.start_ticks);
910 #endif
911 #endif /* CTL_TIME_IO */
912 			ctl_run_task((union ctl_io *)taskio);
913 			break;
914 		}
915 		/* Persistent Reserve action which needs attention */
916 		case CTL_MSG_PERS_ACTION:
917 			presio = (struct ctl_prio *)ctl_alloc_io_nowait(
918 			    ctl_softc->othersc_pool);
919 			if (presio == NULL) {
920 				printf("ctl_isc_event_handler: can't allocate "
921 				       "ctl_io!\n");
922 				/* Bad Juju */
923 				/* Need to set busy and send msg back */
924 				goto bailout;
925 			}
926 			ctl_zero_io((union ctl_io *)presio);
927 			presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
928 			presio->pr_msg = msg_info.pr;
929 			ctl_enqueue_isc((union ctl_io *)presio);
930 			break;
931 		case CTL_MSG_SYNC_FE:
932 			rcv_sync_msg = 1;
933 			break;
934 		default:
935 		        printf("How did I get here?\n");
936 		}
937 	} else if (event == CTL_HA_EVT_MSG_SENT) {
938 		if (param != CTL_HA_STATUS_SUCCESS) {
939 			printf("Bad status from ctl_ha_msg_send status %d\n",
940 			       param);
941 		}
942 		return;
943 	} else if (event == CTL_HA_EVT_DISCONNECT) {
944 		printf("CTL: Got a disconnect from Isc\n");
945 		return;
946 	} else {
947 		printf("ctl_isc_event_handler: Unknown event %d\n", event);
948 		return;
949 	}
950 
951 bailout:
952 	return;
953 }
954 
955 static void
956 ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
957 {
958 	struct scsi_sense_data *sense;
959 
960 	sense = &dest->scsiio.sense_data;
961 	bcopy(&src->scsi.sense_data, sense, sizeof(*sense));
962 	dest->scsiio.scsi_status = src->scsi.scsi_status;
963 	dest->scsiio.sense_len = src->scsi.sense_len;
964 	dest->io_hdr.status = src->hdr.status;
965 }
966 
967 static void
968 ctl_est_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
969 {
970 	ctl_ua_type *pu;
971 
972 	mtx_assert(&lun->lun_lock, MA_OWNED);
973 	pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
974 	if (pu == NULL)
975 		return;
976 	pu[initidx % CTL_MAX_INIT_PER_PORT] |= ua;
977 }
978 
979 static void
980 ctl_est_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
981 {
982 	int i, j;
983 
984 	mtx_assert(&lun->lun_lock, MA_OWNED);
985 	for (i = 0; i < CTL_MAX_PORTS; i++) {
986 		if (lun->pending_ua[i] == NULL)
987 			continue;
988 		for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
989 			if (i * CTL_MAX_INIT_PER_PORT + j == except)
990 				continue;
991 			lun->pending_ua[i][j] |= ua;
992 		}
993 	}
994 }
995 
996 static void
997 ctl_clr_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
998 {
999 	ctl_ua_type *pu;
1000 
1001 	mtx_assert(&lun->lun_lock, MA_OWNED);
1002 	pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1003 	if (pu == NULL)
1004 		return;
1005 	pu[initidx % CTL_MAX_INIT_PER_PORT] &= ~ua;
1006 }
1007 
1008 static void
1009 ctl_clr_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1010 {
1011 	int i, j;
1012 
1013 	mtx_assert(&lun->lun_lock, MA_OWNED);
1014 	for (i = 0; i < CTL_MAX_PORTS; i++) {
1015 		if (lun->pending_ua[i] == NULL)
1016 			continue;
1017 		for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
1018 			if (i * CTL_MAX_INIT_PER_PORT + j == except)
1019 				continue;
1020 			lun->pending_ua[i][j] &= ~ua;
1021 		}
1022 	}
1023 }
1024 
1025 static int
1026 ctl_ha_state_sysctl(SYSCTL_HANDLER_ARGS)
1027 {
1028 	struct ctl_softc *softc = (struct ctl_softc *)arg1;
1029 	struct ctl_lun *lun;
1030 	int error, value;
1031 
1032 	if (softc->flags & CTL_FLAG_ACTIVE_SHELF)
1033 		value = 0;
1034 	else
1035 		value = 1;
1036 
1037 	error = sysctl_handle_int(oidp, &value, 0, req);
1038 	if ((error != 0) || (req->newptr == NULL))
1039 		return (error);
1040 
1041 	mtx_lock(&softc->ctl_lock);
1042 	if (value == 0)
1043 		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1044 	else
1045 		softc->flags &= ~CTL_FLAG_ACTIVE_SHELF;
1046 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
1047 		mtx_lock(&lun->lun_lock);
1048 		ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
1049 		mtx_unlock(&lun->lun_lock);
1050 	}
1051 	mtx_unlock(&softc->ctl_lock);
1052 	return (0);
1053 }
1054 
1055 static int
1056 ctl_init(void)
1057 {
1058 	struct ctl_softc *softc;
1059 	void *other_pool;
1060 	struct ctl_port *port;
1061 	int i, error, retval;
1062 	//int isc_retval;
1063 
1064 	retval = 0;
1065 	ctl_pause_rtr = 0;
1066         rcv_sync_msg = 0;
1067 
1068 	control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
1069 			       M_WAITOK | M_ZERO);
1070 	softc = control_softc;
1071 
1072 	softc->dev = make_dev(&ctl_cdevsw, 0, UID_ROOT, GID_OPERATOR, 0600,
1073 			      "cam/ctl");
1074 
1075 	softc->dev->si_drv1 = softc;
1076 
1077 	/*
1078 	 * By default, return a "bad LUN" peripheral qualifier for unknown
1079 	 * LUNs.  The user can override this default using the tunable or
1080 	 * sysctl.  See the comment in ctl_inquiry_std() for more details.
1081 	 */
1082 	softc->inquiry_pq_no_lun = 1;
1083 	TUNABLE_INT_FETCH("kern.cam.ctl.inquiry_pq_no_lun",
1084 			  &softc->inquiry_pq_no_lun);
1085 	sysctl_ctx_init(&softc->sysctl_ctx);
1086 	softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
1087 		SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
1088 		CTLFLAG_RD, 0, "CAM Target Layer");
1089 
1090 	if (softc->sysctl_tree == NULL) {
1091 		printf("%s: unable to allocate sysctl tree\n", __func__);
1092 		destroy_dev(softc->dev);
1093 		free(control_softc, M_DEVBUF);
1094 		control_softc = NULL;
1095 		return (ENOMEM);
1096 	}
1097 
1098 	SYSCTL_ADD_INT(&softc->sysctl_ctx,
1099 		       SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
1100 		       "inquiry_pq_no_lun", CTLFLAG_RW,
1101 		       &softc->inquiry_pq_no_lun, 0,
1102 		       "Report no lun possible for invalid LUNs");
1103 
1104 	mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
1105 	softc->io_zone = uma_zcreate("CTL IO", sizeof(union ctl_io),
1106 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1107 	softc->open_count = 0;
1108 
1109 	/*
1110 	 * Default to actually sending a SYNCHRONIZE CACHE command down to
1111 	 * the drive.
1112 	 */
1113 	softc->flags = CTL_FLAG_REAL_SYNC;
1114 
1115 	/*
1116 	 * In Copan's HA scheme, the "master" and "slave" roles are
1117 	 * figured out through the slot the controller is in.  Although it
1118 	 * is an active/active system, someone has to be in charge.
1119 	 */
1120 	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1121 	    OID_AUTO, "ha_id", CTLFLAG_RDTUN, &softc->ha_id, 0,
1122 	    "HA head ID (0 - no HA)");
1123 	if (softc->ha_id == 0) {
1124 		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1125 		softc->is_single = 1;
1126 		softc->port_offset = 0;
1127 	} else
1128 		softc->port_offset = (softc->ha_id - 1) * CTL_MAX_PORTS;
1129 	softc->persis_offset = softc->port_offset * CTL_MAX_INIT_PER_PORT;
1130 
1131 	/*
1132 	 * XXX KDM need to figure out where we want to get our target ID
1133 	 * and WWID.  Is it different on each port?
1134 	 */
1135 	softc->target.id = 0;
1136 	softc->target.wwid[0] = 0x12345678;
1137 	softc->target.wwid[1] = 0x87654321;
1138 	STAILQ_INIT(&softc->lun_list);
1139 	STAILQ_INIT(&softc->pending_lun_queue);
1140 	STAILQ_INIT(&softc->fe_list);
1141 	STAILQ_INIT(&softc->port_list);
1142 	STAILQ_INIT(&softc->be_list);
1143 	ctl_tpc_init(softc);
1144 
1145 	if (ctl_pool_create(softc, "othersc", CTL_POOL_ENTRIES_OTHER_SC,
1146 	                    &other_pool) != 0)
1147 	{
1148 		printf("ctl: can't allocate %d entry other SC pool, "
1149 		       "exiting\n", CTL_POOL_ENTRIES_OTHER_SC);
1150 		return (ENOMEM);
1151 	}
1152 	softc->othersc_pool = other_pool;
1153 
1154 	if (worker_threads <= 0)
1155 		worker_threads = max(1, mp_ncpus / 4);
1156 	if (worker_threads > CTL_MAX_THREADS)
1157 		worker_threads = CTL_MAX_THREADS;
1158 
1159 	for (i = 0; i < worker_threads; i++) {
1160 		struct ctl_thread *thr = &softc->threads[i];
1161 
1162 		mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1163 		thr->ctl_softc = softc;
1164 		STAILQ_INIT(&thr->incoming_queue);
1165 		STAILQ_INIT(&thr->rtr_queue);
1166 		STAILQ_INIT(&thr->done_queue);
1167 		STAILQ_INIT(&thr->isc_queue);
1168 
1169 		error = kproc_kthread_add(ctl_work_thread, thr,
1170 		    &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1171 		if (error != 0) {
1172 			printf("error creating CTL work thread!\n");
1173 			ctl_pool_free(other_pool);
1174 			return (error);
1175 		}
1176 	}
1177 	error = kproc_kthread_add(ctl_lun_thread, softc,
1178 	    &softc->ctl_proc, NULL, 0, 0, "ctl", "lun");
1179 	if (error != 0) {
1180 		printf("error creating CTL lun thread!\n");
1181 		ctl_pool_free(other_pool);
1182 		return (error);
1183 	}
1184 	error = kproc_kthread_add(ctl_thresh_thread, softc,
1185 	    &softc->ctl_proc, NULL, 0, 0, "ctl", "thresh");
1186 	if (error != 0) {
1187 		printf("error creating CTL threshold thread!\n");
1188 		ctl_pool_free(other_pool);
1189 		return (error);
1190 	}
1191 	if (bootverbose)
1192 		printf("ctl: CAM Target Layer loaded\n");
1193 
1194 	/*
1195 	 * Initialize the ioctl front end.
1196 	 */
1197 	ctl_frontend_register(&ioctl_frontend);
1198 	port = &softc->ioctl_info.port;
1199 	port->frontend = &ioctl_frontend;
1200 	sprintf(softc->ioctl_info.port_name, "ioctl");
1201 	port->port_type = CTL_PORT_IOCTL;
1202 	port->num_requested_ctl_io = 100;
1203 	port->port_name = softc->ioctl_info.port_name;
1204 	port->port_online = ctl_ioctl_online;
1205 	port->port_offline = ctl_ioctl_offline;
1206 	port->onoff_arg = &softc->ioctl_info;
1207 	port->lun_enable = ctl_ioctl_lun_enable;
1208 	port->lun_disable = ctl_ioctl_lun_disable;
1209 	port->targ_lun_arg = &softc->ioctl_info;
1210 	port->fe_datamove = ctl_ioctl_datamove;
1211 	port->fe_done = ctl_ioctl_done;
1212 	port->max_targets = 15;
1213 	port->max_target_id = 15;
1214 
1215 	if (ctl_port_register(&softc->ioctl_info.port) != 0) {
1216 		printf("ctl: ioctl front end registration failed, will "
1217 		       "continue anyway\n");
1218 	}
1219 
1220 	SYSCTL_ADD_PROC(&softc->sysctl_ctx,SYSCTL_CHILDREN(softc->sysctl_tree),
1221 	    OID_AUTO, "ha_state", CTLTYPE_INT | CTLFLAG_RWTUN,
1222 	    softc, 0, ctl_ha_state_sysctl, "I", "HA state for this head");
1223 
1224 #ifdef CTL_IO_DELAY
1225 	if (sizeof(struct callout) > CTL_TIMER_BYTES) {
1226 		printf("sizeof(struct callout) %zd > CTL_TIMER_BYTES %zd\n",
1227 		       sizeof(struct callout), CTL_TIMER_BYTES);
1228 		return (EINVAL);
1229 	}
1230 #endif /* CTL_IO_DELAY */
1231 
1232 	return (0);
1233 }
1234 
1235 void
1236 ctl_shutdown(void)
1237 {
1238 	struct ctl_softc *softc;
1239 	struct ctl_lun *lun, *next_lun;
1240 
1241 	softc = (struct ctl_softc *)control_softc;
1242 
1243 	if (ctl_port_deregister(&softc->ioctl_info.port) != 0)
1244 		printf("ctl: ioctl front end deregistration failed\n");
1245 
1246 	mtx_lock(&softc->ctl_lock);
1247 
1248 	/*
1249 	 * Free up each LUN.
1250 	 */
1251 	for (lun = STAILQ_FIRST(&softc->lun_list); lun != NULL; lun = next_lun){
1252 		next_lun = STAILQ_NEXT(lun, links);
1253 		ctl_free_lun(lun);
1254 	}
1255 
1256 	mtx_unlock(&softc->ctl_lock);
1257 
1258 	ctl_frontend_deregister(&ioctl_frontend);
1259 
1260 #if 0
1261 	ctl_shutdown_thread(softc->work_thread);
1262 	mtx_destroy(&softc->queue_lock);
1263 #endif
1264 
1265 	ctl_tpc_shutdown(softc);
1266 	uma_zdestroy(softc->io_zone);
1267 	mtx_destroy(&softc->ctl_lock);
1268 
1269 	destroy_dev(softc->dev);
1270 
1271 	sysctl_ctx_free(&softc->sysctl_ctx);
1272 
1273 	free(control_softc, M_DEVBUF);
1274 	control_softc = NULL;
1275 
1276 	if (bootverbose)
1277 		printf("ctl: CAM Target Layer unloaded\n");
1278 }
1279 
1280 static int
1281 ctl_module_event_handler(module_t mod, int what, void *arg)
1282 {
1283 
1284 	switch (what) {
1285 	case MOD_LOAD:
1286 		return (ctl_init());
1287 	case MOD_UNLOAD:
1288 		return (EBUSY);
1289 	default:
1290 		return (EOPNOTSUPP);
1291 	}
1292 }
1293 
1294 /*
1295  * XXX KDM should we do some access checks here?  Bump a reference count to
1296  * prevent a CTL module from being unloaded while someone has it open?
1297  */
1298 static int
1299 ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
1300 {
1301 	return (0);
1302 }
1303 
1304 static int
1305 ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
1306 {
1307 	return (0);
1308 }
1309 
1310 int
1311 ctl_port_enable(ctl_port_type port_type)
1312 {
1313 	struct ctl_softc *softc = control_softc;
1314 	struct ctl_port *port;
1315 
1316 	if (softc->is_single == 0) {
1317 		union ctl_ha_msg msg_info;
1318 		int isc_retval;
1319 
1320 #if 0
1321 		printf("%s: HA mode, synchronizing frontend enable\n",
1322 		        __func__);
1323 #endif
1324 		msg_info.hdr.msg_type = CTL_MSG_SYNC_FE;
1325 	        if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1326 		        sizeof(msg_info), 1 )) > CTL_HA_STATUS_SUCCESS) {
1327 			printf("Sync msg send error retval %d\n", isc_retval);
1328 		}
1329 		if (!rcv_sync_msg) {
1330 			isc_retval=ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
1331 			        sizeof(msg_info), 1);
1332 		}
1333 #if 0
1334         	printf("CTL:Frontend Enable\n");
1335 	} else {
1336 		printf("%s: single mode, skipping frontend synchronization\n",
1337 		        __func__);
1338 #endif
1339 	}
1340 
1341 	STAILQ_FOREACH(port, &softc->port_list, links) {
1342 		if (port_type & port->port_type)
1343 		{
1344 #if 0
1345 			printf("port %d\n", port->targ_port);
1346 #endif
1347 			ctl_port_online(port);
1348 		}
1349 	}
1350 
1351 	return (0);
1352 }
1353 
1354 int
1355 ctl_port_disable(ctl_port_type port_type)
1356 {
1357 	struct ctl_softc *softc;
1358 	struct ctl_port *port;
1359 
1360 	softc = control_softc;
1361 
1362 	STAILQ_FOREACH(port, &softc->port_list, links) {
1363 		if (port_type & port->port_type)
1364 			ctl_port_offline(port);
1365 	}
1366 
1367 	return (0);
1368 }
1369 
1370 /*
1371  * Returns 0 for success, 1 for failure.
1372  * Currently the only failure mode is if there aren't enough entries
1373  * allocated.  So, in case of a failure, look at num_entries_dropped,
1374  * reallocate and try again.
1375  */
1376 int
1377 ctl_port_list(struct ctl_port_entry *entries, int num_entries_alloced,
1378 	      int *num_entries_filled, int *num_entries_dropped,
1379 	      ctl_port_type port_type, int no_virtual)
1380 {
1381 	struct ctl_softc *softc;
1382 	struct ctl_port *port;
1383 	int entries_dropped, entries_filled;
1384 	int retval;
1385 	int i;
1386 
1387 	softc = control_softc;
1388 
1389 	retval = 0;
1390 	entries_filled = 0;
1391 	entries_dropped = 0;
1392 
1393 	i = 0;
1394 	mtx_lock(&softc->ctl_lock);
1395 	STAILQ_FOREACH(port, &softc->port_list, links) {
1396 		struct ctl_port_entry *entry;
1397 
1398 		if ((port->port_type & port_type) == 0)
1399 			continue;
1400 
1401 		if ((no_virtual != 0)
1402 		 && (port->virtual_port != 0))
1403 			continue;
1404 
1405 		if (entries_filled >= num_entries_alloced) {
1406 			entries_dropped++;
1407 			continue;
1408 		}
1409 		entry = &entries[i];
1410 
1411 		entry->port_type = port->port_type;
1412 		strlcpy(entry->port_name, port->port_name,
1413 			sizeof(entry->port_name));
1414 		entry->physical_port = port->physical_port;
1415 		entry->virtual_port = port->virtual_port;
1416 		entry->wwnn = port->wwnn;
1417 		entry->wwpn = port->wwpn;
1418 
1419 		i++;
1420 		entries_filled++;
1421 	}
1422 
1423 	mtx_unlock(&softc->ctl_lock);
1424 
1425 	if (entries_dropped > 0)
1426 		retval = 1;
1427 
1428 	*num_entries_dropped = entries_dropped;
1429 	*num_entries_filled = entries_filled;
1430 
1431 	return (retval);
1432 }
1433 
1434 static void
1435 ctl_ioctl_online(void *arg)
1436 {
1437 	struct ctl_ioctl_info *ioctl_info;
1438 
1439 	ioctl_info = (struct ctl_ioctl_info *)arg;
1440 
1441 	ioctl_info->flags |= CTL_IOCTL_FLAG_ENABLED;
1442 }
1443 
1444 static void
1445 ctl_ioctl_offline(void *arg)
1446 {
1447 	struct ctl_ioctl_info *ioctl_info;
1448 
1449 	ioctl_info = (struct ctl_ioctl_info *)arg;
1450 
1451 	ioctl_info->flags &= ~CTL_IOCTL_FLAG_ENABLED;
1452 }
1453 
1454 /*
1455  * Remove an initiator by port number and initiator ID.
1456  * Returns 0 for success, -1 for failure.
1457  */
1458 int
1459 ctl_remove_initiator(struct ctl_port *port, int iid)
1460 {
1461 	struct ctl_softc *softc = control_softc;
1462 
1463 	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1464 
1465 	if (iid > CTL_MAX_INIT_PER_PORT) {
1466 		printf("%s: initiator ID %u > maximun %u!\n",
1467 		       __func__, iid, CTL_MAX_INIT_PER_PORT);
1468 		return (-1);
1469 	}
1470 
1471 	mtx_lock(&softc->ctl_lock);
1472 	port->wwpn_iid[iid].in_use--;
1473 	port->wwpn_iid[iid].last_use = time_uptime;
1474 	mtx_unlock(&softc->ctl_lock);
1475 
1476 	return (0);
1477 }
1478 
1479 /*
1480  * Add an initiator to the initiator map.
1481  * Returns iid for success, < 0 for failure.
1482  */
1483 int
1484 ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
1485 {
1486 	struct ctl_softc *softc = control_softc;
1487 	time_t best_time;
1488 	int i, best;
1489 
1490 	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1491 
1492 	if (iid >= CTL_MAX_INIT_PER_PORT) {
1493 		printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
1494 		       __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
1495 		free(name, M_CTL);
1496 		return (-1);
1497 	}
1498 
1499 	mtx_lock(&softc->ctl_lock);
1500 
1501 	if (iid < 0 && (wwpn != 0 || name != NULL)) {
1502 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1503 			if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
1504 				iid = i;
1505 				break;
1506 			}
1507 			if (name != NULL && port->wwpn_iid[i].name != NULL &&
1508 			    strcmp(name, port->wwpn_iid[i].name) == 0) {
1509 				iid = i;
1510 				break;
1511 			}
1512 		}
1513 	}
1514 
1515 	if (iid < 0) {
1516 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1517 			if (port->wwpn_iid[i].in_use == 0 &&
1518 			    port->wwpn_iid[i].wwpn == 0 &&
1519 			    port->wwpn_iid[i].name == NULL) {
1520 				iid = i;
1521 				break;
1522 			}
1523 		}
1524 	}
1525 
1526 	if (iid < 0) {
1527 		best = -1;
1528 		best_time = INT32_MAX;
1529 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1530 			if (port->wwpn_iid[i].in_use == 0) {
1531 				if (port->wwpn_iid[i].last_use < best_time) {
1532 					best = i;
1533 					best_time = port->wwpn_iid[i].last_use;
1534 				}
1535 			}
1536 		}
1537 		iid = best;
1538 	}
1539 
1540 	if (iid < 0) {
1541 		mtx_unlock(&softc->ctl_lock);
1542 		free(name, M_CTL);
1543 		return (-2);
1544 	}
1545 
1546 	if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
1547 		/*
1548 		 * This is not an error yet.
1549 		 */
1550 		if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
1551 #if 0
1552 			printf("%s: port %d iid %u WWPN %#jx arrived"
1553 			    " again\n", __func__, port->targ_port,
1554 			    iid, (uintmax_t)wwpn);
1555 #endif
1556 			goto take;
1557 		}
1558 		if (name != NULL && port->wwpn_iid[iid].name != NULL &&
1559 		    strcmp(name, port->wwpn_iid[iid].name) == 0) {
1560 #if 0
1561 			printf("%s: port %d iid %u name '%s' arrived"
1562 			    " again\n", __func__, port->targ_port,
1563 			    iid, name);
1564 #endif
1565 			goto take;
1566 		}
1567 
1568 		/*
1569 		 * This is an error, but what do we do about it?  The
1570 		 * driver is telling us we have a new WWPN for this
1571 		 * initiator ID, so we pretty much need to use it.
1572 		 */
1573 		printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
1574 		    " but WWPN %#jx '%s' is still at that address\n",
1575 		    __func__, port->targ_port, iid, wwpn, name,
1576 		    (uintmax_t)port->wwpn_iid[iid].wwpn,
1577 		    port->wwpn_iid[iid].name);
1578 
1579 		/*
1580 		 * XXX KDM clear have_ca and ua_pending on each LUN for
1581 		 * this initiator.
1582 		 */
1583 	}
1584 take:
1585 	free(port->wwpn_iid[iid].name, M_CTL);
1586 	port->wwpn_iid[iid].name = name;
1587 	port->wwpn_iid[iid].wwpn = wwpn;
1588 	port->wwpn_iid[iid].in_use++;
1589 	mtx_unlock(&softc->ctl_lock);
1590 
1591 	return (iid);
1592 }
1593 
1594 static int
1595 ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
1596 {
1597 	int len;
1598 
1599 	switch (port->port_type) {
1600 	case CTL_PORT_FC:
1601 	{
1602 		struct scsi_transportid_fcp *id =
1603 		    (struct scsi_transportid_fcp *)buf;
1604 		if (port->wwpn_iid[iid].wwpn == 0)
1605 			return (0);
1606 		memset(id, 0, sizeof(*id));
1607 		id->format_protocol = SCSI_PROTO_FC;
1608 		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
1609 		return (sizeof(*id));
1610 	}
1611 	case CTL_PORT_ISCSI:
1612 	{
1613 		struct scsi_transportid_iscsi_port *id =
1614 		    (struct scsi_transportid_iscsi_port *)buf;
1615 		if (port->wwpn_iid[iid].name == NULL)
1616 			return (0);
1617 		memset(id, 0, 256);
1618 		id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
1619 		    SCSI_PROTO_ISCSI;
1620 		len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
1621 		len = roundup2(min(len, 252), 4);
1622 		scsi_ulto2b(len, id->additional_length);
1623 		return (sizeof(*id) + len);
1624 	}
1625 	case CTL_PORT_SAS:
1626 	{
1627 		struct scsi_transportid_sas *id =
1628 		    (struct scsi_transportid_sas *)buf;
1629 		if (port->wwpn_iid[iid].wwpn == 0)
1630 			return (0);
1631 		memset(id, 0, sizeof(*id));
1632 		id->format_protocol = SCSI_PROTO_SAS;
1633 		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
1634 		return (sizeof(*id));
1635 	}
1636 	default:
1637 	{
1638 		struct scsi_transportid_spi *id =
1639 		    (struct scsi_transportid_spi *)buf;
1640 		memset(id, 0, sizeof(*id));
1641 		id->format_protocol = SCSI_PROTO_SPI;
1642 		scsi_ulto2b(iid, id->scsi_addr);
1643 		scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
1644 		return (sizeof(*id));
1645 	}
1646 	}
1647 }
1648 
1649 static int
1650 ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id)
1651 {
1652 	return (0);
1653 }
1654 
1655 static int
1656 ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id)
1657 {
1658 	return (0);
1659 }
1660 
1661 /*
1662  * Data movement routine for the CTL ioctl frontend port.
1663  */
1664 static int
1665 ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio)
1666 {
1667 	struct ctl_sg_entry *ext_sglist, *kern_sglist;
1668 	struct ctl_sg_entry ext_entry, kern_entry;
1669 	int ext_sglen, ext_sg_entries, kern_sg_entries;
1670 	int ext_sg_start, ext_offset;
1671 	int len_to_copy, len_copied;
1672 	int kern_watermark, ext_watermark;
1673 	int ext_sglist_malloced;
1674 	int i, j;
1675 
1676 	ext_sglist_malloced = 0;
1677 	ext_sg_start = 0;
1678 	ext_offset = 0;
1679 
1680 	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove\n"));
1681 
1682 	/*
1683 	 * If this flag is set, fake the data transfer.
1684 	 */
1685 	if (ctsio->io_hdr.flags & CTL_FLAG_NO_DATAMOVE) {
1686 		ctsio->ext_data_filled = ctsio->ext_data_len;
1687 		goto bailout;
1688 	}
1689 
1690 	/*
1691 	 * To simplify things here, if we have a single buffer, stick it in
1692 	 * a S/G entry and just make it a single entry S/G list.
1693 	 */
1694 	if (ctsio->io_hdr.flags & CTL_FLAG_EDPTR_SGLIST) {
1695 		int len_seen;
1696 
1697 		ext_sglen = ctsio->ext_sg_entries * sizeof(*ext_sglist);
1698 
1699 		ext_sglist = (struct ctl_sg_entry *)malloc(ext_sglen, M_CTL,
1700 							   M_WAITOK);
1701 		ext_sglist_malloced = 1;
1702 		if (copyin(ctsio->ext_data_ptr, ext_sglist,
1703 				   ext_sglen) != 0) {
1704 			ctl_set_internal_failure(ctsio,
1705 						 /*sks_valid*/ 0,
1706 						 /*retry_count*/ 0);
1707 			goto bailout;
1708 		}
1709 		ext_sg_entries = ctsio->ext_sg_entries;
1710 		len_seen = 0;
1711 		for (i = 0; i < ext_sg_entries; i++) {
1712 			if ((len_seen + ext_sglist[i].len) >=
1713 			     ctsio->ext_data_filled) {
1714 				ext_sg_start = i;
1715 				ext_offset = ctsio->ext_data_filled - len_seen;
1716 				break;
1717 			}
1718 			len_seen += ext_sglist[i].len;
1719 		}
1720 	} else {
1721 		ext_sglist = &ext_entry;
1722 		ext_sglist->addr = ctsio->ext_data_ptr;
1723 		ext_sglist->len = ctsio->ext_data_len;
1724 		ext_sg_entries = 1;
1725 		ext_sg_start = 0;
1726 		ext_offset = ctsio->ext_data_filled;
1727 	}
1728 
1729 	if (ctsio->kern_sg_entries > 0) {
1730 		kern_sglist = (struct ctl_sg_entry *)ctsio->kern_data_ptr;
1731 		kern_sg_entries = ctsio->kern_sg_entries;
1732 	} else {
1733 		kern_sglist = &kern_entry;
1734 		kern_sglist->addr = ctsio->kern_data_ptr;
1735 		kern_sglist->len = ctsio->kern_data_len;
1736 		kern_sg_entries = 1;
1737 	}
1738 
1739 
1740 	kern_watermark = 0;
1741 	ext_watermark = ext_offset;
1742 	len_copied = 0;
1743 	for (i = ext_sg_start, j = 0;
1744 	     i < ext_sg_entries && j < kern_sg_entries;) {
1745 		uint8_t *ext_ptr, *kern_ptr;
1746 
1747 		len_to_copy = ctl_min(ext_sglist[i].len - ext_watermark,
1748 				      kern_sglist[j].len - kern_watermark);
1749 
1750 		ext_ptr = (uint8_t *)ext_sglist[i].addr;
1751 		ext_ptr = ext_ptr + ext_watermark;
1752 		if (ctsio->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
1753 			/*
1754 			 * XXX KDM fix this!
1755 			 */
1756 			panic("need to implement bus address support");
1757 #if 0
1758 			kern_ptr = bus_to_virt(kern_sglist[j].addr);
1759 #endif
1760 		} else
1761 			kern_ptr = (uint8_t *)kern_sglist[j].addr;
1762 		kern_ptr = kern_ptr + kern_watermark;
1763 
1764 		kern_watermark += len_to_copy;
1765 		ext_watermark += len_to_copy;
1766 
1767 		if ((ctsio->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
1768 		     CTL_FLAG_DATA_IN) {
1769 			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1770 					 "bytes to user\n", len_to_copy));
1771 			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1772 					 "to %p\n", kern_ptr, ext_ptr));
1773 			if (copyout(kern_ptr, ext_ptr, len_to_copy) != 0) {
1774 				ctl_set_internal_failure(ctsio,
1775 							 /*sks_valid*/ 0,
1776 							 /*retry_count*/ 0);
1777 				goto bailout;
1778 			}
1779 		} else {
1780 			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1781 					 "bytes from user\n", len_to_copy));
1782 			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1783 					 "to %p\n", ext_ptr, kern_ptr));
1784 			if (copyin(ext_ptr, kern_ptr, len_to_copy)!= 0){
1785 				ctl_set_internal_failure(ctsio,
1786 							 /*sks_valid*/ 0,
1787 							 /*retry_count*/0);
1788 				goto bailout;
1789 			}
1790 		}
1791 
1792 		len_copied += len_to_copy;
1793 
1794 		if (ext_sglist[i].len == ext_watermark) {
1795 			i++;
1796 			ext_watermark = 0;
1797 		}
1798 
1799 		if (kern_sglist[j].len == kern_watermark) {
1800 			j++;
1801 			kern_watermark = 0;
1802 		}
1803 	}
1804 
1805 	ctsio->ext_data_filled += len_copied;
1806 
1807 	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_sg_entries: %d, "
1808 			 "kern_sg_entries: %d\n", ext_sg_entries,
1809 			 kern_sg_entries));
1810 	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_data_len = %d, "
1811 			 "kern_data_len = %d\n", ctsio->ext_data_len,
1812 			 ctsio->kern_data_len));
1813 
1814 
1815 	/* XXX KDM set residual?? */
1816 bailout:
1817 
1818 	if (ext_sglist_malloced != 0)
1819 		free(ext_sglist, M_CTL);
1820 
1821 	return (CTL_RETVAL_COMPLETE);
1822 }
1823 
1824 /*
1825  * Serialize a command that went down the "wrong" side, and so was sent to
1826  * this controller for execution.  The logic is a little different than the
1827  * standard case in ctl_scsiio_precheck().  Errors in this case need to get
1828  * sent back to the other side, but in the success case, we execute the
1829  * command on this side (XFER mode) or tell the other side to execute it
1830  * (SER_ONLY mode).
1831  */
1832 static int
1833 ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
1834 {
1835 	struct ctl_softc *ctl_softc;
1836 	union ctl_ha_msg msg_info;
1837 	struct ctl_lun *lun;
1838 	int retval = 0;
1839 	uint32_t targ_lun;
1840 
1841 	ctl_softc = control_softc;
1842 
1843 	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
1844 	lun = ctl_softc->ctl_luns[targ_lun];
1845 	if (lun==NULL)
1846 	{
1847 		/*
1848 		 * Why isn't LUN defined? The other side wouldn't
1849 		 * send a cmd if the LUN is undefined.
1850 		 */
1851 		printf("%s: Bad JUJU!, LUN is NULL!\n", __func__);
1852 
1853 		/* "Logical unit not supported" */
1854 		ctl_set_sense_data(&msg_info.scsi.sense_data,
1855 				   lun,
1856 				   /*sense_format*/SSD_TYPE_NONE,
1857 				   /*current_error*/ 1,
1858 				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1859 				   /*asc*/ 0x25,
1860 				   /*ascq*/ 0x00,
1861 				   SSD_ELEM_NONE);
1862 
1863 		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1864 		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1865 		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1866 		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1867 		msg_info.hdr.serializing_sc = NULL;
1868 		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1869 	        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1870 				sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1871 		}
1872 		return(1);
1873 
1874 	}
1875 
1876 	mtx_lock(&lun->lun_lock);
1877     	TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1878 
1879 	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
1880 		(union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
1881 		 ooa_links))) {
1882 	case CTL_ACTION_BLOCK:
1883 		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
1884 		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
1885 				  blocked_links);
1886 		break;
1887 	case CTL_ACTION_PASS:
1888 	case CTL_ACTION_SKIP:
1889 		if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
1890 			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
1891 			ctl_enqueue_rtr((union ctl_io *)ctsio);
1892 		} else {
1893 
1894 			/* send msg back to other side */
1895 			msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1896 			msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
1897 			msg_info.hdr.msg_type = CTL_MSG_R2R;
1898 #if 0
1899 			printf("2. pOrig %x\n", (int)msg_info.hdr.original_sc);
1900 #endif
1901 		        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1902 			    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1903 			}
1904 		}
1905 		break;
1906 	case CTL_ACTION_OVERLAP:
1907 		/* OVERLAPPED COMMANDS ATTEMPTED */
1908 		ctl_set_sense_data(&msg_info.scsi.sense_data,
1909 				   lun,
1910 				   /*sense_format*/SSD_TYPE_NONE,
1911 				   /*current_error*/ 1,
1912 				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1913 				   /*asc*/ 0x4E,
1914 				   /*ascq*/ 0x00,
1915 				   SSD_ELEM_NONE);
1916 
1917 		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1918 		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1919 		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1920 		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1921 		msg_info.hdr.serializing_sc = NULL;
1922 		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1923 #if 0
1924 		printf("BAD JUJU:Major Bummer Overlap\n");
1925 #endif
1926 		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1927 		retval = 1;
1928 		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1929 		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1930 		}
1931 		break;
1932 	case CTL_ACTION_OVERLAP_TAG:
1933 		/* TAGGED OVERLAPPED COMMANDS (NN = QUEUE TAG) */
1934 		ctl_set_sense_data(&msg_info.scsi.sense_data,
1935 				   lun,
1936 				   /*sense_format*/SSD_TYPE_NONE,
1937 				   /*current_error*/ 1,
1938 				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1939 				   /*asc*/ 0x4D,
1940 				   /*ascq*/ ctsio->tag_num & 0xff,
1941 				   SSD_ELEM_NONE);
1942 
1943 		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1944 		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1945 		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1946 		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1947 		msg_info.hdr.serializing_sc = NULL;
1948 		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1949 #if 0
1950 		printf("BAD JUJU:Major Bummer Overlap Tag\n");
1951 #endif
1952 		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1953 		retval = 1;
1954 		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1955 		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1956 		}
1957 		break;
1958 	case CTL_ACTION_ERROR:
1959 	default:
1960 		/* "Internal target failure" */
1961 		ctl_set_sense_data(&msg_info.scsi.sense_data,
1962 				   lun,
1963 				   /*sense_format*/SSD_TYPE_NONE,
1964 				   /*current_error*/ 1,
1965 				   /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
1966 				   /*asc*/ 0x44,
1967 				   /*ascq*/ 0x00,
1968 				   SSD_ELEM_NONE);
1969 
1970 		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1971 		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1972 		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1973 		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1974 		msg_info.hdr.serializing_sc = NULL;
1975 		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1976 #if 0
1977 		printf("BAD JUJU:Major Bummer HW Error\n");
1978 #endif
1979 		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1980 		retval = 1;
1981 		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1982 		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1983 		}
1984 		break;
1985 	}
1986 	mtx_unlock(&lun->lun_lock);
1987 	return (retval);
1988 }
1989 
1990 static int
1991 ctl_ioctl_submit_wait(union ctl_io *io)
1992 {
1993 	struct ctl_fe_ioctl_params params;
1994 	ctl_fe_ioctl_state last_state;
1995 	int done, retval;
1996 
1997 	retval = 0;
1998 
1999 	bzero(&params, sizeof(params));
2000 
2001 	mtx_init(&params.ioctl_mtx, "ctliocmtx", NULL, MTX_DEF);
2002 	cv_init(&params.sem, "ctlioccv");
2003 	params.state = CTL_IOCTL_INPROG;
2004 	last_state = params.state;
2005 
2006 	io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr = &params;
2007 
2008 	CTL_DEBUG_PRINT(("ctl_ioctl_submit_wait\n"));
2009 
2010 	/* This shouldn't happen */
2011 	if ((retval = ctl_queue(io)) != CTL_RETVAL_COMPLETE)
2012 		return (retval);
2013 
2014 	done = 0;
2015 
2016 	do {
2017 		mtx_lock(&params.ioctl_mtx);
2018 		/*
2019 		 * Check the state here, and don't sleep if the state has
2020 		 * already changed (i.e. wakeup has already occured, but we
2021 		 * weren't waiting yet).
2022 		 */
2023 		if (params.state == last_state) {
2024 			/* XXX KDM cv_wait_sig instead? */
2025 			cv_wait(&params.sem, &params.ioctl_mtx);
2026 		}
2027 		last_state = params.state;
2028 
2029 		switch (params.state) {
2030 		case CTL_IOCTL_INPROG:
2031 			/* Why did we wake up? */
2032 			/* XXX KDM error here? */
2033 			mtx_unlock(&params.ioctl_mtx);
2034 			break;
2035 		case CTL_IOCTL_DATAMOVE:
2036 			CTL_DEBUG_PRINT(("got CTL_IOCTL_DATAMOVE\n"));
2037 
2038 			/*
2039 			 * change last_state back to INPROG to avoid
2040 			 * deadlock on subsequent data moves.
2041 			 */
2042 			params.state = last_state = CTL_IOCTL_INPROG;
2043 
2044 			mtx_unlock(&params.ioctl_mtx);
2045 			ctl_ioctl_do_datamove(&io->scsiio);
2046 			/*
2047 			 * Note that in some cases, most notably writes,
2048 			 * this will queue the I/O and call us back later.
2049 			 * In other cases, generally reads, this routine
2050 			 * will immediately call back and wake us up,
2051 			 * probably using our own context.
2052 			 */
2053 			io->scsiio.be_move_done(io);
2054 			break;
2055 		case CTL_IOCTL_DONE:
2056 			mtx_unlock(&params.ioctl_mtx);
2057 			CTL_DEBUG_PRINT(("got CTL_IOCTL_DONE\n"));
2058 			done = 1;
2059 			break;
2060 		default:
2061 			mtx_unlock(&params.ioctl_mtx);
2062 			/* XXX KDM error here? */
2063 			break;
2064 		}
2065 	} while (done == 0);
2066 
2067 	mtx_destroy(&params.ioctl_mtx);
2068 	cv_destroy(&params.sem);
2069 
2070 	return (CTL_RETVAL_COMPLETE);
2071 }
2072 
2073 static void
2074 ctl_ioctl_datamove(union ctl_io *io)
2075 {
2076 	struct ctl_fe_ioctl_params *params;
2077 
2078 	params = (struct ctl_fe_ioctl_params *)
2079 		io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2080 
2081 	mtx_lock(&params->ioctl_mtx);
2082 	params->state = CTL_IOCTL_DATAMOVE;
2083 	cv_broadcast(&params->sem);
2084 	mtx_unlock(&params->ioctl_mtx);
2085 }
2086 
2087 static void
2088 ctl_ioctl_done(union ctl_io *io)
2089 {
2090 	struct ctl_fe_ioctl_params *params;
2091 
2092 	params = (struct ctl_fe_ioctl_params *)
2093 		io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2094 
2095 	mtx_lock(&params->ioctl_mtx);
2096 	params->state = CTL_IOCTL_DONE;
2097 	cv_broadcast(&params->sem);
2098 	mtx_unlock(&params->ioctl_mtx);
2099 }
2100 
2101 static void
2102 ctl_ioctl_hard_startstop_callback(void *arg, struct cfi_metatask *metatask)
2103 {
2104 	struct ctl_fe_ioctl_startstop_info *sd_info;
2105 
2106 	sd_info = (struct ctl_fe_ioctl_startstop_info *)arg;
2107 
2108 	sd_info->hs_info.status = metatask->status;
2109 	sd_info->hs_info.total_luns = metatask->taskinfo.startstop.total_luns;
2110 	sd_info->hs_info.luns_complete =
2111 		metatask->taskinfo.startstop.luns_complete;
2112 	sd_info->hs_info.luns_failed = metatask->taskinfo.startstop.luns_failed;
2113 
2114 	cv_broadcast(&sd_info->sem);
2115 }
2116 
2117 static void
2118 ctl_ioctl_bbrread_callback(void *arg, struct cfi_metatask *metatask)
2119 {
2120 	struct ctl_fe_ioctl_bbrread_info *fe_bbr_info;
2121 
2122 	fe_bbr_info = (struct ctl_fe_ioctl_bbrread_info *)arg;
2123 
2124 	mtx_lock(fe_bbr_info->lock);
2125 	fe_bbr_info->bbr_info->status = metatask->status;
2126 	fe_bbr_info->bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2127 	fe_bbr_info->wakeup_done = 1;
2128 	mtx_unlock(fe_bbr_info->lock);
2129 
2130 	cv_broadcast(&fe_bbr_info->sem);
2131 }
2132 
2133 /*
2134  * Returns 0 for success, errno for failure.
2135  */
2136 static int
2137 ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2138 		   struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2139 {
2140 	union ctl_io *io;
2141 	int retval;
2142 
2143 	retval = 0;
2144 
2145 	mtx_lock(&lun->lun_lock);
2146 	for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
2147 	     (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2148 	     ooa_links)) {
2149 		struct ctl_ooa_entry *entry;
2150 
2151 		/*
2152 		 * If we've got more than we can fit, just count the
2153 		 * remaining entries.
2154 		 */
2155 		if (*cur_fill_num >= ooa_hdr->alloc_num)
2156 			continue;
2157 
2158 		entry = &kern_entries[*cur_fill_num];
2159 
2160 		entry->tag_num = io->scsiio.tag_num;
2161 		entry->lun_num = lun->lun;
2162 #ifdef CTL_TIME_IO
2163 		entry->start_bt = io->io_hdr.start_bt;
2164 #endif
2165 		bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2166 		entry->cdb_len = io->scsiio.cdb_len;
2167 		if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
2168 			entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2169 
2170 		if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2171 			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2172 
2173 		if (io->io_hdr.flags & CTL_FLAG_ABORT)
2174 			entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2175 
2176 		if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2177 			entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2178 
2179 		if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2180 			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2181 	}
2182 	mtx_unlock(&lun->lun_lock);
2183 
2184 	return (retval);
2185 }
2186 
2187 static void *
2188 ctl_copyin_alloc(void *user_addr, int len, char *error_str,
2189 		 size_t error_str_len)
2190 {
2191 	void *kptr;
2192 
2193 	kptr = malloc(len, M_CTL, M_WAITOK | M_ZERO);
2194 
2195 	if (copyin(user_addr, kptr, len) != 0) {
2196 		snprintf(error_str, error_str_len, "Error copying %d bytes "
2197 			 "from user address %p to kernel address %p", len,
2198 			 user_addr, kptr);
2199 		free(kptr, M_CTL);
2200 		return (NULL);
2201 	}
2202 
2203 	return (kptr);
2204 }
2205 
2206 static void
2207 ctl_free_args(int num_args, struct ctl_be_arg *args)
2208 {
2209 	int i;
2210 
2211 	if (args == NULL)
2212 		return;
2213 
2214 	for (i = 0; i < num_args; i++) {
2215 		free(args[i].kname, M_CTL);
2216 		free(args[i].kvalue, M_CTL);
2217 	}
2218 
2219 	free(args, M_CTL);
2220 }
2221 
2222 static struct ctl_be_arg *
2223 ctl_copyin_args(int num_args, struct ctl_be_arg *uargs,
2224 		char *error_str, size_t error_str_len)
2225 {
2226 	struct ctl_be_arg *args;
2227 	int i;
2228 
2229 	args = ctl_copyin_alloc(uargs, num_args * sizeof(*args),
2230 				error_str, error_str_len);
2231 
2232 	if (args == NULL)
2233 		goto bailout;
2234 
2235 	for (i = 0; i < num_args; i++) {
2236 		args[i].kname = NULL;
2237 		args[i].kvalue = NULL;
2238 	}
2239 
2240 	for (i = 0; i < num_args; i++) {
2241 		uint8_t *tmpptr;
2242 
2243 		args[i].kname = ctl_copyin_alloc(args[i].name,
2244 			args[i].namelen, error_str, error_str_len);
2245 		if (args[i].kname == NULL)
2246 			goto bailout;
2247 
2248 		if (args[i].kname[args[i].namelen - 1] != '\0') {
2249 			snprintf(error_str, error_str_len, "Argument %d "
2250 				 "name is not NUL-terminated", i);
2251 			goto bailout;
2252 		}
2253 
2254 		if (args[i].flags & CTL_BEARG_RD) {
2255 			tmpptr = ctl_copyin_alloc(args[i].value,
2256 				args[i].vallen, error_str, error_str_len);
2257 			if (tmpptr == NULL)
2258 				goto bailout;
2259 			if ((args[i].flags & CTL_BEARG_ASCII)
2260 			 && (tmpptr[args[i].vallen - 1] != '\0')) {
2261 				snprintf(error_str, error_str_len, "Argument "
2262 				    "%d value is not NUL-terminated", i);
2263 				goto bailout;
2264 			}
2265 			args[i].kvalue = tmpptr;
2266 		} else {
2267 			args[i].kvalue = malloc(args[i].vallen,
2268 			    M_CTL, M_WAITOK | M_ZERO);
2269 		}
2270 	}
2271 
2272 	return (args);
2273 bailout:
2274 
2275 	ctl_free_args(num_args, args);
2276 
2277 	return (NULL);
2278 }
2279 
2280 static void
2281 ctl_copyout_args(int num_args, struct ctl_be_arg *args)
2282 {
2283 	int i;
2284 
2285 	for (i = 0; i < num_args; i++) {
2286 		if (args[i].flags & CTL_BEARG_WR)
2287 			copyout(args[i].kvalue, args[i].value, args[i].vallen);
2288 	}
2289 }
2290 
2291 /*
2292  * Escape characters that are illegal or not recommended in XML.
2293  */
2294 int
2295 ctl_sbuf_printf_esc(struct sbuf *sb, char *str, int size)
2296 {
2297 	char *end = str + size;
2298 	int retval;
2299 
2300 	retval = 0;
2301 
2302 	for (; *str && str < end; str++) {
2303 		switch (*str) {
2304 		case '&':
2305 			retval = sbuf_printf(sb, "&amp;");
2306 			break;
2307 		case '>':
2308 			retval = sbuf_printf(sb, "&gt;");
2309 			break;
2310 		case '<':
2311 			retval = sbuf_printf(sb, "&lt;");
2312 			break;
2313 		default:
2314 			retval = sbuf_putc(sb, *str);
2315 			break;
2316 		}
2317 
2318 		if (retval != 0)
2319 			break;
2320 
2321 	}
2322 
2323 	return (retval);
2324 }
2325 
2326 static void
2327 ctl_id_sbuf(struct ctl_devid *id, struct sbuf *sb)
2328 {
2329 	struct scsi_vpd_id_descriptor *desc;
2330 	int i;
2331 
2332 	if (id == NULL || id->len < 4)
2333 		return;
2334 	desc = (struct scsi_vpd_id_descriptor *)id->data;
2335 	switch (desc->id_type & SVPD_ID_TYPE_MASK) {
2336 	case SVPD_ID_TYPE_T10:
2337 		sbuf_printf(sb, "t10.");
2338 		break;
2339 	case SVPD_ID_TYPE_EUI64:
2340 		sbuf_printf(sb, "eui.");
2341 		break;
2342 	case SVPD_ID_TYPE_NAA:
2343 		sbuf_printf(sb, "naa.");
2344 		break;
2345 	case SVPD_ID_TYPE_SCSI_NAME:
2346 		break;
2347 	}
2348 	switch (desc->proto_codeset & SVPD_ID_CODESET_MASK) {
2349 	case SVPD_ID_CODESET_BINARY:
2350 		for (i = 0; i < desc->length; i++)
2351 			sbuf_printf(sb, "%02x", desc->identifier[i]);
2352 		break;
2353 	case SVPD_ID_CODESET_ASCII:
2354 		sbuf_printf(sb, "%.*s", (int)desc->length,
2355 		    (char *)desc->identifier);
2356 		break;
2357 	case SVPD_ID_CODESET_UTF8:
2358 		sbuf_printf(sb, "%s", (char *)desc->identifier);
2359 		break;
2360 	}
2361 }
2362 
2363 static int
2364 ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2365 	  struct thread *td)
2366 {
2367 	struct ctl_softc *softc;
2368 	int retval;
2369 
2370 	softc = control_softc;
2371 
2372 	retval = 0;
2373 
2374 	switch (cmd) {
2375 	case CTL_IO: {
2376 		union ctl_io *io;
2377 		void *pool_tmp;
2378 
2379 		/*
2380 		 * If we haven't been "enabled", don't allow any SCSI I/O
2381 		 * to this FETD.
2382 		 */
2383 		if ((softc->ioctl_info.flags & CTL_IOCTL_FLAG_ENABLED) == 0) {
2384 			retval = EPERM;
2385 			break;
2386 		}
2387 
2388 		io = ctl_alloc_io(softc->ioctl_info.port.ctl_pool_ref);
2389 
2390 		/*
2391 		 * Need to save the pool reference so it doesn't get
2392 		 * spammed by the user's ctl_io.
2393 		 */
2394 		pool_tmp = io->io_hdr.pool;
2395 		memcpy(io, (void *)addr, sizeof(*io));
2396 		io->io_hdr.pool = pool_tmp;
2397 
2398 		/*
2399 		 * No status yet, so make sure the status is set properly.
2400 		 */
2401 		io->io_hdr.status = CTL_STATUS_NONE;
2402 
2403 		/*
2404 		 * The user sets the initiator ID, target and LUN IDs.
2405 		 */
2406 		io->io_hdr.nexus.targ_port = softc->ioctl_info.port.targ_port;
2407 		io->io_hdr.flags |= CTL_FLAG_USER_REQ;
2408 		if ((io->io_hdr.io_type == CTL_IO_SCSI)
2409 		 && (io->scsiio.tag_type != CTL_TAG_UNTAGGED))
2410 			io->scsiio.tag_num = softc->ioctl_info.cur_tag_num++;
2411 
2412 		retval = ctl_ioctl_submit_wait(io);
2413 
2414 		if (retval != 0) {
2415 			ctl_free_io(io);
2416 			break;
2417 		}
2418 
2419 		memcpy((void *)addr, io, sizeof(*io));
2420 
2421 		/* return this to our pool */
2422 		ctl_free_io(io);
2423 
2424 		break;
2425 	}
2426 	case CTL_ENABLE_PORT:
2427 	case CTL_DISABLE_PORT:
2428 	case CTL_SET_PORT_WWNS: {
2429 		struct ctl_port *port;
2430 		struct ctl_port_entry *entry;
2431 
2432 		entry = (struct ctl_port_entry *)addr;
2433 
2434 		mtx_lock(&softc->ctl_lock);
2435 		STAILQ_FOREACH(port, &softc->port_list, links) {
2436 			int action, done;
2437 
2438 			action = 0;
2439 			done = 0;
2440 
2441 			if ((entry->port_type == CTL_PORT_NONE)
2442 			 && (entry->targ_port == port->targ_port)) {
2443 				/*
2444 				 * If the user only wants to enable or
2445 				 * disable or set WWNs on a specific port,
2446 				 * do the operation and we're done.
2447 				 */
2448 				action = 1;
2449 				done = 1;
2450 			} else if (entry->port_type & port->port_type) {
2451 				/*
2452 				 * Compare the user's type mask with the
2453 				 * particular frontend type to see if we
2454 				 * have a match.
2455 				 */
2456 				action = 1;
2457 				done = 0;
2458 
2459 				/*
2460 				 * Make sure the user isn't trying to set
2461 				 * WWNs on multiple ports at the same time.
2462 				 */
2463 				if (cmd == CTL_SET_PORT_WWNS) {
2464 					printf("%s: Can't set WWNs on "
2465 					       "multiple ports\n", __func__);
2466 					retval = EINVAL;
2467 					break;
2468 				}
2469 			}
2470 			if (action != 0) {
2471 				/*
2472 				 * XXX KDM we have to drop the lock here,
2473 				 * because the online/offline operations
2474 				 * can potentially block.  We need to
2475 				 * reference count the frontends so they
2476 				 * can't go away,
2477 				 */
2478 				mtx_unlock(&softc->ctl_lock);
2479 
2480 				if (cmd == CTL_ENABLE_PORT) {
2481 					struct ctl_lun *lun;
2482 
2483 					STAILQ_FOREACH(lun, &softc->lun_list,
2484 						       links) {
2485 						port->lun_enable(port->targ_lun_arg,
2486 						    lun->target,
2487 						    lun->lun);
2488 					}
2489 
2490 					ctl_port_online(port);
2491 				} else if (cmd == CTL_DISABLE_PORT) {
2492 					struct ctl_lun *lun;
2493 
2494 					ctl_port_offline(port);
2495 
2496 					STAILQ_FOREACH(lun, &softc->lun_list,
2497 						       links) {
2498 						port->lun_disable(
2499 						    port->targ_lun_arg,
2500 						    lun->target,
2501 						    lun->lun);
2502 					}
2503 				}
2504 
2505 				mtx_lock(&softc->ctl_lock);
2506 
2507 				if (cmd == CTL_SET_PORT_WWNS)
2508 					ctl_port_set_wwns(port,
2509 					    (entry->flags & CTL_PORT_WWNN_VALID) ?
2510 					    1 : 0, entry->wwnn,
2511 					    (entry->flags & CTL_PORT_WWPN_VALID) ?
2512 					    1 : 0, entry->wwpn);
2513 			}
2514 			if (done != 0)
2515 				break;
2516 		}
2517 		mtx_unlock(&softc->ctl_lock);
2518 		break;
2519 	}
2520 	case CTL_GET_PORT_LIST: {
2521 		struct ctl_port *port;
2522 		struct ctl_port_list *list;
2523 		int i;
2524 
2525 		list = (struct ctl_port_list *)addr;
2526 
2527 		if (list->alloc_len != (list->alloc_num *
2528 		    sizeof(struct ctl_port_entry))) {
2529 			printf("%s: CTL_GET_PORT_LIST: alloc_len %u != "
2530 			       "alloc_num %u * sizeof(struct ctl_port_entry) "
2531 			       "%zu\n", __func__, list->alloc_len,
2532 			       list->alloc_num, sizeof(struct ctl_port_entry));
2533 			retval = EINVAL;
2534 			break;
2535 		}
2536 		list->fill_len = 0;
2537 		list->fill_num = 0;
2538 		list->dropped_num = 0;
2539 		i = 0;
2540 		mtx_lock(&softc->ctl_lock);
2541 		STAILQ_FOREACH(port, &softc->port_list, links) {
2542 			struct ctl_port_entry entry, *list_entry;
2543 
2544 			if (list->fill_num >= list->alloc_num) {
2545 				list->dropped_num++;
2546 				continue;
2547 			}
2548 
2549 			entry.port_type = port->port_type;
2550 			strlcpy(entry.port_name, port->port_name,
2551 				sizeof(entry.port_name));
2552 			entry.targ_port = port->targ_port;
2553 			entry.physical_port = port->physical_port;
2554 			entry.virtual_port = port->virtual_port;
2555 			entry.wwnn = port->wwnn;
2556 			entry.wwpn = port->wwpn;
2557 			if (port->status & CTL_PORT_STATUS_ONLINE)
2558 				entry.online = 1;
2559 			else
2560 				entry.online = 0;
2561 
2562 			list_entry = &list->entries[i];
2563 
2564 			retval = copyout(&entry, list_entry, sizeof(entry));
2565 			if (retval != 0) {
2566 				printf("%s: CTL_GET_PORT_LIST: copyout "
2567 				       "returned %d\n", __func__, retval);
2568 				break;
2569 			}
2570 			i++;
2571 			list->fill_num++;
2572 			list->fill_len += sizeof(entry);
2573 		}
2574 		mtx_unlock(&softc->ctl_lock);
2575 
2576 		/*
2577 		 * If this is non-zero, we had a copyout fault, so there's
2578 		 * probably no point in attempting to set the status inside
2579 		 * the structure.
2580 		 */
2581 		if (retval != 0)
2582 			break;
2583 
2584 		if (list->dropped_num > 0)
2585 			list->status = CTL_PORT_LIST_NEED_MORE_SPACE;
2586 		else
2587 			list->status = CTL_PORT_LIST_OK;
2588 		break;
2589 	}
2590 	case CTL_DUMP_OOA: {
2591 		struct ctl_lun *lun;
2592 		union ctl_io *io;
2593 		char printbuf[128];
2594 		struct sbuf sb;
2595 
2596 		mtx_lock(&softc->ctl_lock);
2597 		printf("Dumping OOA queues:\n");
2598 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
2599 			mtx_lock(&lun->lun_lock);
2600 			for (io = (union ctl_io *)TAILQ_FIRST(
2601 			     &lun->ooa_queue); io != NULL;
2602 			     io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2603 			     ooa_links)) {
2604 				sbuf_new(&sb, printbuf, sizeof(printbuf),
2605 					 SBUF_FIXEDLEN);
2606 				sbuf_printf(&sb, "LUN %jd tag 0x%04x%s%s%s%s: ",
2607 					    (intmax_t)lun->lun,
2608 					    io->scsiio.tag_num,
2609 					    (io->io_hdr.flags &
2610 					    CTL_FLAG_BLOCKED) ? "" : " BLOCKED",
2611 					    (io->io_hdr.flags &
2612 					    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
2613 					    (io->io_hdr.flags &
2614 					    CTL_FLAG_ABORT) ? " ABORT" : "",
2615 			                    (io->io_hdr.flags &
2616 		                        CTL_FLAG_IS_WAS_ON_RTR) ? " RTR" : "");
2617 				ctl_scsi_command_string(&io->scsiio, NULL, &sb);
2618 				sbuf_finish(&sb);
2619 				printf("%s\n", sbuf_data(&sb));
2620 			}
2621 			mtx_unlock(&lun->lun_lock);
2622 		}
2623 		printf("OOA queues dump done\n");
2624 		mtx_unlock(&softc->ctl_lock);
2625 		break;
2626 	}
2627 	case CTL_GET_OOA: {
2628 		struct ctl_lun *lun;
2629 		struct ctl_ooa *ooa_hdr;
2630 		struct ctl_ooa_entry *entries;
2631 		uint32_t cur_fill_num;
2632 
2633 		ooa_hdr = (struct ctl_ooa *)addr;
2634 
2635 		if ((ooa_hdr->alloc_len == 0)
2636 		 || (ooa_hdr->alloc_num == 0)) {
2637 			printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2638 			       "must be non-zero\n", __func__,
2639 			       ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2640 			retval = EINVAL;
2641 			break;
2642 		}
2643 
2644 		if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2645 		    sizeof(struct ctl_ooa_entry))) {
2646 			printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2647 			       "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2648 			       __func__, ooa_hdr->alloc_len,
2649 			       ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2650 			retval = EINVAL;
2651 			break;
2652 		}
2653 
2654 		entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2655 		if (entries == NULL) {
2656 			printf("%s: could not allocate %d bytes for OOA "
2657 			       "dump\n", __func__, ooa_hdr->alloc_len);
2658 			retval = ENOMEM;
2659 			break;
2660 		}
2661 
2662 		mtx_lock(&softc->ctl_lock);
2663 		if (((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0)
2664 		 && ((ooa_hdr->lun_num >= CTL_MAX_LUNS)
2665 		  || (softc->ctl_luns[ooa_hdr->lun_num] == NULL))) {
2666 			mtx_unlock(&softc->ctl_lock);
2667 			free(entries, M_CTL);
2668 			printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2669 			       __func__, (uintmax_t)ooa_hdr->lun_num);
2670 			retval = EINVAL;
2671 			break;
2672 		}
2673 
2674 		cur_fill_num = 0;
2675 
2676 		if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2677 			STAILQ_FOREACH(lun, &softc->lun_list, links) {
2678 				retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2679 					ooa_hdr, entries);
2680 				if (retval != 0)
2681 					break;
2682 			}
2683 			if (retval != 0) {
2684 				mtx_unlock(&softc->ctl_lock);
2685 				free(entries, M_CTL);
2686 				break;
2687 			}
2688 		} else {
2689 			lun = softc->ctl_luns[ooa_hdr->lun_num];
2690 
2691 			retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,ooa_hdr,
2692 						    entries);
2693 		}
2694 		mtx_unlock(&softc->ctl_lock);
2695 
2696 		ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2697 		ooa_hdr->fill_len = ooa_hdr->fill_num *
2698 			sizeof(struct ctl_ooa_entry);
2699 		retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2700 		if (retval != 0) {
2701 			printf("%s: error copying out %d bytes for OOA dump\n",
2702 			       __func__, ooa_hdr->fill_len);
2703 		}
2704 
2705 		getbintime(&ooa_hdr->cur_bt);
2706 
2707 		if (cur_fill_num > ooa_hdr->alloc_num) {
2708 			ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2709 			ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2710 		} else {
2711 			ooa_hdr->dropped_num = 0;
2712 			ooa_hdr->status = CTL_OOA_OK;
2713 		}
2714 
2715 		free(entries, M_CTL);
2716 		break;
2717 	}
2718 	case CTL_CHECK_OOA: {
2719 		union ctl_io *io;
2720 		struct ctl_lun *lun;
2721 		struct ctl_ooa_info *ooa_info;
2722 
2723 
2724 		ooa_info = (struct ctl_ooa_info *)addr;
2725 
2726 		if (ooa_info->lun_id >= CTL_MAX_LUNS) {
2727 			ooa_info->status = CTL_OOA_INVALID_LUN;
2728 			break;
2729 		}
2730 		mtx_lock(&softc->ctl_lock);
2731 		lun = softc->ctl_luns[ooa_info->lun_id];
2732 		if (lun == NULL) {
2733 			mtx_unlock(&softc->ctl_lock);
2734 			ooa_info->status = CTL_OOA_INVALID_LUN;
2735 			break;
2736 		}
2737 		mtx_lock(&lun->lun_lock);
2738 		mtx_unlock(&softc->ctl_lock);
2739 		ooa_info->num_entries = 0;
2740 		for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
2741 		     io != NULL; io = (union ctl_io *)TAILQ_NEXT(
2742 		     &io->io_hdr, ooa_links)) {
2743 			ooa_info->num_entries++;
2744 		}
2745 		mtx_unlock(&lun->lun_lock);
2746 
2747 		ooa_info->status = CTL_OOA_SUCCESS;
2748 
2749 		break;
2750 	}
2751 	case CTL_HARD_START:
2752 	case CTL_HARD_STOP: {
2753 		struct ctl_fe_ioctl_startstop_info ss_info;
2754 		struct cfi_metatask *metatask;
2755 		struct mtx hs_mtx;
2756 
2757 		mtx_init(&hs_mtx, "HS Mutex", NULL, MTX_DEF);
2758 
2759 		cv_init(&ss_info.sem, "hard start/stop cv" );
2760 
2761 		metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2762 		if (metatask == NULL) {
2763 			retval = ENOMEM;
2764 			mtx_destroy(&hs_mtx);
2765 			break;
2766 		}
2767 
2768 		if (cmd == CTL_HARD_START)
2769 			metatask->tasktype = CFI_TASK_STARTUP;
2770 		else
2771 			metatask->tasktype = CFI_TASK_SHUTDOWN;
2772 
2773 		metatask->callback = ctl_ioctl_hard_startstop_callback;
2774 		metatask->callback_arg = &ss_info;
2775 
2776 		cfi_action(metatask);
2777 
2778 		/* Wait for the callback */
2779 		mtx_lock(&hs_mtx);
2780 		cv_wait_sig(&ss_info.sem, &hs_mtx);
2781 		mtx_unlock(&hs_mtx);
2782 
2783 		/*
2784 		 * All information has been copied from the metatask by the
2785 		 * time cv_broadcast() is called, so we free the metatask here.
2786 		 */
2787 		cfi_free_metatask(metatask);
2788 
2789 		memcpy((void *)addr, &ss_info.hs_info, sizeof(ss_info.hs_info));
2790 
2791 		mtx_destroy(&hs_mtx);
2792 		break;
2793 	}
2794 	case CTL_BBRREAD: {
2795 		struct ctl_bbrread_info *bbr_info;
2796 		struct ctl_fe_ioctl_bbrread_info fe_bbr_info;
2797 		struct mtx bbr_mtx;
2798 		struct cfi_metatask *metatask;
2799 
2800 		bbr_info = (struct ctl_bbrread_info *)addr;
2801 
2802 		bzero(&fe_bbr_info, sizeof(fe_bbr_info));
2803 
2804 		bzero(&bbr_mtx, sizeof(bbr_mtx));
2805 		mtx_init(&bbr_mtx, "BBR Mutex", NULL, MTX_DEF);
2806 
2807 		fe_bbr_info.bbr_info = bbr_info;
2808 		fe_bbr_info.lock = &bbr_mtx;
2809 
2810 		cv_init(&fe_bbr_info.sem, "BBR read cv");
2811 		metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2812 
2813 		if (metatask == NULL) {
2814 			mtx_destroy(&bbr_mtx);
2815 			cv_destroy(&fe_bbr_info.sem);
2816 			retval = ENOMEM;
2817 			break;
2818 		}
2819 		metatask->tasktype = CFI_TASK_BBRREAD;
2820 		metatask->callback = ctl_ioctl_bbrread_callback;
2821 		metatask->callback_arg = &fe_bbr_info;
2822 		metatask->taskinfo.bbrread.lun_num = bbr_info->lun_num;
2823 		metatask->taskinfo.bbrread.lba = bbr_info->lba;
2824 		metatask->taskinfo.bbrread.len = bbr_info->len;
2825 
2826 		cfi_action(metatask);
2827 
2828 		mtx_lock(&bbr_mtx);
2829 		while (fe_bbr_info.wakeup_done == 0)
2830 			cv_wait_sig(&fe_bbr_info.sem, &bbr_mtx);
2831 		mtx_unlock(&bbr_mtx);
2832 
2833 		bbr_info->status = metatask->status;
2834 		bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2835 		bbr_info->scsi_status = metatask->taskinfo.bbrread.scsi_status;
2836 		memcpy(&bbr_info->sense_data,
2837 		       &metatask->taskinfo.bbrread.sense_data,
2838 		       ctl_min(sizeof(bbr_info->sense_data),
2839 			       sizeof(metatask->taskinfo.bbrread.sense_data)));
2840 
2841 		cfi_free_metatask(metatask);
2842 
2843 		mtx_destroy(&bbr_mtx);
2844 		cv_destroy(&fe_bbr_info.sem);
2845 
2846 		break;
2847 	}
2848 	case CTL_DELAY_IO: {
2849 		struct ctl_io_delay_info *delay_info;
2850 #ifdef CTL_IO_DELAY
2851 		struct ctl_lun *lun;
2852 #endif /* CTL_IO_DELAY */
2853 
2854 		delay_info = (struct ctl_io_delay_info *)addr;
2855 
2856 #ifdef CTL_IO_DELAY
2857 		mtx_lock(&softc->ctl_lock);
2858 
2859 		if ((delay_info->lun_id >= CTL_MAX_LUNS)
2860 		 || (softc->ctl_luns[delay_info->lun_id] == NULL)) {
2861 			delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2862 		} else {
2863 			lun = softc->ctl_luns[delay_info->lun_id];
2864 			mtx_lock(&lun->lun_lock);
2865 
2866 			delay_info->status = CTL_DELAY_STATUS_OK;
2867 
2868 			switch (delay_info->delay_type) {
2869 			case CTL_DELAY_TYPE_CONT:
2870 				break;
2871 			case CTL_DELAY_TYPE_ONESHOT:
2872 				break;
2873 			default:
2874 				delay_info->status =
2875 					CTL_DELAY_STATUS_INVALID_TYPE;
2876 				break;
2877 			}
2878 
2879 			switch (delay_info->delay_loc) {
2880 			case CTL_DELAY_LOC_DATAMOVE:
2881 				lun->delay_info.datamove_type =
2882 					delay_info->delay_type;
2883 				lun->delay_info.datamove_delay =
2884 					delay_info->delay_secs;
2885 				break;
2886 			case CTL_DELAY_LOC_DONE:
2887 				lun->delay_info.done_type =
2888 					delay_info->delay_type;
2889 				lun->delay_info.done_delay =
2890 					delay_info->delay_secs;
2891 				break;
2892 			default:
2893 				delay_info->status =
2894 					CTL_DELAY_STATUS_INVALID_LOC;
2895 				break;
2896 			}
2897 			mtx_unlock(&lun->lun_lock);
2898 		}
2899 
2900 		mtx_unlock(&softc->ctl_lock);
2901 #else
2902 		delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2903 #endif /* CTL_IO_DELAY */
2904 		break;
2905 	}
2906 	case CTL_REALSYNC_SET: {
2907 		int *syncstate;
2908 
2909 		syncstate = (int *)addr;
2910 
2911 		mtx_lock(&softc->ctl_lock);
2912 		switch (*syncstate) {
2913 		case 0:
2914 			softc->flags &= ~CTL_FLAG_REAL_SYNC;
2915 			break;
2916 		case 1:
2917 			softc->flags |= CTL_FLAG_REAL_SYNC;
2918 			break;
2919 		default:
2920 			retval = EINVAL;
2921 			break;
2922 		}
2923 		mtx_unlock(&softc->ctl_lock);
2924 		break;
2925 	}
2926 	case CTL_REALSYNC_GET: {
2927 		int *syncstate;
2928 
2929 		syncstate = (int*)addr;
2930 
2931 		mtx_lock(&softc->ctl_lock);
2932 		if (softc->flags & CTL_FLAG_REAL_SYNC)
2933 			*syncstate = 1;
2934 		else
2935 			*syncstate = 0;
2936 		mtx_unlock(&softc->ctl_lock);
2937 
2938 		break;
2939 	}
2940 	case CTL_SETSYNC:
2941 	case CTL_GETSYNC: {
2942 		struct ctl_sync_info *sync_info;
2943 		struct ctl_lun *lun;
2944 
2945 		sync_info = (struct ctl_sync_info *)addr;
2946 
2947 		mtx_lock(&softc->ctl_lock);
2948 		lun = softc->ctl_luns[sync_info->lun_id];
2949 		if (lun == NULL) {
2950 			mtx_unlock(&softc->ctl_lock);
2951 			sync_info->status = CTL_GS_SYNC_NO_LUN;
2952 		}
2953 		/*
2954 		 * Get or set the sync interval.  We're not bounds checking
2955 		 * in the set case, hopefully the user won't do something
2956 		 * silly.
2957 		 */
2958 		mtx_lock(&lun->lun_lock);
2959 		mtx_unlock(&softc->ctl_lock);
2960 		if (cmd == CTL_GETSYNC)
2961 			sync_info->sync_interval = lun->sync_interval;
2962 		else
2963 			lun->sync_interval = sync_info->sync_interval;
2964 		mtx_unlock(&lun->lun_lock);
2965 
2966 		sync_info->status = CTL_GS_SYNC_OK;
2967 
2968 		break;
2969 	}
2970 	case CTL_GETSTATS: {
2971 		struct ctl_stats *stats;
2972 		struct ctl_lun *lun;
2973 		int i;
2974 
2975 		stats = (struct ctl_stats *)addr;
2976 
2977 		if ((sizeof(struct ctl_lun_io_stats) * softc->num_luns) >
2978 		     stats->alloc_len) {
2979 			stats->status = CTL_SS_NEED_MORE_SPACE;
2980 			stats->num_luns = softc->num_luns;
2981 			break;
2982 		}
2983 		/*
2984 		 * XXX KDM no locking here.  If the LUN list changes,
2985 		 * things can blow up.
2986 		 */
2987 		for (i = 0, lun = STAILQ_FIRST(&softc->lun_list); lun != NULL;
2988 		     i++, lun = STAILQ_NEXT(lun, links)) {
2989 			retval = copyout(&lun->stats, &stats->lun_stats[i],
2990 					 sizeof(lun->stats));
2991 			if (retval != 0)
2992 				break;
2993 		}
2994 		stats->num_luns = softc->num_luns;
2995 		stats->fill_len = sizeof(struct ctl_lun_io_stats) *
2996 				 softc->num_luns;
2997 		stats->status = CTL_SS_OK;
2998 #ifdef CTL_TIME_IO
2999 		stats->flags = CTL_STATS_FLAG_TIME_VALID;
3000 #else
3001 		stats->flags = CTL_STATS_FLAG_NONE;
3002 #endif
3003 		getnanouptime(&stats->timestamp);
3004 		break;
3005 	}
3006 	case CTL_ERROR_INJECT: {
3007 		struct ctl_error_desc *err_desc, *new_err_desc;
3008 		struct ctl_lun *lun;
3009 
3010 		err_desc = (struct ctl_error_desc *)addr;
3011 
3012 		new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
3013 				      M_WAITOK | M_ZERO);
3014 		bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
3015 
3016 		mtx_lock(&softc->ctl_lock);
3017 		lun = softc->ctl_luns[err_desc->lun_id];
3018 		if (lun == NULL) {
3019 			mtx_unlock(&softc->ctl_lock);
3020 			free(new_err_desc, M_CTL);
3021 			printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
3022 			       __func__, (uintmax_t)err_desc->lun_id);
3023 			retval = EINVAL;
3024 			break;
3025 		}
3026 		mtx_lock(&lun->lun_lock);
3027 		mtx_unlock(&softc->ctl_lock);
3028 
3029 		/*
3030 		 * We could do some checking here to verify the validity
3031 		 * of the request, but given the complexity of error
3032 		 * injection requests, the checking logic would be fairly
3033 		 * complex.
3034 		 *
3035 		 * For now, if the request is invalid, it just won't get
3036 		 * executed and might get deleted.
3037 		 */
3038 		STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
3039 
3040 		/*
3041 		 * XXX KDM check to make sure the serial number is unique,
3042 		 * in case we somehow manage to wrap.  That shouldn't
3043 		 * happen for a very long time, but it's the right thing to
3044 		 * do.
3045 		 */
3046 		new_err_desc->serial = lun->error_serial;
3047 		err_desc->serial = lun->error_serial;
3048 		lun->error_serial++;
3049 
3050 		mtx_unlock(&lun->lun_lock);
3051 		break;
3052 	}
3053 	case CTL_ERROR_INJECT_DELETE: {
3054 		struct ctl_error_desc *delete_desc, *desc, *desc2;
3055 		struct ctl_lun *lun;
3056 		int delete_done;
3057 
3058 		delete_desc = (struct ctl_error_desc *)addr;
3059 		delete_done = 0;
3060 
3061 		mtx_lock(&softc->ctl_lock);
3062 		lun = softc->ctl_luns[delete_desc->lun_id];
3063 		if (lun == NULL) {
3064 			mtx_unlock(&softc->ctl_lock);
3065 			printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
3066 			       __func__, (uintmax_t)delete_desc->lun_id);
3067 			retval = EINVAL;
3068 			break;
3069 		}
3070 		mtx_lock(&lun->lun_lock);
3071 		mtx_unlock(&softc->ctl_lock);
3072 		STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
3073 			if (desc->serial != delete_desc->serial)
3074 				continue;
3075 
3076 			STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
3077 				      links);
3078 			free(desc, M_CTL);
3079 			delete_done = 1;
3080 		}
3081 		mtx_unlock(&lun->lun_lock);
3082 		if (delete_done == 0) {
3083 			printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
3084 			       "error serial %ju on LUN %u\n", __func__,
3085 			       delete_desc->serial, delete_desc->lun_id);
3086 			retval = EINVAL;
3087 			break;
3088 		}
3089 		break;
3090 	}
3091 	case CTL_DUMP_STRUCTS: {
3092 		int i, j, k;
3093 		struct ctl_port *port;
3094 		struct ctl_frontend *fe;
3095 
3096 		mtx_lock(&softc->ctl_lock);
3097 		printf("CTL Persistent Reservation information start:\n");
3098 		for (i = 0; i < CTL_MAX_LUNS; i++) {
3099 			struct ctl_lun *lun;
3100 
3101 			lun = softc->ctl_luns[i];
3102 
3103 			if ((lun == NULL)
3104 			 || ((lun->flags & CTL_LUN_DISABLED) != 0))
3105 				continue;
3106 
3107 			for (j = 0; j < (CTL_MAX_PORTS * 2); j++) {
3108 				if (lun->pr_keys[j] == NULL)
3109 					continue;
3110 				for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
3111 					if (lun->pr_keys[j][k] == 0)
3112 						continue;
3113 					printf("  LUN %d port %d iid %d key "
3114 					       "%#jx\n", i, j, k,
3115 					       (uintmax_t)lun->pr_keys[j][k]);
3116 				}
3117 			}
3118 		}
3119 		printf("CTL Persistent Reservation information end\n");
3120 		printf("CTL Ports:\n");
3121 		STAILQ_FOREACH(port, &softc->port_list, links) {
3122 			printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
3123 			       "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
3124 			       port->frontend->name, port->port_type,
3125 			       port->physical_port, port->virtual_port,
3126 			       (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
3127 			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3128 				if (port->wwpn_iid[j].in_use == 0 &&
3129 				    port->wwpn_iid[j].wwpn == 0 &&
3130 				    port->wwpn_iid[j].name == NULL)
3131 					continue;
3132 
3133 				printf("    iid %u use %d WWPN %#jx '%s'\n",
3134 				    j, port->wwpn_iid[j].in_use,
3135 				    (uintmax_t)port->wwpn_iid[j].wwpn,
3136 				    port->wwpn_iid[j].name);
3137 			}
3138 		}
3139 		printf("CTL Port information end\n");
3140 		mtx_unlock(&softc->ctl_lock);
3141 		/*
3142 		 * XXX KDM calling this without a lock.  We'd likely want
3143 		 * to drop the lock before calling the frontend's dump
3144 		 * routine anyway.
3145 		 */
3146 		printf("CTL Frontends:\n");
3147 		STAILQ_FOREACH(fe, &softc->fe_list, links) {
3148 			printf("  Frontend '%s'\n", fe->name);
3149 			if (fe->fe_dump != NULL)
3150 				fe->fe_dump();
3151 		}
3152 		printf("CTL Frontend information end\n");
3153 		break;
3154 	}
3155 	case CTL_LUN_REQ: {
3156 		struct ctl_lun_req *lun_req;
3157 		struct ctl_backend_driver *backend;
3158 
3159 		lun_req = (struct ctl_lun_req *)addr;
3160 
3161 		backend = ctl_backend_find(lun_req->backend);
3162 		if (backend == NULL) {
3163 			lun_req->status = CTL_LUN_ERROR;
3164 			snprintf(lun_req->error_str,
3165 				 sizeof(lun_req->error_str),
3166 				 "Backend \"%s\" not found.",
3167 				 lun_req->backend);
3168 			break;
3169 		}
3170 		if (lun_req->num_be_args > 0) {
3171 			lun_req->kern_be_args = ctl_copyin_args(
3172 				lun_req->num_be_args,
3173 				lun_req->be_args,
3174 				lun_req->error_str,
3175 				sizeof(lun_req->error_str));
3176 			if (lun_req->kern_be_args == NULL) {
3177 				lun_req->status = CTL_LUN_ERROR;
3178 				break;
3179 			}
3180 		}
3181 
3182 		retval = backend->ioctl(dev, cmd, addr, flag, td);
3183 
3184 		if (lun_req->num_be_args > 0) {
3185 			ctl_copyout_args(lun_req->num_be_args,
3186 				      lun_req->kern_be_args);
3187 			ctl_free_args(lun_req->num_be_args,
3188 				      lun_req->kern_be_args);
3189 		}
3190 		break;
3191 	}
3192 	case CTL_LUN_LIST: {
3193 		struct sbuf *sb;
3194 		struct ctl_lun *lun;
3195 		struct ctl_lun_list *list;
3196 		struct ctl_option *opt;
3197 
3198 		list = (struct ctl_lun_list *)addr;
3199 
3200 		/*
3201 		 * Allocate a fixed length sbuf here, based on the length
3202 		 * of the user's buffer.  We could allocate an auto-extending
3203 		 * buffer, and then tell the user how much larger our
3204 		 * amount of data is than his buffer, but that presents
3205 		 * some problems:
3206 		 *
3207 		 * 1.  The sbuf(9) routines use a blocking malloc, and so
3208 		 *     we can't hold a lock while calling them with an
3209 		 *     auto-extending buffer.
3210  		 *
3211 		 * 2.  There is not currently a LUN reference counting
3212 		 *     mechanism, outside of outstanding transactions on
3213 		 *     the LUN's OOA queue.  So a LUN could go away on us
3214 		 *     while we're getting the LUN number, backend-specific
3215 		 *     information, etc.  Thus, given the way things
3216 		 *     currently work, we need to hold the CTL lock while
3217 		 *     grabbing LUN information.
3218 		 *
3219 		 * So, from the user's standpoint, the best thing to do is
3220 		 * allocate what he thinks is a reasonable buffer length,
3221 		 * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
3222 		 * double the buffer length and try again.  (And repeat
3223 		 * that until he succeeds.)
3224 		 */
3225 		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3226 		if (sb == NULL) {
3227 			list->status = CTL_LUN_LIST_ERROR;
3228 			snprintf(list->error_str, sizeof(list->error_str),
3229 				 "Unable to allocate %d bytes for LUN list",
3230 				 list->alloc_len);
3231 			break;
3232 		}
3233 
3234 		sbuf_printf(sb, "<ctllunlist>\n");
3235 
3236 		mtx_lock(&softc->ctl_lock);
3237 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
3238 			mtx_lock(&lun->lun_lock);
3239 			retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3240 					     (uintmax_t)lun->lun);
3241 
3242 			/*
3243 			 * Bail out as soon as we see that we've overfilled
3244 			 * the buffer.
3245 			 */
3246 			if (retval != 0)
3247 				break;
3248 
3249 			retval = sbuf_printf(sb, "\t<backend_type>%s"
3250 					     "</backend_type>\n",
3251 					     (lun->backend == NULL) ?  "none" :
3252 					     lun->backend->name);
3253 
3254 			if (retval != 0)
3255 				break;
3256 
3257 			retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3258 					     lun->be_lun->lun_type);
3259 
3260 			if (retval != 0)
3261 				break;
3262 
3263 			if (lun->backend == NULL) {
3264 				retval = sbuf_printf(sb, "</lun>\n");
3265 				if (retval != 0)
3266 					break;
3267 				continue;
3268 			}
3269 
3270 			retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3271 					     (lun->be_lun->maxlba > 0) ?
3272 					     lun->be_lun->maxlba + 1 : 0);
3273 
3274 			if (retval != 0)
3275 				break;
3276 
3277 			retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3278 					     lun->be_lun->blocksize);
3279 
3280 			if (retval != 0)
3281 				break;
3282 
3283 			retval = sbuf_printf(sb, "\t<serial_number>");
3284 
3285 			if (retval != 0)
3286 				break;
3287 
3288 			retval = ctl_sbuf_printf_esc(sb,
3289 			    lun->be_lun->serial_num,
3290 			    sizeof(lun->be_lun->serial_num));
3291 
3292 			if (retval != 0)
3293 				break;
3294 
3295 			retval = sbuf_printf(sb, "</serial_number>\n");
3296 
3297 			if (retval != 0)
3298 				break;
3299 
3300 			retval = sbuf_printf(sb, "\t<device_id>");
3301 
3302 			if (retval != 0)
3303 				break;
3304 
3305 			retval = ctl_sbuf_printf_esc(sb,
3306 			    lun->be_lun->device_id,
3307 			    sizeof(lun->be_lun->device_id));
3308 
3309 			if (retval != 0)
3310 				break;
3311 
3312 			retval = sbuf_printf(sb, "</device_id>\n");
3313 
3314 			if (retval != 0)
3315 				break;
3316 
3317 			if (lun->backend->lun_info != NULL) {
3318 				retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
3319 				if (retval != 0)
3320 					break;
3321 			}
3322 			STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
3323 				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3324 				    opt->name, opt->value, opt->name);
3325 				if (retval != 0)
3326 					break;
3327 			}
3328 
3329 			retval = sbuf_printf(sb, "</lun>\n");
3330 
3331 			if (retval != 0)
3332 				break;
3333 			mtx_unlock(&lun->lun_lock);
3334 		}
3335 		if (lun != NULL)
3336 			mtx_unlock(&lun->lun_lock);
3337 		mtx_unlock(&softc->ctl_lock);
3338 
3339 		if ((retval != 0)
3340 		 || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3341 			retval = 0;
3342 			sbuf_delete(sb);
3343 			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3344 			snprintf(list->error_str, sizeof(list->error_str),
3345 				 "Out of space, %d bytes is too small",
3346 				 list->alloc_len);
3347 			break;
3348 		}
3349 
3350 		sbuf_finish(sb);
3351 
3352 		retval = copyout(sbuf_data(sb), list->lun_xml,
3353 				 sbuf_len(sb) + 1);
3354 
3355 		list->fill_len = sbuf_len(sb) + 1;
3356 		list->status = CTL_LUN_LIST_OK;
3357 		sbuf_delete(sb);
3358 		break;
3359 	}
3360 	case CTL_ISCSI: {
3361 		struct ctl_iscsi *ci;
3362 		struct ctl_frontend *fe;
3363 
3364 		ci = (struct ctl_iscsi *)addr;
3365 
3366 		fe = ctl_frontend_find("iscsi");
3367 		if (fe == NULL) {
3368 			ci->status = CTL_ISCSI_ERROR;
3369 			snprintf(ci->error_str, sizeof(ci->error_str),
3370 			    "Frontend \"iscsi\" not found.");
3371 			break;
3372 		}
3373 
3374 		retval = fe->ioctl(dev, cmd, addr, flag, td);
3375 		break;
3376 	}
3377 	case CTL_PORT_REQ: {
3378 		struct ctl_req *req;
3379 		struct ctl_frontend *fe;
3380 
3381 		req = (struct ctl_req *)addr;
3382 
3383 		fe = ctl_frontend_find(req->driver);
3384 		if (fe == NULL) {
3385 			req->status = CTL_LUN_ERROR;
3386 			snprintf(req->error_str, sizeof(req->error_str),
3387 			    "Frontend \"%s\" not found.", req->driver);
3388 			break;
3389 		}
3390 		if (req->num_args > 0) {
3391 			req->kern_args = ctl_copyin_args(req->num_args,
3392 			    req->args, req->error_str, sizeof(req->error_str));
3393 			if (req->kern_args == NULL) {
3394 				req->status = CTL_LUN_ERROR;
3395 				break;
3396 			}
3397 		}
3398 
3399 		retval = fe->ioctl(dev, cmd, addr, flag, td);
3400 
3401 		if (req->num_args > 0) {
3402 			ctl_copyout_args(req->num_args, req->kern_args);
3403 			ctl_free_args(req->num_args, req->kern_args);
3404 		}
3405 		break;
3406 	}
3407 	case CTL_PORT_LIST: {
3408 		struct sbuf *sb;
3409 		struct ctl_port *port;
3410 		struct ctl_lun_list *list;
3411 		struct ctl_option *opt;
3412 		int j;
3413 
3414 		list = (struct ctl_lun_list *)addr;
3415 
3416 		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3417 		if (sb == NULL) {
3418 			list->status = CTL_LUN_LIST_ERROR;
3419 			snprintf(list->error_str, sizeof(list->error_str),
3420 				 "Unable to allocate %d bytes for LUN list",
3421 				 list->alloc_len);
3422 			break;
3423 		}
3424 
3425 		sbuf_printf(sb, "<ctlportlist>\n");
3426 
3427 		mtx_lock(&softc->ctl_lock);
3428 		STAILQ_FOREACH(port, &softc->port_list, links) {
3429 			retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3430 					     (uintmax_t)port->targ_port);
3431 
3432 			/*
3433 			 * Bail out as soon as we see that we've overfilled
3434 			 * the buffer.
3435 			 */
3436 			if (retval != 0)
3437 				break;
3438 
3439 			retval = sbuf_printf(sb, "\t<frontend_type>%s"
3440 			    "</frontend_type>\n", port->frontend->name);
3441 			if (retval != 0)
3442 				break;
3443 
3444 			retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3445 					     port->port_type);
3446 			if (retval != 0)
3447 				break;
3448 
3449 			retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3450 			    (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3451 			if (retval != 0)
3452 				break;
3453 
3454 			retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3455 			    port->port_name);
3456 			if (retval != 0)
3457 				break;
3458 
3459 			retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3460 			    port->physical_port);
3461 			if (retval != 0)
3462 				break;
3463 
3464 			retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3465 			    port->virtual_port);
3466 			if (retval != 0)
3467 				break;
3468 
3469 			if (port->target_devid != NULL) {
3470 				sbuf_printf(sb, "\t<target>");
3471 				ctl_id_sbuf(port->target_devid, sb);
3472 				sbuf_printf(sb, "</target>\n");
3473 			}
3474 
3475 			if (port->port_devid != NULL) {
3476 				sbuf_printf(sb, "\t<port>");
3477 				ctl_id_sbuf(port->port_devid, sb);
3478 				sbuf_printf(sb, "</port>\n");
3479 			}
3480 
3481 			if (port->port_info != NULL) {
3482 				retval = port->port_info(port->onoff_arg, sb);
3483 				if (retval != 0)
3484 					break;
3485 			}
3486 			STAILQ_FOREACH(opt, &port->options, links) {
3487 				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3488 				    opt->name, opt->value, opt->name);
3489 				if (retval != 0)
3490 					break;
3491 			}
3492 
3493 			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3494 				if (port->wwpn_iid[j].in_use == 0 ||
3495 				    (port->wwpn_iid[j].wwpn == 0 &&
3496 				     port->wwpn_iid[j].name == NULL))
3497 					continue;
3498 
3499 				if (port->wwpn_iid[j].name != NULL)
3500 					retval = sbuf_printf(sb,
3501 					    "\t<initiator>%u %s</initiator>\n",
3502 					    j, port->wwpn_iid[j].name);
3503 				else
3504 					retval = sbuf_printf(sb,
3505 					    "\t<initiator>%u naa.%08jx</initiator>\n",
3506 					    j, port->wwpn_iid[j].wwpn);
3507 				if (retval != 0)
3508 					break;
3509 			}
3510 			if (retval != 0)
3511 				break;
3512 
3513 			retval = sbuf_printf(sb, "</targ_port>\n");
3514 			if (retval != 0)
3515 				break;
3516 		}
3517 		mtx_unlock(&softc->ctl_lock);
3518 
3519 		if ((retval != 0)
3520 		 || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3521 			retval = 0;
3522 			sbuf_delete(sb);
3523 			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3524 			snprintf(list->error_str, sizeof(list->error_str),
3525 				 "Out of space, %d bytes is too small",
3526 				 list->alloc_len);
3527 			break;
3528 		}
3529 
3530 		sbuf_finish(sb);
3531 
3532 		retval = copyout(sbuf_data(sb), list->lun_xml,
3533 				 sbuf_len(sb) + 1);
3534 
3535 		list->fill_len = sbuf_len(sb) + 1;
3536 		list->status = CTL_LUN_LIST_OK;
3537 		sbuf_delete(sb);
3538 		break;
3539 	}
3540 	default: {
3541 		/* XXX KDM should we fix this? */
3542 #if 0
3543 		struct ctl_backend_driver *backend;
3544 		unsigned int type;
3545 		int found;
3546 
3547 		found = 0;
3548 
3549 		/*
3550 		 * We encode the backend type as the ioctl type for backend
3551 		 * ioctls.  So parse it out here, and then search for a
3552 		 * backend of this type.
3553 		 */
3554 		type = _IOC_TYPE(cmd);
3555 
3556 		STAILQ_FOREACH(backend, &softc->be_list, links) {
3557 			if (backend->type == type) {
3558 				found = 1;
3559 				break;
3560 			}
3561 		}
3562 		if (found == 0) {
3563 			printf("ctl: unknown ioctl command %#lx or backend "
3564 			       "%d\n", cmd, type);
3565 			retval = EINVAL;
3566 			break;
3567 		}
3568 		retval = backend->ioctl(dev, cmd, addr, flag, td);
3569 #endif
3570 		retval = ENOTTY;
3571 		break;
3572 	}
3573 	}
3574 	return (retval);
3575 }
3576 
3577 uint32_t
3578 ctl_get_initindex(struct ctl_nexus *nexus)
3579 {
3580 	if (nexus->targ_port < CTL_MAX_PORTS)
3581 		return (nexus->initid.id +
3582 			(nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3583 	else
3584 		return (nexus->initid.id +
3585 		       ((nexus->targ_port - CTL_MAX_PORTS) *
3586 			CTL_MAX_INIT_PER_PORT));
3587 }
3588 
3589 uint32_t
3590 ctl_get_resindex(struct ctl_nexus *nexus)
3591 {
3592 	return (nexus->initid.id + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3593 }
3594 
3595 uint32_t
3596 ctl_port_idx(int port_num)
3597 {
3598 	if (port_num < CTL_MAX_PORTS)
3599 		return(port_num);
3600 	else
3601 		return(port_num - CTL_MAX_PORTS);
3602 }
3603 
3604 static uint32_t
3605 ctl_map_lun(int port_num, uint32_t lun_id)
3606 {
3607 	struct ctl_port *port;
3608 
3609 	port = control_softc->ctl_ports[ctl_port_idx(port_num)];
3610 	if (port == NULL)
3611 		return (UINT32_MAX);
3612 	if (port->lun_map == NULL)
3613 		return (lun_id);
3614 	return (port->lun_map(port->targ_lun_arg, lun_id));
3615 }
3616 
3617 static uint32_t
3618 ctl_map_lun_back(int port_num, uint32_t lun_id)
3619 {
3620 	struct ctl_port *port;
3621 	uint32_t i;
3622 
3623 	port = control_softc->ctl_ports[ctl_port_idx(port_num)];
3624 	if (port->lun_map == NULL)
3625 		return (lun_id);
3626 	for (i = 0; i < CTL_MAX_LUNS; i++) {
3627 		if (port->lun_map(port->targ_lun_arg, i) == lun_id)
3628 			return (i);
3629 	}
3630 	return (UINT32_MAX);
3631 }
3632 
3633 /*
3634  * Note:  This only works for bitmask sizes that are at least 32 bits, and
3635  * that are a power of 2.
3636  */
3637 int
3638 ctl_ffz(uint32_t *mask, uint32_t size)
3639 {
3640 	uint32_t num_chunks, num_pieces;
3641 	int i, j;
3642 
3643 	num_chunks = (size >> 5);
3644 	if (num_chunks == 0)
3645 		num_chunks++;
3646 	num_pieces = ctl_min((sizeof(uint32_t) * 8), size);
3647 
3648 	for (i = 0; i < num_chunks; i++) {
3649 		for (j = 0; j < num_pieces; j++) {
3650 			if ((mask[i] & (1 << j)) == 0)
3651 				return ((i << 5) + j);
3652 		}
3653 	}
3654 
3655 	return (-1);
3656 }
3657 
3658 int
3659 ctl_set_mask(uint32_t *mask, uint32_t bit)
3660 {
3661 	uint32_t chunk, piece;
3662 
3663 	chunk = bit >> 5;
3664 	piece = bit % (sizeof(uint32_t) * 8);
3665 
3666 	if ((mask[chunk] & (1 << piece)) != 0)
3667 		return (-1);
3668 	else
3669 		mask[chunk] |= (1 << piece);
3670 
3671 	return (0);
3672 }
3673 
3674 int
3675 ctl_clear_mask(uint32_t *mask, uint32_t bit)
3676 {
3677 	uint32_t chunk, piece;
3678 
3679 	chunk = bit >> 5;
3680 	piece = bit % (sizeof(uint32_t) * 8);
3681 
3682 	if ((mask[chunk] & (1 << piece)) == 0)
3683 		return (-1);
3684 	else
3685 		mask[chunk] &= ~(1 << piece);
3686 
3687 	return (0);
3688 }
3689 
3690 int
3691 ctl_is_set(uint32_t *mask, uint32_t bit)
3692 {
3693 	uint32_t chunk, piece;
3694 
3695 	chunk = bit >> 5;
3696 	piece = bit % (sizeof(uint32_t) * 8);
3697 
3698 	if ((mask[chunk] & (1 << piece)) == 0)
3699 		return (0);
3700 	else
3701 		return (1);
3702 }
3703 
3704 static uint64_t
3705 ctl_get_prkey(struct ctl_lun *lun, uint32_t residx)
3706 {
3707 	uint64_t *t;
3708 
3709 	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3710 	if (t == NULL)
3711 		return (0);
3712 	return (t[residx % CTL_MAX_INIT_PER_PORT]);
3713 }
3714 
3715 static void
3716 ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx)
3717 {
3718 	uint64_t *t;
3719 
3720 	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3721 	if (t == NULL)
3722 		return;
3723 	t[residx % CTL_MAX_INIT_PER_PORT] = 0;
3724 }
3725 
3726 static void
3727 ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx)
3728 {
3729 	uint64_t *p;
3730 	u_int i;
3731 
3732 	i = residx/CTL_MAX_INIT_PER_PORT;
3733 	if (lun->pr_keys[i] != NULL)
3734 		return;
3735 	mtx_unlock(&lun->lun_lock);
3736 	p = malloc(sizeof(uint64_t) * CTL_MAX_INIT_PER_PORT, M_CTL,
3737 	    M_WAITOK | M_ZERO);
3738 	mtx_lock(&lun->lun_lock);
3739 	if (lun->pr_keys[i] == NULL)
3740 		lun->pr_keys[i] = p;
3741 	else
3742 		free(p, M_CTL);
3743 }
3744 
3745 static void
3746 ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key)
3747 {
3748 	uint64_t *t;
3749 
3750 	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3751 	KASSERT(t != NULL, ("prkey %d is not allocated", residx));
3752 	t[residx % CTL_MAX_INIT_PER_PORT] = key;
3753 }
3754 
3755 /*
3756  * ctl_softc, pool_name, total_ctl_io are passed in.
3757  * npool is passed out.
3758  */
3759 int
3760 ctl_pool_create(struct ctl_softc *ctl_softc, const char *pool_name,
3761 		uint32_t total_ctl_io, void **npool)
3762 {
3763 #ifdef IO_POOLS
3764 	struct ctl_io_pool *pool;
3765 
3766 	pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3767 					    M_NOWAIT | M_ZERO);
3768 	if (pool == NULL)
3769 		return (ENOMEM);
3770 
3771 	snprintf(pool->name, sizeof(pool->name), "CTL IO %s", pool_name);
3772 	pool->ctl_softc = ctl_softc;
3773 	pool->zone = uma_zsecond_create(pool->name, NULL,
3774 	    NULL, NULL, NULL, ctl_softc->io_zone);
3775 	/* uma_prealloc(pool->zone, total_ctl_io); */
3776 
3777 	*npool = pool;
3778 #else
3779 	*npool = ctl_softc->io_zone;
3780 #endif
3781 	return (0);
3782 }
3783 
3784 void
3785 ctl_pool_free(struct ctl_io_pool *pool)
3786 {
3787 
3788 	if (pool == NULL)
3789 		return;
3790 
3791 #ifdef IO_POOLS
3792 	uma_zdestroy(pool->zone);
3793 	free(pool, M_CTL);
3794 #endif
3795 }
3796 
3797 union ctl_io *
3798 ctl_alloc_io(void *pool_ref)
3799 {
3800 	union ctl_io *io;
3801 #ifdef IO_POOLS
3802 	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3803 
3804 	io = uma_zalloc(pool->zone, M_WAITOK);
3805 #else
3806 	io = uma_zalloc((uma_zone_t)pool_ref, M_WAITOK);
3807 #endif
3808 	if (io != NULL)
3809 		io->io_hdr.pool = pool_ref;
3810 	return (io);
3811 }
3812 
3813 union ctl_io *
3814 ctl_alloc_io_nowait(void *pool_ref)
3815 {
3816 	union ctl_io *io;
3817 #ifdef IO_POOLS
3818 	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3819 
3820 	io = uma_zalloc(pool->zone, M_NOWAIT);
3821 #else
3822 	io = uma_zalloc((uma_zone_t)pool_ref, M_NOWAIT);
3823 #endif
3824 	if (io != NULL)
3825 		io->io_hdr.pool = pool_ref;
3826 	return (io);
3827 }
3828 
3829 void
3830 ctl_free_io(union ctl_io *io)
3831 {
3832 #ifdef IO_POOLS
3833 	struct ctl_io_pool *pool;
3834 #endif
3835 
3836 	if (io == NULL)
3837 		return;
3838 
3839 #ifdef IO_POOLS
3840 	pool = (struct ctl_io_pool *)io->io_hdr.pool;
3841 	uma_zfree(pool->zone, io);
3842 #else
3843 	uma_zfree((uma_zone_t)io->io_hdr.pool, io);
3844 #endif
3845 }
3846 
3847 void
3848 ctl_zero_io(union ctl_io *io)
3849 {
3850 	void *pool_ref;
3851 
3852 	if (io == NULL)
3853 		return;
3854 
3855 	/*
3856 	 * May need to preserve linked list pointers at some point too.
3857 	 */
3858 	pool_ref = io->io_hdr.pool;
3859 	memset(io, 0, sizeof(*io));
3860 	io->io_hdr.pool = pool_ref;
3861 }
3862 
3863 /*
3864  * This routine is currently used for internal copies of ctl_ios that need
3865  * to persist for some reason after we've already returned status to the
3866  * FETD.  (Thus the flag set.)
3867  *
3868  * XXX XXX
3869  * Note that this makes a blind copy of all fields in the ctl_io, except
3870  * for the pool reference.  This includes any memory that has been
3871  * allocated!  That memory will no longer be valid after done has been
3872  * called, so this would be VERY DANGEROUS for command that actually does
3873  * any reads or writes.  Right now (11/7/2005), this is only used for immediate
3874  * start and stop commands, which don't transfer any data, so this is not a
3875  * problem.  If it is used for anything else, the caller would also need to
3876  * allocate data buffer space and this routine would need to be modified to
3877  * copy the data buffer(s) as well.
3878  */
3879 void
3880 ctl_copy_io(union ctl_io *src, union ctl_io *dest)
3881 {
3882 	void *pool_ref;
3883 
3884 	if ((src == NULL)
3885 	 || (dest == NULL))
3886 		return;
3887 
3888 	/*
3889 	 * May need to preserve linked list pointers at some point too.
3890 	 */
3891 	pool_ref = dest->io_hdr.pool;
3892 
3893 	memcpy(dest, src, ctl_min(sizeof(*src), sizeof(*dest)));
3894 
3895 	dest->io_hdr.pool = pool_ref;
3896 	/*
3897 	 * We need to know that this is an internal copy, and doesn't need
3898 	 * to get passed back to the FETD that allocated it.
3899 	 */
3900 	dest->io_hdr.flags |= CTL_FLAG_INT_COPY;
3901 }
3902 
3903 static int
3904 ctl_expand_number(const char *buf, uint64_t *num)
3905 {
3906 	char *endptr;
3907 	uint64_t number;
3908 	unsigned shift;
3909 
3910 	number = strtoq(buf, &endptr, 0);
3911 
3912 	switch (tolower((unsigned char)*endptr)) {
3913 	case 'e':
3914 		shift = 60;
3915 		break;
3916 	case 'p':
3917 		shift = 50;
3918 		break;
3919 	case 't':
3920 		shift = 40;
3921 		break;
3922 	case 'g':
3923 		shift = 30;
3924 		break;
3925 	case 'm':
3926 		shift = 20;
3927 		break;
3928 	case 'k':
3929 		shift = 10;
3930 		break;
3931 	case 'b':
3932 	case '\0': /* No unit. */
3933 		*num = number;
3934 		return (0);
3935 	default:
3936 		/* Unrecognized unit. */
3937 		return (-1);
3938 	}
3939 
3940 	if ((number << shift) >> shift != number) {
3941 		/* Overflow */
3942 		return (-1);
3943 	}
3944 	*num = number << shift;
3945 	return (0);
3946 }
3947 
3948 
3949 /*
3950  * This routine could be used in the future to load default and/or saved
3951  * mode page parameters for a particuar lun.
3952  */
3953 static int
3954 ctl_init_page_index(struct ctl_lun *lun)
3955 {
3956 	int i;
3957 	struct ctl_page_index *page_index;
3958 	const char *value;
3959 	uint64_t ival;
3960 
3961 	memcpy(&lun->mode_pages.index, page_index_template,
3962 	       sizeof(page_index_template));
3963 
3964 	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
3965 
3966 		page_index = &lun->mode_pages.index[i];
3967 		/*
3968 		 * If this is a disk-only mode page, there's no point in
3969 		 * setting it up.  For some pages, we have to have some
3970 		 * basic information about the disk in order to calculate the
3971 		 * mode page data.
3972 		 */
3973 		if ((lun->be_lun->lun_type != T_DIRECT)
3974 		 && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
3975 			continue;
3976 
3977 		switch (page_index->page_code & SMPH_PC_MASK) {
3978 		case SMS_RW_ERROR_RECOVERY_PAGE: {
3979 			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3980 				panic("subpage is incorrect!");
3981 			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT],
3982 			       &rw_er_page_default,
3983 			       sizeof(rw_er_page_default));
3984 			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CHANGEABLE],
3985 			       &rw_er_page_changeable,
3986 			       sizeof(rw_er_page_changeable));
3987 			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_DEFAULT],
3988 			       &rw_er_page_default,
3989 			       sizeof(rw_er_page_default));
3990 			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_SAVED],
3991 			       &rw_er_page_default,
3992 			       sizeof(rw_er_page_default));
3993 			page_index->page_data =
3994 				(uint8_t *)lun->mode_pages.rw_er_page;
3995 			break;
3996 		}
3997 		case SMS_FORMAT_DEVICE_PAGE: {
3998 			struct scsi_format_page *format_page;
3999 
4000 			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4001 				panic("subpage is incorrect!");
4002 
4003 			/*
4004 			 * Sectors per track are set above.  Bytes per
4005 			 * sector need to be set here on a per-LUN basis.
4006 			 */
4007 			memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
4008 			       &format_page_default,
4009 			       sizeof(format_page_default));
4010 			memcpy(&lun->mode_pages.format_page[
4011 			       CTL_PAGE_CHANGEABLE], &format_page_changeable,
4012 			       sizeof(format_page_changeable));
4013 			memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
4014 			       &format_page_default,
4015 			       sizeof(format_page_default));
4016 			memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
4017 			       &format_page_default,
4018 			       sizeof(format_page_default));
4019 
4020 			format_page = &lun->mode_pages.format_page[
4021 				CTL_PAGE_CURRENT];
4022 			scsi_ulto2b(lun->be_lun->blocksize,
4023 				    format_page->bytes_per_sector);
4024 
4025 			format_page = &lun->mode_pages.format_page[
4026 				CTL_PAGE_DEFAULT];
4027 			scsi_ulto2b(lun->be_lun->blocksize,
4028 				    format_page->bytes_per_sector);
4029 
4030 			format_page = &lun->mode_pages.format_page[
4031 				CTL_PAGE_SAVED];
4032 			scsi_ulto2b(lun->be_lun->blocksize,
4033 				    format_page->bytes_per_sector);
4034 
4035 			page_index->page_data =
4036 				(uint8_t *)lun->mode_pages.format_page;
4037 			break;
4038 		}
4039 		case SMS_RIGID_DISK_PAGE: {
4040 			struct scsi_rigid_disk_page *rigid_disk_page;
4041 			uint32_t sectors_per_cylinder;
4042 			uint64_t cylinders;
4043 #ifndef	__XSCALE__
4044 			int shift;
4045 #endif /* !__XSCALE__ */
4046 
4047 			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4048 				panic("invalid subpage value %d",
4049 				      page_index->subpage);
4050 
4051 			/*
4052 			 * Rotation rate and sectors per track are set
4053 			 * above.  We calculate the cylinders here based on
4054 			 * capacity.  Due to the number of heads and
4055 			 * sectors per track we're using, smaller arrays
4056 			 * may turn out to have 0 cylinders.  Linux and
4057 			 * FreeBSD don't pay attention to these mode pages
4058 			 * to figure out capacity, but Solaris does.  It
4059 			 * seems to deal with 0 cylinders just fine, and
4060 			 * works out a fake geometry based on the capacity.
4061 			 */
4062 			memcpy(&lun->mode_pages.rigid_disk_page[
4063 			       CTL_PAGE_DEFAULT], &rigid_disk_page_default,
4064 			       sizeof(rigid_disk_page_default));
4065 			memcpy(&lun->mode_pages.rigid_disk_page[
4066 			       CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
4067 			       sizeof(rigid_disk_page_changeable));
4068 
4069 			sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
4070 				CTL_DEFAULT_HEADS;
4071 
4072 			/*
4073 			 * The divide method here will be more accurate,
4074 			 * probably, but results in floating point being
4075 			 * used in the kernel on i386 (__udivdi3()).  On the
4076 			 * XScale, though, __udivdi3() is implemented in
4077 			 * software.
4078 			 *
4079 			 * The shift method for cylinder calculation is
4080 			 * accurate if sectors_per_cylinder is a power of
4081 			 * 2.  Otherwise it might be slightly off -- you
4082 			 * might have a bit of a truncation problem.
4083 			 */
4084 #ifdef	__XSCALE__
4085 			cylinders = (lun->be_lun->maxlba + 1) /
4086 				sectors_per_cylinder;
4087 #else
4088 			for (shift = 31; shift > 0; shift--) {
4089 				if (sectors_per_cylinder & (1 << shift))
4090 					break;
4091 			}
4092 			cylinders = (lun->be_lun->maxlba + 1) >> shift;
4093 #endif
4094 
4095 			/*
4096 			 * We've basically got 3 bytes, or 24 bits for the
4097 			 * cylinder size in the mode page.  If we're over,
4098 			 * just round down to 2^24.
4099 			 */
4100 			if (cylinders > 0xffffff)
4101 				cylinders = 0xffffff;
4102 
4103 			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4104 				CTL_PAGE_DEFAULT];
4105 			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4106 
4107 			if ((value = ctl_get_opt(&lun->be_lun->options,
4108 			    "rpm")) != NULL) {
4109 				scsi_ulto2b(strtol(value, NULL, 0),
4110 				     rigid_disk_page->rotation_rate);
4111 			}
4112 
4113 			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_CURRENT],
4114 			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4115 			       sizeof(rigid_disk_page_default));
4116 			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_SAVED],
4117 			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4118 			       sizeof(rigid_disk_page_default));
4119 
4120 			page_index->page_data =
4121 				(uint8_t *)lun->mode_pages.rigid_disk_page;
4122 			break;
4123 		}
4124 		case SMS_CACHING_PAGE: {
4125 			struct scsi_caching_page *caching_page;
4126 
4127 			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4128 				panic("invalid subpage value %d",
4129 				      page_index->subpage);
4130 			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4131 			       &caching_page_default,
4132 			       sizeof(caching_page_default));
4133 			memcpy(&lun->mode_pages.caching_page[
4134 			       CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4135 			       sizeof(caching_page_changeable));
4136 			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4137 			       &caching_page_default,
4138 			       sizeof(caching_page_default));
4139 			caching_page = &lun->mode_pages.caching_page[
4140 			    CTL_PAGE_SAVED];
4141 			value = ctl_get_opt(&lun->be_lun->options, "writecache");
4142 			if (value != NULL && strcmp(value, "off") == 0)
4143 				caching_page->flags1 &= ~SCP_WCE;
4144 			value = ctl_get_opt(&lun->be_lun->options, "readcache");
4145 			if (value != NULL && strcmp(value, "off") == 0)
4146 				caching_page->flags1 |= SCP_RCD;
4147 			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4148 			       &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4149 			       sizeof(caching_page_default));
4150 			page_index->page_data =
4151 				(uint8_t *)lun->mode_pages.caching_page;
4152 			break;
4153 		}
4154 		case SMS_CONTROL_MODE_PAGE: {
4155 			struct scsi_control_page *control_page;
4156 
4157 			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4158 				panic("invalid subpage value %d",
4159 				      page_index->subpage);
4160 
4161 			memcpy(&lun->mode_pages.control_page[CTL_PAGE_DEFAULT],
4162 			       &control_page_default,
4163 			       sizeof(control_page_default));
4164 			memcpy(&lun->mode_pages.control_page[
4165 			       CTL_PAGE_CHANGEABLE], &control_page_changeable,
4166 			       sizeof(control_page_changeable));
4167 			memcpy(&lun->mode_pages.control_page[CTL_PAGE_SAVED],
4168 			       &control_page_default,
4169 			       sizeof(control_page_default));
4170 			control_page = &lun->mode_pages.control_page[
4171 			    CTL_PAGE_SAVED];
4172 			value = ctl_get_opt(&lun->be_lun->options, "reordering");
4173 			if (value != NULL && strcmp(value, "unrestricted") == 0) {
4174 				control_page->queue_flags &= ~SCP_QUEUE_ALG_MASK;
4175 				control_page->queue_flags |= SCP_QUEUE_ALG_UNRESTRICTED;
4176 			}
4177 			memcpy(&lun->mode_pages.control_page[CTL_PAGE_CURRENT],
4178 			       &lun->mode_pages.control_page[CTL_PAGE_SAVED],
4179 			       sizeof(control_page_default));
4180 			page_index->page_data =
4181 				(uint8_t *)lun->mode_pages.control_page;
4182 			break;
4183 
4184 		}
4185 		case SMS_INFO_EXCEPTIONS_PAGE: {
4186 			switch (page_index->subpage) {
4187 			case SMS_SUBPAGE_PAGE_0:
4188 				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_CURRENT],
4189 				       &ie_page_default,
4190 				       sizeof(ie_page_default));
4191 				memcpy(&lun->mode_pages.ie_page[
4192 				       CTL_PAGE_CHANGEABLE], &ie_page_changeable,
4193 				       sizeof(ie_page_changeable));
4194 				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_DEFAULT],
4195 				       &ie_page_default,
4196 				       sizeof(ie_page_default));
4197 				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_SAVED],
4198 				       &ie_page_default,
4199 				       sizeof(ie_page_default));
4200 				page_index->page_data =
4201 					(uint8_t *)lun->mode_pages.ie_page;
4202 				break;
4203 			case 0x02: {
4204 				struct ctl_logical_block_provisioning_page *page;
4205 
4206 				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_DEFAULT],
4207 				       &lbp_page_default,
4208 				       sizeof(lbp_page_default));
4209 				memcpy(&lun->mode_pages.lbp_page[
4210 				       CTL_PAGE_CHANGEABLE], &lbp_page_changeable,
4211 				       sizeof(lbp_page_changeable));
4212 				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4213 				       &lbp_page_default,
4214 				       sizeof(lbp_page_default));
4215 				page = &lun->mode_pages.lbp_page[CTL_PAGE_SAVED];
4216 				value = ctl_get_opt(&lun->be_lun->options,
4217 				    "avail-threshold");
4218 				if (value != NULL &&
4219 				    ctl_expand_number(value, &ival) == 0) {
4220 					page->descr[0].flags |= SLBPPD_ENABLED |
4221 					    SLBPPD_ARMING_DEC;
4222 					if (lun->be_lun->blocksize)
4223 						ival /= lun->be_lun->blocksize;
4224 					else
4225 						ival /= 512;
4226 					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4227 					    page->descr[0].count);
4228 				}
4229 				value = ctl_get_opt(&lun->be_lun->options,
4230 				    "used-threshold");
4231 				if (value != NULL &&
4232 				    ctl_expand_number(value, &ival) == 0) {
4233 					page->descr[1].flags |= SLBPPD_ENABLED |
4234 					    SLBPPD_ARMING_INC;
4235 					if (lun->be_lun->blocksize)
4236 						ival /= lun->be_lun->blocksize;
4237 					else
4238 						ival /= 512;
4239 					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4240 					    page->descr[1].count);
4241 				}
4242 				value = ctl_get_opt(&lun->be_lun->options,
4243 				    "pool-avail-threshold");
4244 				if (value != NULL &&
4245 				    ctl_expand_number(value, &ival) == 0) {
4246 					page->descr[2].flags |= SLBPPD_ENABLED |
4247 					    SLBPPD_ARMING_DEC;
4248 					if (lun->be_lun->blocksize)
4249 						ival /= lun->be_lun->blocksize;
4250 					else
4251 						ival /= 512;
4252 					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4253 					    page->descr[2].count);
4254 				}
4255 				value = ctl_get_opt(&lun->be_lun->options,
4256 				    "pool-used-threshold");
4257 				if (value != NULL &&
4258 				    ctl_expand_number(value, &ival) == 0) {
4259 					page->descr[3].flags |= SLBPPD_ENABLED |
4260 					    SLBPPD_ARMING_INC;
4261 					if (lun->be_lun->blocksize)
4262 						ival /= lun->be_lun->blocksize;
4263 					else
4264 						ival /= 512;
4265 					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4266 					    page->descr[3].count);
4267 				}
4268 				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_CURRENT],
4269 				       &lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4270 				       sizeof(lbp_page_default));
4271 				page_index->page_data =
4272 					(uint8_t *)lun->mode_pages.lbp_page;
4273 			}}
4274 			break;
4275 		}
4276 		case SMS_VENDOR_SPECIFIC_PAGE:{
4277 			switch (page_index->subpage) {
4278 			case DBGCNF_SUBPAGE_CODE: {
4279 				struct copan_debugconf_subpage *current_page,
4280 							       *saved_page;
4281 
4282 				memcpy(&lun->mode_pages.debugconf_subpage[
4283 				       CTL_PAGE_CURRENT],
4284 				       &debugconf_page_default,
4285 				       sizeof(debugconf_page_default));
4286 				memcpy(&lun->mode_pages.debugconf_subpage[
4287 				       CTL_PAGE_CHANGEABLE],
4288 				       &debugconf_page_changeable,
4289 				       sizeof(debugconf_page_changeable));
4290 				memcpy(&lun->mode_pages.debugconf_subpage[
4291 				       CTL_PAGE_DEFAULT],
4292 				       &debugconf_page_default,
4293 				       sizeof(debugconf_page_default));
4294 				memcpy(&lun->mode_pages.debugconf_subpage[
4295 				       CTL_PAGE_SAVED],
4296 				       &debugconf_page_default,
4297 				       sizeof(debugconf_page_default));
4298 				page_index->page_data =
4299 					(uint8_t *)lun->mode_pages.debugconf_subpage;
4300 
4301 				current_page = (struct copan_debugconf_subpage *)
4302 					(page_index->page_data +
4303 					 (page_index->page_len *
4304 					  CTL_PAGE_CURRENT));
4305 				saved_page = (struct copan_debugconf_subpage *)
4306 					(page_index->page_data +
4307 					 (page_index->page_len *
4308 					  CTL_PAGE_SAVED));
4309 				break;
4310 			}
4311 			default:
4312 				panic("invalid subpage value %d",
4313 				      page_index->subpage);
4314 				break;
4315 			}
4316    			break;
4317 		}
4318 		default:
4319 			panic("invalid page value %d",
4320 			      page_index->page_code & SMPH_PC_MASK);
4321 			break;
4322     	}
4323 	}
4324 
4325 	return (CTL_RETVAL_COMPLETE);
4326 }
4327 
4328 static int
4329 ctl_init_log_page_index(struct ctl_lun *lun)
4330 {
4331 	struct ctl_page_index *page_index;
4332 	int i, j, k, prev;
4333 
4334 	memcpy(&lun->log_pages.index, log_page_index_template,
4335 	       sizeof(log_page_index_template));
4336 
4337 	prev = -1;
4338 	for (i = 0, j = 0, k = 0; i < CTL_NUM_LOG_PAGES; i++) {
4339 
4340 		page_index = &lun->log_pages.index[i];
4341 		/*
4342 		 * If this is a disk-only mode page, there's no point in
4343 		 * setting it up.  For some pages, we have to have some
4344 		 * basic information about the disk in order to calculate the
4345 		 * mode page data.
4346 		 */
4347 		if ((lun->be_lun->lun_type != T_DIRECT)
4348 		 && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
4349 			continue;
4350 
4351 		if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING &&
4352 		     lun->backend->lun_attr == NULL)
4353 			continue;
4354 
4355 		if (page_index->page_code != prev) {
4356 			lun->log_pages.pages_page[j] = page_index->page_code;
4357 			prev = page_index->page_code;
4358 			j++;
4359 		}
4360 		lun->log_pages.subpages_page[k*2] = page_index->page_code;
4361 		lun->log_pages.subpages_page[k*2+1] = page_index->subpage;
4362 		k++;
4363 	}
4364 	lun->log_pages.index[0].page_data = &lun->log_pages.pages_page[0];
4365 	lun->log_pages.index[0].page_len = j;
4366 	lun->log_pages.index[1].page_data = &lun->log_pages.subpages_page[0];
4367 	lun->log_pages.index[1].page_len = k * 2;
4368 	lun->log_pages.index[2].page_data = &lun->log_pages.lbp_page[0];
4369 	lun->log_pages.index[2].page_len = 12*CTL_NUM_LBP_PARAMS;
4370 
4371 	return (CTL_RETVAL_COMPLETE);
4372 }
4373 
4374 static int
4375 hex2bin(const char *str, uint8_t *buf, int buf_size)
4376 {
4377 	int i;
4378 	u_char c;
4379 
4380 	memset(buf, 0, buf_size);
4381 	while (isspace(str[0]))
4382 		str++;
4383 	if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
4384 		str += 2;
4385 	buf_size *= 2;
4386 	for (i = 0; str[i] != 0 && i < buf_size; i++) {
4387 		c = str[i];
4388 		if (isdigit(c))
4389 			c -= '0';
4390 		else if (isalpha(c))
4391 			c -= isupper(c) ? 'A' - 10 : 'a' - 10;
4392 		else
4393 			break;
4394 		if (c >= 16)
4395 			break;
4396 		if ((i & 1) == 0)
4397 			buf[i / 2] |= (c << 4);
4398 		else
4399 			buf[i / 2] |= c;
4400 	}
4401 	return ((i + 1) / 2);
4402 }
4403 
4404 /*
4405  * LUN allocation.
4406  *
4407  * Requirements:
4408  * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4409  *   wants us to allocate the LUN and he can block.
4410  * - ctl_softc is always set
4411  * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4412  *
4413  * Returns 0 for success, non-zero (errno) for failure.
4414  */
4415 static int
4416 ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4417 	      struct ctl_be_lun *const be_lun, struct ctl_id target_id)
4418 {
4419 	struct ctl_lun *nlun, *lun;
4420 	struct ctl_port *port;
4421 	struct scsi_vpd_id_descriptor *desc;
4422 	struct scsi_vpd_id_t10 *t10id;
4423 	const char *eui, *naa, *scsiname, *vendor, *value;
4424 	int lun_number, i, lun_malloced;
4425 	int devidlen, idlen1, idlen2 = 0, len;
4426 
4427 	if (be_lun == NULL)
4428 		return (EINVAL);
4429 
4430 	/*
4431 	 * We currently only support Direct Access or Processor LUN types.
4432 	 */
4433 	switch (be_lun->lun_type) {
4434 	case T_DIRECT:
4435 		break;
4436 	case T_PROCESSOR:
4437 		break;
4438 	case T_SEQUENTIAL:
4439 	case T_CHANGER:
4440 	default:
4441 		be_lun->lun_config_status(be_lun->be_lun,
4442 					  CTL_LUN_CONFIG_FAILURE);
4443 		break;
4444 	}
4445 	if (ctl_lun == NULL) {
4446 		lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4447 		lun_malloced = 1;
4448 	} else {
4449 		lun_malloced = 0;
4450 		lun = ctl_lun;
4451 	}
4452 
4453 	memset(lun, 0, sizeof(*lun));
4454 	if (lun_malloced)
4455 		lun->flags = CTL_LUN_MALLOCED;
4456 
4457 	/* Generate LUN ID. */
4458 	devidlen = max(CTL_DEVID_MIN_LEN,
4459 	    strnlen(be_lun->device_id, CTL_DEVID_LEN));
4460 	idlen1 = sizeof(*t10id) + devidlen;
4461 	len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4462 	scsiname = ctl_get_opt(&be_lun->options, "scsiname");
4463 	if (scsiname != NULL) {
4464 		idlen2 = roundup2(strlen(scsiname) + 1, 4);
4465 		len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4466 	}
4467 	eui = ctl_get_opt(&be_lun->options, "eui");
4468 	if (eui != NULL) {
4469 		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4470 	}
4471 	naa = ctl_get_opt(&be_lun->options, "naa");
4472 	if (naa != NULL) {
4473 		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4474 	}
4475 	lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4476 	    M_CTL, M_WAITOK | M_ZERO);
4477 	desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4478 	desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4479 	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4480 	desc->length = idlen1;
4481 	t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4482 	memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4483 	if ((vendor = ctl_get_opt(&be_lun->options, "vendor")) == NULL) {
4484 		strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4485 	} else {
4486 		strncpy(t10id->vendor, vendor,
4487 		    min(sizeof(t10id->vendor), strlen(vendor)));
4488 	}
4489 	strncpy((char *)t10id->vendor_spec_id,
4490 	    (char *)be_lun->device_id, devidlen);
4491 	if (scsiname != NULL) {
4492 		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4493 		    desc->length);
4494 		desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4495 		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4496 		    SVPD_ID_TYPE_SCSI_NAME;
4497 		desc->length = idlen2;
4498 		strlcpy(desc->identifier, scsiname, idlen2);
4499 	}
4500 	if (eui != NULL) {
4501 		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4502 		    desc->length);
4503 		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4504 		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4505 		    SVPD_ID_TYPE_EUI64;
4506 		desc->length = hex2bin(eui, desc->identifier, 16);
4507 		desc->length = desc->length > 12 ? 16 :
4508 		    (desc->length > 8 ? 12 : 8);
4509 		len -= 16 - desc->length;
4510 	}
4511 	if (naa != NULL) {
4512 		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4513 		    desc->length);
4514 		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4515 		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4516 		    SVPD_ID_TYPE_NAA;
4517 		desc->length = hex2bin(naa, desc->identifier, 16);
4518 		desc->length = desc->length > 8 ? 16 : 8;
4519 		len -= 16 - desc->length;
4520 	}
4521 	lun->lun_devid->len = len;
4522 
4523 	mtx_lock(&ctl_softc->ctl_lock);
4524 	/*
4525 	 * See if the caller requested a particular LUN number.  If so, see
4526 	 * if it is available.  Otherwise, allocate the first available LUN.
4527 	 */
4528 	if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4529 		if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4530 		 || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4531 			mtx_unlock(&ctl_softc->ctl_lock);
4532 			if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4533 				printf("ctl: requested LUN ID %d is higher "
4534 				       "than CTL_MAX_LUNS - 1 (%d)\n",
4535 				       be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4536 			} else {
4537 				/*
4538 				 * XXX KDM return an error, or just assign
4539 				 * another LUN ID in this case??
4540 				 */
4541 				printf("ctl: requested LUN ID %d is already "
4542 				       "in use\n", be_lun->req_lun_id);
4543 			}
4544 			if (lun->flags & CTL_LUN_MALLOCED)
4545 				free(lun, M_CTL);
4546 			be_lun->lun_config_status(be_lun->be_lun,
4547 						  CTL_LUN_CONFIG_FAILURE);
4548 			return (ENOSPC);
4549 		}
4550 		lun_number = be_lun->req_lun_id;
4551 	} else {
4552 		lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, CTL_MAX_LUNS);
4553 		if (lun_number == -1) {
4554 			mtx_unlock(&ctl_softc->ctl_lock);
4555 			printf("ctl: can't allocate LUN on target %ju, out of "
4556 			       "LUNs\n", (uintmax_t)target_id.id);
4557 			if (lun->flags & CTL_LUN_MALLOCED)
4558 				free(lun, M_CTL);
4559 			be_lun->lun_config_status(be_lun->be_lun,
4560 						  CTL_LUN_CONFIG_FAILURE);
4561 			return (ENOSPC);
4562 		}
4563 	}
4564 	ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4565 
4566 	mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4567 	lun->target = target_id;
4568 	lun->lun = lun_number;
4569 	lun->be_lun = be_lun;
4570 	/*
4571 	 * The processor LUN is always enabled.  Disk LUNs come on line
4572 	 * disabled, and must be enabled by the backend.
4573 	 */
4574 	lun->flags |= CTL_LUN_DISABLED;
4575 	lun->backend = be_lun->be;
4576 	be_lun->ctl_lun = lun;
4577 	be_lun->lun_id = lun_number;
4578 	atomic_add_int(&be_lun->be->num_luns, 1);
4579 	if (be_lun->flags & CTL_LUN_FLAG_OFFLINE)
4580 		lun->flags |= CTL_LUN_OFFLINE;
4581 
4582 	if (be_lun->flags & CTL_LUN_FLAG_POWERED_OFF)
4583 		lun->flags |= CTL_LUN_STOPPED;
4584 
4585 	if (be_lun->flags & CTL_LUN_FLAG_INOPERABLE)
4586 		lun->flags |= CTL_LUN_INOPERABLE;
4587 
4588 	if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4589 		lun->flags |= CTL_LUN_PRIMARY_SC;
4590 
4591 	value = ctl_get_opt(&be_lun->options, "readonly");
4592 	if (value != NULL && strcmp(value, "on") == 0)
4593 		lun->flags |= CTL_LUN_READONLY;
4594 
4595 	lun->serseq = CTL_LUN_SERSEQ_OFF;
4596 	if (be_lun->flags & CTL_LUN_FLAG_SERSEQ_READ)
4597 		lun->serseq = CTL_LUN_SERSEQ_READ;
4598 	value = ctl_get_opt(&be_lun->options, "serseq");
4599 	if (value != NULL && strcmp(value, "on") == 0)
4600 		lun->serseq = CTL_LUN_SERSEQ_ON;
4601 	else if (value != NULL && strcmp(value, "read") == 0)
4602 		lun->serseq = CTL_LUN_SERSEQ_READ;
4603 	else if (value != NULL && strcmp(value, "off") == 0)
4604 		lun->serseq = CTL_LUN_SERSEQ_OFF;
4605 
4606 	lun->ctl_softc = ctl_softc;
4607 	TAILQ_INIT(&lun->ooa_queue);
4608 	TAILQ_INIT(&lun->blocked_queue);
4609 	STAILQ_INIT(&lun->error_list);
4610 	ctl_tpc_lun_init(lun);
4611 
4612 	/*
4613 	 * Initialize the mode and log page index.
4614 	 */
4615 	ctl_init_page_index(lun);
4616 	ctl_init_log_page_index(lun);
4617 
4618 	/*
4619 	 * Now, before we insert this lun on the lun list, set the lun
4620 	 * inventory changed UA for all other luns.
4621 	 */
4622 	STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4623 		mtx_lock(&nlun->lun_lock);
4624 		ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4625 		mtx_unlock(&nlun->lun_lock);
4626 	}
4627 
4628 	STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4629 
4630 	ctl_softc->ctl_luns[lun_number] = lun;
4631 
4632 	ctl_softc->num_luns++;
4633 
4634 	/* Setup statistics gathering */
4635 	lun->stats.device_type = be_lun->lun_type;
4636 	lun->stats.lun_number = lun_number;
4637 	if (lun->stats.device_type == T_DIRECT)
4638 		lun->stats.blocksize = be_lun->blocksize;
4639 	else
4640 		lun->stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4641 	for (i = 0;i < CTL_MAX_PORTS;i++)
4642 		lun->stats.ports[i].targ_port = i;
4643 
4644 	mtx_unlock(&ctl_softc->ctl_lock);
4645 
4646 	lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4647 
4648 	/*
4649 	 * Run through each registered FETD and bring it online if it isn't
4650 	 * already.  Enable the target ID if it hasn't been enabled, and
4651 	 * enable this particular LUN.
4652 	 */
4653 	STAILQ_FOREACH(port, &ctl_softc->port_list, links) {
4654 		int retval;
4655 
4656 		retval = port->lun_enable(port->targ_lun_arg, target_id,lun_number);
4657 		if (retval != 0) {
4658 			printf("ctl_alloc_lun: FETD %s port %d returned error "
4659 			       "%d for lun_enable on target %ju lun %d\n",
4660 			       port->port_name, port->targ_port, retval,
4661 			       (uintmax_t)target_id.id, lun_number);
4662 		} else
4663 			port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4664 	}
4665 	return (0);
4666 }
4667 
4668 /*
4669  * Delete a LUN.
4670  * Assumptions:
4671  * - LUN has already been marked invalid and any pending I/O has been taken
4672  *   care of.
4673  */
4674 static int
4675 ctl_free_lun(struct ctl_lun *lun)
4676 {
4677 	struct ctl_softc *softc;
4678 #if 0
4679 	struct ctl_port *port;
4680 #endif
4681 	struct ctl_lun *nlun;
4682 	int i;
4683 
4684 	softc = lun->ctl_softc;
4685 
4686 	mtx_assert(&softc->ctl_lock, MA_OWNED);
4687 
4688 	STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4689 
4690 	ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4691 
4692 	softc->ctl_luns[lun->lun] = NULL;
4693 
4694 	if (!TAILQ_EMPTY(&lun->ooa_queue))
4695 		panic("Freeing a LUN %p with outstanding I/O!!\n", lun);
4696 
4697 	softc->num_luns--;
4698 
4699 	/*
4700 	 * XXX KDM this scheme only works for a single target/multiple LUN
4701 	 * setup.  It needs to be revamped for a multiple target scheme.
4702 	 *
4703 	 * XXX KDM this results in port->lun_disable() getting called twice,
4704 	 * once when ctl_disable_lun() is called, and a second time here.
4705 	 * We really need to re-think the LUN disable semantics.  There
4706 	 * should probably be several steps/levels to LUN removal:
4707 	 *  - disable
4708 	 *  - invalidate
4709 	 *  - free
4710  	 *
4711 	 * Right now we only have a disable method when communicating to
4712 	 * the front end ports, at least for individual LUNs.
4713 	 */
4714 #if 0
4715 	STAILQ_FOREACH(port, &softc->port_list, links) {
4716 		int retval;
4717 
4718 		retval = port->lun_disable(port->targ_lun_arg, lun->target,
4719 					 lun->lun);
4720 		if (retval != 0) {
4721 			printf("ctl_free_lun: FETD %s port %d returned error "
4722 			       "%d for lun_disable on target %ju lun %jd\n",
4723 			       port->port_name, port->targ_port, retval,
4724 			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4725 		}
4726 
4727 		if (STAILQ_FIRST(&softc->lun_list) == NULL) {
4728 			port->status &= ~CTL_PORT_STATUS_LUN_ONLINE;
4729 
4730 			retval = port->targ_disable(port->targ_lun_arg,lun->target);
4731 			if (retval != 0) {
4732 				printf("ctl_free_lun: FETD %s port %d "
4733 				       "returned error %d for targ_disable on "
4734 				       "target %ju\n", port->port_name,
4735 				       port->targ_port, retval,
4736 				       (uintmax_t)lun->target.id);
4737 			} else
4738 				port->status &= ~CTL_PORT_STATUS_TARG_ONLINE;
4739 
4740 			if ((port->status & CTL_PORT_STATUS_TARG_ONLINE) != 0)
4741 				continue;
4742 
4743 #if 0
4744 			port->port_offline(port->onoff_arg);
4745 			port->status &= ~CTL_PORT_STATUS_ONLINE;
4746 #endif
4747 		}
4748 	}
4749 #endif
4750 
4751 	/*
4752 	 * Tell the backend to free resources, if this LUN has a backend.
4753 	 */
4754 	atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4755 	lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4756 
4757 	ctl_tpc_lun_shutdown(lun);
4758 	mtx_destroy(&lun->lun_lock);
4759 	free(lun->lun_devid, M_CTL);
4760 	for (i = 0; i < CTL_MAX_PORTS; i++)
4761 		free(lun->pending_ua[i], M_CTL);
4762 	for (i = 0; i < 2 * CTL_MAX_PORTS; i++)
4763 		free(lun->pr_keys[i], M_CTL);
4764 	free(lun->write_buffer, M_CTL);
4765 	if (lun->flags & CTL_LUN_MALLOCED)
4766 		free(lun, M_CTL);
4767 
4768 	STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4769 		mtx_lock(&nlun->lun_lock);
4770 		ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4771 		mtx_unlock(&nlun->lun_lock);
4772 	}
4773 
4774 	return (0);
4775 }
4776 
4777 static void
4778 ctl_create_lun(struct ctl_be_lun *be_lun)
4779 {
4780 	struct ctl_softc *ctl_softc;
4781 
4782 	ctl_softc = control_softc;
4783 
4784 	/*
4785 	 * ctl_alloc_lun() should handle all potential failure cases.
4786 	 */
4787 	ctl_alloc_lun(ctl_softc, NULL, be_lun, ctl_softc->target);
4788 }
4789 
4790 int
4791 ctl_add_lun(struct ctl_be_lun *be_lun)
4792 {
4793 	struct ctl_softc *ctl_softc = control_softc;
4794 
4795 	mtx_lock(&ctl_softc->ctl_lock);
4796 	STAILQ_INSERT_TAIL(&ctl_softc->pending_lun_queue, be_lun, links);
4797 	mtx_unlock(&ctl_softc->ctl_lock);
4798 	wakeup(&ctl_softc->pending_lun_queue);
4799 
4800 	return (0);
4801 }
4802 
4803 int
4804 ctl_enable_lun(struct ctl_be_lun *be_lun)
4805 {
4806 	struct ctl_softc *ctl_softc;
4807 	struct ctl_port *port, *nport;
4808 	struct ctl_lun *lun;
4809 	int retval;
4810 
4811 	ctl_softc = control_softc;
4812 
4813 	lun = (struct ctl_lun *)be_lun->ctl_lun;
4814 
4815 	mtx_lock(&ctl_softc->ctl_lock);
4816 	mtx_lock(&lun->lun_lock);
4817 	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4818 		/*
4819 		 * eh?  Why did we get called if the LUN is already
4820 		 * enabled?
4821 		 */
4822 		mtx_unlock(&lun->lun_lock);
4823 		mtx_unlock(&ctl_softc->ctl_lock);
4824 		return (0);
4825 	}
4826 	lun->flags &= ~CTL_LUN_DISABLED;
4827 	mtx_unlock(&lun->lun_lock);
4828 
4829 	for (port = STAILQ_FIRST(&ctl_softc->port_list); port != NULL; port = nport) {
4830 		nport = STAILQ_NEXT(port, links);
4831 
4832 		/*
4833 		 * Drop the lock while we call the FETD's enable routine.
4834 		 * This can lead to a callback into CTL (at least in the
4835 		 * case of the internal initiator frontend.
4836 		 */
4837 		mtx_unlock(&ctl_softc->ctl_lock);
4838 		retval = port->lun_enable(port->targ_lun_arg, lun->target,lun->lun);
4839 		mtx_lock(&ctl_softc->ctl_lock);
4840 		if (retval != 0) {
4841 			printf("%s: FETD %s port %d returned error "
4842 			       "%d for lun_enable on target %ju lun %jd\n",
4843 			       __func__, port->port_name, port->targ_port, retval,
4844 			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4845 		}
4846 #if 0
4847 		 else {
4848             /* NOTE:  TODO:  why does lun enable affect port status? */
4849 			port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4850 		}
4851 #endif
4852 	}
4853 
4854 	mtx_unlock(&ctl_softc->ctl_lock);
4855 
4856 	return (0);
4857 }
4858 
4859 int
4860 ctl_disable_lun(struct ctl_be_lun *be_lun)
4861 {
4862 	struct ctl_softc *ctl_softc;
4863 	struct ctl_port *port;
4864 	struct ctl_lun *lun;
4865 	int retval;
4866 
4867 	ctl_softc = control_softc;
4868 
4869 	lun = (struct ctl_lun *)be_lun->ctl_lun;
4870 
4871 	mtx_lock(&ctl_softc->ctl_lock);
4872 	mtx_lock(&lun->lun_lock);
4873 	if (lun->flags & CTL_LUN_DISABLED) {
4874 		mtx_unlock(&lun->lun_lock);
4875 		mtx_unlock(&ctl_softc->ctl_lock);
4876 		return (0);
4877 	}
4878 	lun->flags |= CTL_LUN_DISABLED;
4879 	mtx_unlock(&lun->lun_lock);
4880 
4881 	STAILQ_FOREACH(port, &ctl_softc->port_list, links) {
4882 		mtx_unlock(&ctl_softc->ctl_lock);
4883 		/*
4884 		 * Drop the lock before we call the frontend's disable
4885 		 * routine, to avoid lock order reversals.
4886 		 *
4887 		 * XXX KDM what happens if the frontend list changes while
4888 		 * we're traversing it?  It's unlikely, but should be handled.
4889 		 */
4890 		retval = port->lun_disable(port->targ_lun_arg, lun->target,
4891 					 lun->lun);
4892 		mtx_lock(&ctl_softc->ctl_lock);
4893 		if (retval != 0) {
4894 			printf("ctl_alloc_lun: FETD %s port %d returned error "
4895 			       "%d for lun_disable on target %ju lun %jd\n",
4896 			       port->port_name, port->targ_port, retval,
4897 			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4898 		}
4899 	}
4900 
4901 	mtx_unlock(&ctl_softc->ctl_lock);
4902 
4903 	return (0);
4904 }
4905 
4906 int
4907 ctl_start_lun(struct ctl_be_lun *be_lun)
4908 {
4909 	struct ctl_softc *ctl_softc;
4910 	struct ctl_lun *lun;
4911 
4912 	ctl_softc = control_softc;
4913 
4914 	lun = (struct ctl_lun *)be_lun->ctl_lun;
4915 
4916 	mtx_lock(&lun->lun_lock);
4917 	lun->flags &= ~CTL_LUN_STOPPED;
4918 	mtx_unlock(&lun->lun_lock);
4919 
4920 	return (0);
4921 }
4922 
4923 int
4924 ctl_stop_lun(struct ctl_be_lun *be_lun)
4925 {
4926 	struct ctl_softc *ctl_softc;
4927 	struct ctl_lun *lun;
4928 
4929 	ctl_softc = control_softc;
4930 
4931 	lun = (struct ctl_lun *)be_lun->ctl_lun;
4932 
4933 	mtx_lock(&lun->lun_lock);
4934 	lun->flags |= CTL_LUN_STOPPED;
4935 	mtx_unlock(&lun->lun_lock);
4936 
4937 	return (0);
4938 }
4939 
4940 int
4941 ctl_lun_offline(struct ctl_be_lun *be_lun)
4942 {
4943 	struct ctl_softc *ctl_softc;
4944 	struct ctl_lun *lun;
4945 
4946 	ctl_softc = control_softc;
4947 
4948 	lun = (struct ctl_lun *)be_lun->ctl_lun;
4949 
4950 	mtx_lock(&lun->lun_lock);
4951 	lun->flags |= CTL_LUN_OFFLINE;
4952 	mtx_unlock(&lun->lun_lock);
4953 
4954 	return (0);
4955 }
4956 
4957 int
4958 ctl_lun_online(struct ctl_be_lun *be_lun)
4959 {
4960 	struct ctl_softc *ctl_softc;
4961 	struct ctl_lun *lun;
4962 
4963 	ctl_softc = control_softc;
4964 
4965 	lun = (struct ctl_lun *)be_lun->ctl_lun;
4966 
4967 	mtx_lock(&lun->lun_lock);
4968 	lun->flags &= ~CTL_LUN_OFFLINE;
4969 	mtx_unlock(&lun->lun_lock);
4970 
4971 	return (0);
4972 }
4973 
4974 int
4975 ctl_invalidate_lun(struct ctl_be_lun *be_lun)
4976 {
4977 	struct ctl_softc *ctl_softc;
4978 	struct ctl_lun *lun;
4979 
4980 	ctl_softc = control_softc;
4981 
4982 	lun = (struct ctl_lun *)be_lun->ctl_lun;
4983 
4984 	mtx_lock(&lun->lun_lock);
4985 
4986 	/*
4987 	 * The LUN needs to be disabled before it can be marked invalid.
4988 	 */
4989 	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4990 		mtx_unlock(&lun->lun_lock);
4991 		return (-1);
4992 	}
4993 	/*
4994 	 * Mark the LUN invalid.
4995 	 */
4996 	lun->flags |= CTL_LUN_INVALID;
4997 
4998 	/*
4999 	 * If there is nothing in the OOA queue, go ahead and free the LUN.
5000 	 * If we have something in the OOA queue, we'll free it when the
5001 	 * last I/O completes.
5002 	 */
5003 	if (TAILQ_EMPTY(&lun->ooa_queue)) {
5004 		mtx_unlock(&lun->lun_lock);
5005 		mtx_lock(&ctl_softc->ctl_lock);
5006 		ctl_free_lun(lun);
5007 		mtx_unlock(&ctl_softc->ctl_lock);
5008 	} else
5009 		mtx_unlock(&lun->lun_lock);
5010 
5011 	return (0);
5012 }
5013 
5014 int
5015 ctl_lun_inoperable(struct ctl_be_lun *be_lun)
5016 {
5017 	struct ctl_softc *ctl_softc;
5018 	struct ctl_lun *lun;
5019 
5020 	ctl_softc = control_softc;
5021 	lun = (struct ctl_lun *)be_lun->ctl_lun;
5022 
5023 	mtx_lock(&lun->lun_lock);
5024 	lun->flags |= CTL_LUN_INOPERABLE;
5025 	mtx_unlock(&lun->lun_lock);
5026 
5027 	return (0);
5028 }
5029 
5030 int
5031 ctl_lun_operable(struct ctl_be_lun *be_lun)
5032 {
5033 	struct ctl_softc *ctl_softc;
5034 	struct ctl_lun *lun;
5035 
5036 	ctl_softc = control_softc;
5037 	lun = (struct ctl_lun *)be_lun->ctl_lun;
5038 
5039 	mtx_lock(&lun->lun_lock);
5040 	lun->flags &= ~CTL_LUN_INOPERABLE;
5041 	mtx_unlock(&lun->lun_lock);
5042 
5043 	return (0);
5044 }
5045 
5046 void
5047 ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
5048 {
5049 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5050 
5051 	mtx_lock(&lun->lun_lock);
5052 	ctl_est_ua_all(lun, -1, CTL_UA_CAPACITY_CHANGED);
5053 	mtx_unlock(&lun->lun_lock);
5054 }
5055 
5056 /*
5057  * Backend "memory move is complete" callback for requests that never
5058  * make it down to say RAIDCore's configuration code.
5059  */
5060 int
5061 ctl_config_move_done(union ctl_io *io)
5062 {
5063 	int retval;
5064 
5065 	CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
5066 	KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
5067 	    ("Config I/O type isn't CTL_IO_SCSI (%d)!", io->io_hdr.io_type));
5068 
5069 	if ((io->io_hdr.port_status != 0) &&
5070 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5071 	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5072 		/*
5073 		 * For hardware error sense keys, the sense key
5074 		 * specific value is defined to be a retry count,
5075 		 * but we use it to pass back an internal FETD
5076 		 * error code.  XXX KDM  Hopefully the FETD is only
5077 		 * using 16 bits for an error code, since that's
5078 		 * all the space we have in the sks field.
5079 		 */
5080 		ctl_set_internal_failure(&io->scsiio,
5081 					 /*sks_valid*/ 1,
5082 					 /*retry_count*/
5083 					 io->io_hdr.port_status);
5084 	}
5085 
5086 	if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN) ||
5087 	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5088 	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) ||
5089 	    ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
5090 		/*
5091 		 * XXX KDM just assuming a single pointer here, and not a
5092 		 * S/G list.  If we start using S/G lists for config data,
5093 		 * we'll need to know how to clean them up here as well.
5094 		 */
5095 		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5096 			free(io->scsiio.kern_data_ptr, M_CTL);
5097 		ctl_done(io);
5098 		retval = CTL_RETVAL_COMPLETE;
5099 	} else {
5100 		/*
5101 		 * XXX KDM now we need to continue data movement.  Some
5102 		 * options:
5103 		 * - call ctl_scsiio() again?  We don't do this for data
5104 		 *   writes, because for those at least we know ahead of
5105 		 *   time where the write will go and how long it is.  For
5106 		 *   config writes, though, that information is largely
5107 		 *   contained within the write itself, thus we need to
5108 		 *   parse out the data again.
5109 		 *
5110 		 * - Call some other function once the data is in?
5111 		 */
5112 		if (ctl_debug & CTL_DEBUG_CDB_DATA)
5113 			ctl_data_print(io);
5114 
5115 		/*
5116 		 * XXX KDM call ctl_scsiio() again for now, and check flag
5117 		 * bits to see whether we're allocated or not.
5118 		 */
5119 		retval = ctl_scsiio(&io->scsiio);
5120 	}
5121 	return (retval);
5122 }
5123 
5124 /*
5125  * This gets called by a backend driver when it is done with a
5126  * data_submit method.
5127  */
5128 void
5129 ctl_data_submit_done(union ctl_io *io)
5130 {
5131 	/*
5132 	 * If the IO_CONT flag is set, we need to call the supplied
5133 	 * function to continue processing the I/O, instead of completing
5134 	 * the I/O just yet.
5135 	 *
5136 	 * If there is an error, though, we don't want to keep processing.
5137 	 * Instead, just send status back to the initiator.
5138 	 */
5139 	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5140 	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5141 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5142 	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5143 		io->scsiio.io_cont(io);
5144 		return;
5145 	}
5146 	ctl_done(io);
5147 }
5148 
5149 /*
5150  * This gets called by a backend driver when it is done with a
5151  * configuration write.
5152  */
5153 void
5154 ctl_config_write_done(union ctl_io *io)
5155 {
5156 	uint8_t *buf;
5157 
5158 	/*
5159 	 * If the IO_CONT flag is set, we need to call the supplied
5160 	 * function to continue processing the I/O, instead of completing
5161 	 * the I/O just yet.
5162 	 *
5163 	 * If there is an error, though, we don't want to keep processing.
5164 	 * Instead, just send status back to the initiator.
5165 	 */
5166 	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5167 	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5168 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5169 	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5170 		io->scsiio.io_cont(io);
5171 		return;
5172 	}
5173 	/*
5174 	 * Since a configuration write can be done for commands that actually
5175 	 * have data allocated, like write buffer, and commands that have
5176 	 * no data, like start/stop unit, we need to check here.
5177 	 */
5178 	if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5179 		buf = io->scsiio.kern_data_ptr;
5180 	else
5181 		buf = NULL;
5182 	ctl_done(io);
5183 	if (buf)
5184 		free(buf, M_CTL);
5185 }
5186 
5187 void
5188 ctl_config_read_done(union ctl_io *io)
5189 {
5190 	uint8_t *buf;
5191 
5192 	/*
5193 	 * If there is some error -- we are done, skip data transfer.
5194 	 */
5195 	if ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0 ||
5196 	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5197 	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)) {
5198 		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5199 			buf = io->scsiio.kern_data_ptr;
5200 		else
5201 			buf = NULL;
5202 		ctl_done(io);
5203 		if (buf)
5204 			free(buf, M_CTL);
5205 		return;
5206 	}
5207 
5208 	/*
5209 	 * If the IO_CONT flag is set, we need to call the supplied
5210 	 * function to continue processing the I/O, instead of completing
5211 	 * the I/O just yet.
5212 	 */
5213 	if (io->io_hdr.flags & CTL_FLAG_IO_CONT) {
5214 		io->scsiio.io_cont(io);
5215 		return;
5216 	}
5217 
5218 	ctl_datamove(io);
5219 }
5220 
5221 /*
5222  * SCSI release command.
5223  */
5224 int
5225 ctl_scsi_release(struct ctl_scsiio *ctsio)
5226 {
5227 	int length, longid, thirdparty_id, resv_id;
5228 	struct ctl_softc *ctl_softc;
5229 	struct ctl_lun *lun;
5230 	uint32_t residx;
5231 
5232 	length = 0;
5233 	resv_id = 0;
5234 
5235 	CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5236 
5237 	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5238 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5239 	ctl_softc = control_softc;
5240 
5241 	switch (ctsio->cdb[0]) {
5242 	case RELEASE_10: {
5243 		struct scsi_release_10 *cdb;
5244 
5245 		cdb = (struct scsi_release_10 *)ctsio->cdb;
5246 
5247 		if (cdb->byte2 & SR10_LONGID)
5248 			longid = 1;
5249 		else
5250 			thirdparty_id = cdb->thirdparty_id;
5251 
5252 		resv_id = cdb->resv_id;
5253 		length = scsi_2btoul(cdb->length);
5254 		break;
5255 	}
5256 	}
5257 
5258 
5259 	/*
5260 	 * XXX KDM right now, we only support LUN reservation.  We don't
5261 	 * support 3rd party reservations, or extent reservations, which
5262 	 * might actually need the parameter list.  If we've gotten this
5263 	 * far, we've got a LUN reservation.  Anything else got kicked out
5264 	 * above.  So, according to SPC, ignore the length.
5265 	 */
5266 	length = 0;
5267 
5268 	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5269 	 && (length > 0)) {
5270 		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5271 		ctsio->kern_data_len = length;
5272 		ctsio->kern_total_len = length;
5273 		ctsio->kern_data_resid = 0;
5274 		ctsio->kern_rel_offset = 0;
5275 		ctsio->kern_sg_entries = 0;
5276 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5277 		ctsio->be_move_done = ctl_config_move_done;
5278 		ctl_datamove((union ctl_io *)ctsio);
5279 
5280 		return (CTL_RETVAL_COMPLETE);
5281 	}
5282 
5283 	if (length > 0)
5284 		thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5285 
5286 	mtx_lock(&lun->lun_lock);
5287 
5288 	/*
5289 	 * According to SPC, it is not an error for an intiator to attempt
5290 	 * to release a reservation on a LUN that isn't reserved, or that
5291 	 * is reserved by another initiator.  The reservation can only be
5292 	 * released, though, by the initiator who made it or by one of
5293 	 * several reset type events.
5294 	 */
5295 	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
5296 			lun->flags &= ~CTL_LUN_RESERVED;
5297 
5298 	mtx_unlock(&lun->lun_lock);
5299 
5300 	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5301 		free(ctsio->kern_data_ptr, M_CTL);
5302 		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5303 	}
5304 
5305 	ctl_set_success(ctsio);
5306 	ctl_done((union ctl_io *)ctsio);
5307 	return (CTL_RETVAL_COMPLETE);
5308 }
5309 
5310 int
5311 ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5312 {
5313 	int extent, thirdparty, longid;
5314 	int resv_id, length;
5315 	uint64_t thirdparty_id;
5316 	struct ctl_softc *ctl_softc;
5317 	struct ctl_lun *lun;
5318 	uint32_t residx;
5319 
5320 	extent = 0;
5321 	thirdparty = 0;
5322 	longid = 0;
5323 	resv_id = 0;
5324 	length = 0;
5325 	thirdparty_id = 0;
5326 
5327 	CTL_DEBUG_PRINT(("ctl_reserve\n"));
5328 
5329 	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5330 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5331 	ctl_softc = control_softc;
5332 
5333 	switch (ctsio->cdb[0]) {
5334 	case RESERVE_10: {
5335 		struct scsi_reserve_10 *cdb;
5336 
5337 		cdb = (struct scsi_reserve_10 *)ctsio->cdb;
5338 
5339 		if (cdb->byte2 & SR10_LONGID)
5340 			longid = 1;
5341 		else
5342 			thirdparty_id = cdb->thirdparty_id;
5343 
5344 		resv_id = cdb->resv_id;
5345 		length = scsi_2btoul(cdb->length);
5346 		break;
5347 	}
5348 	}
5349 
5350 	/*
5351 	 * XXX KDM right now, we only support LUN reservation.  We don't
5352 	 * support 3rd party reservations, or extent reservations, which
5353 	 * might actually need the parameter list.  If we've gotten this
5354 	 * far, we've got a LUN reservation.  Anything else got kicked out
5355 	 * above.  So, according to SPC, ignore the length.
5356 	 */
5357 	length = 0;
5358 
5359 	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5360 	 && (length > 0)) {
5361 		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5362 		ctsio->kern_data_len = length;
5363 		ctsio->kern_total_len = length;
5364 		ctsio->kern_data_resid = 0;
5365 		ctsio->kern_rel_offset = 0;
5366 		ctsio->kern_sg_entries = 0;
5367 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5368 		ctsio->be_move_done = ctl_config_move_done;
5369 		ctl_datamove((union ctl_io *)ctsio);
5370 
5371 		return (CTL_RETVAL_COMPLETE);
5372 	}
5373 
5374 	if (length > 0)
5375 		thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5376 
5377 	mtx_lock(&lun->lun_lock);
5378 	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
5379 		ctl_set_reservation_conflict(ctsio);
5380 		goto bailout;
5381 	}
5382 
5383 	lun->flags |= CTL_LUN_RESERVED;
5384 	lun->res_idx = residx;
5385 
5386 	ctl_set_success(ctsio);
5387 
5388 bailout:
5389 	mtx_unlock(&lun->lun_lock);
5390 
5391 	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5392 		free(ctsio->kern_data_ptr, M_CTL);
5393 		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5394 	}
5395 
5396 	ctl_done((union ctl_io *)ctsio);
5397 	return (CTL_RETVAL_COMPLETE);
5398 }
5399 
5400 int
5401 ctl_start_stop(struct ctl_scsiio *ctsio)
5402 {
5403 	struct scsi_start_stop_unit *cdb;
5404 	struct ctl_lun *lun;
5405 	struct ctl_softc *ctl_softc;
5406 	int retval;
5407 
5408 	CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5409 
5410 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5411 	ctl_softc = control_softc;
5412 	retval = 0;
5413 
5414 	cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5415 
5416 	/*
5417 	 * XXX KDM
5418 	 * We don't support the immediate bit on a stop unit.  In order to
5419 	 * do that, we would need to code up a way to know that a stop is
5420 	 * pending, and hold off any new commands until it completes, one
5421 	 * way or another.  Then we could accept or reject those commands
5422 	 * depending on its status.  We would almost need to do the reverse
5423 	 * of what we do below for an immediate start -- return the copy of
5424 	 * the ctl_io to the FETD with status to send to the host (and to
5425 	 * free the copy!) and then free the original I/O once the stop
5426 	 * actually completes.  That way, the OOA queue mechanism can work
5427 	 * to block commands that shouldn't proceed.  Another alternative
5428 	 * would be to put the copy in the queue in place of the original,
5429 	 * and return the original back to the caller.  That could be
5430 	 * slightly safer..
5431 	 */
5432 	if ((cdb->byte2 & SSS_IMMED)
5433 	 && ((cdb->how & SSS_START) == 0)) {
5434 		ctl_set_invalid_field(ctsio,
5435 				      /*sks_valid*/ 1,
5436 				      /*command*/ 1,
5437 				      /*field*/ 1,
5438 				      /*bit_valid*/ 1,
5439 				      /*bit*/ 0);
5440 		ctl_done((union ctl_io *)ctsio);
5441 		return (CTL_RETVAL_COMPLETE);
5442 	}
5443 
5444 	if ((lun->flags & CTL_LUN_PR_RESERVED)
5445 	 && ((cdb->how & SSS_START)==0)) {
5446 		uint32_t residx;
5447 
5448 		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5449 		if (ctl_get_prkey(lun, residx) == 0
5450 		 || (lun->pr_res_idx!=residx && lun->res_type < 4)) {
5451 
5452 			ctl_set_reservation_conflict(ctsio);
5453 			ctl_done((union ctl_io *)ctsio);
5454 			return (CTL_RETVAL_COMPLETE);
5455 		}
5456 	}
5457 
5458 	/*
5459 	 * If there is no backend on this device, we can't start or stop
5460 	 * it.  In theory we shouldn't get any start/stop commands in the
5461 	 * first place at this level if the LUN doesn't have a backend.
5462 	 * That should get stopped by the command decode code.
5463 	 */
5464 	if (lun->backend == NULL) {
5465 		ctl_set_invalid_opcode(ctsio);
5466 		ctl_done((union ctl_io *)ctsio);
5467 		return (CTL_RETVAL_COMPLETE);
5468 	}
5469 
5470 	/*
5471 	 * XXX KDM Copan-specific offline behavior.
5472 	 * Figure out a reasonable way to port this?
5473 	 */
5474 #ifdef NEEDTOPORT
5475 	mtx_lock(&lun->lun_lock);
5476 
5477 	if (((cdb->byte2 & SSS_ONOFFLINE) == 0)
5478 	 && (lun->flags & CTL_LUN_OFFLINE)) {
5479 		/*
5480 		 * If the LUN is offline, and the on/offline bit isn't set,
5481 		 * reject the start or stop.  Otherwise, let it through.
5482 		 */
5483 		mtx_unlock(&lun->lun_lock);
5484 		ctl_set_lun_not_ready(ctsio);
5485 		ctl_done((union ctl_io *)ctsio);
5486 	} else {
5487 		mtx_unlock(&lun->lun_lock);
5488 #endif /* NEEDTOPORT */
5489 		/*
5490 		 * This could be a start or a stop when we're online,
5491 		 * or a stop/offline or start/online.  A start or stop when
5492 		 * we're offline is covered in the case above.
5493 		 */
5494 		/*
5495 		 * In the non-immediate case, we send the request to
5496 		 * the backend and return status to the user when
5497 		 * it is done.
5498 		 *
5499 		 * In the immediate case, we allocate a new ctl_io
5500 		 * to hold a copy of the request, and send that to
5501 		 * the backend.  We then set good status on the
5502 		 * user's request and return it immediately.
5503 		 */
5504 		if (cdb->byte2 & SSS_IMMED) {
5505 			union ctl_io *new_io;
5506 
5507 			new_io = ctl_alloc_io(ctsio->io_hdr.pool);
5508 			ctl_copy_io((union ctl_io *)ctsio, new_io);
5509 			retval = lun->backend->config_write(new_io);
5510 			ctl_set_success(ctsio);
5511 			ctl_done((union ctl_io *)ctsio);
5512 		} else {
5513 			retval = lun->backend->config_write(
5514 				(union ctl_io *)ctsio);
5515 		}
5516 #ifdef NEEDTOPORT
5517 	}
5518 #endif
5519 	return (retval);
5520 }
5521 
5522 /*
5523  * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5524  * we don't really do anything with the LBA and length fields if the user
5525  * passes them in.  Instead we'll just flush out the cache for the entire
5526  * LUN.
5527  */
5528 int
5529 ctl_sync_cache(struct ctl_scsiio *ctsio)
5530 {
5531 	struct ctl_lun *lun;
5532 	struct ctl_softc *ctl_softc;
5533 	uint64_t starting_lba;
5534 	uint32_t block_count;
5535 	int retval;
5536 
5537 	CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5538 
5539 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5540 	ctl_softc = control_softc;
5541 	retval = 0;
5542 
5543 	switch (ctsio->cdb[0]) {
5544 	case SYNCHRONIZE_CACHE: {
5545 		struct scsi_sync_cache *cdb;
5546 		cdb = (struct scsi_sync_cache *)ctsio->cdb;
5547 
5548 		starting_lba = scsi_4btoul(cdb->begin_lba);
5549 		block_count = scsi_2btoul(cdb->lb_count);
5550 		break;
5551 	}
5552 	case SYNCHRONIZE_CACHE_16: {
5553 		struct scsi_sync_cache_16 *cdb;
5554 		cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5555 
5556 		starting_lba = scsi_8btou64(cdb->begin_lba);
5557 		block_count = scsi_4btoul(cdb->lb_count);
5558 		break;
5559 	}
5560 	default:
5561 		ctl_set_invalid_opcode(ctsio);
5562 		ctl_done((union ctl_io *)ctsio);
5563 		goto bailout;
5564 		break; /* NOTREACHED */
5565 	}
5566 
5567 	/*
5568 	 * We check the LBA and length, but don't do anything with them.
5569 	 * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5570 	 * get flushed.  This check will just help satisfy anyone who wants
5571 	 * to see an error for an out of range LBA.
5572 	 */
5573 	if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5574 		ctl_set_lba_out_of_range(ctsio);
5575 		ctl_done((union ctl_io *)ctsio);
5576 		goto bailout;
5577 	}
5578 
5579 	/*
5580 	 * If this LUN has no backend, we can't flush the cache anyway.
5581 	 */
5582 	if (lun->backend == NULL) {
5583 		ctl_set_invalid_opcode(ctsio);
5584 		ctl_done((union ctl_io *)ctsio);
5585 		goto bailout;
5586 	}
5587 
5588 	/*
5589 	 * Check to see whether we're configured to send the SYNCHRONIZE
5590 	 * CACHE command directly to the back end.
5591 	 */
5592 	mtx_lock(&lun->lun_lock);
5593 	if ((ctl_softc->flags & CTL_FLAG_REAL_SYNC)
5594 	 && (++(lun->sync_count) >= lun->sync_interval)) {
5595 		lun->sync_count = 0;
5596 		mtx_unlock(&lun->lun_lock);
5597 		retval = lun->backend->config_write((union ctl_io *)ctsio);
5598 	} else {
5599 		mtx_unlock(&lun->lun_lock);
5600 		ctl_set_success(ctsio);
5601 		ctl_done((union ctl_io *)ctsio);
5602 	}
5603 
5604 bailout:
5605 
5606 	return (retval);
5607 }
5608 
5609 int
5610 ctl_format(struct ctl_scsiio *ctsio)
5611 {
5612 	struct scsi_format *cdb;
5613 	struct ctl_lun *lun;
5614 	struct ctl_softc *ctl_softc;
5615 	int length, defect_list_len;
5616 
5617 	CTL_DEBUG_PRINT(("ctl_format\n"));
5618 
5619 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5620 	ctl_softc = control_softc;
5621 
5622 	cdb = (struct scsi_format *)ctsio->cdb;
5623 
5624 	length = 0;
5625 	if (cdb->byte2 & SF_FMTDATA) {
5626 		if (cdb->byte2 & SF_LONGLIST)
5627 			length = sizeof(struct scsi_format_header_long);
5628 		else
5629 			length = sizeof(struct scsi_format_header_short);
5630 	}
5631 
5632 	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5633 	 && (length > 0)) {
5634 		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5635 		ctsio->kern_data_len = length;
5636 		ctsio->kern_total_len = length;
5637 		ctsio->kern_data_resid = 0;
5638 		ctsio->kern_rel_offset = 0;
5639 		ctsio->kern_sg_entries = 0;
5640 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5641 		ctsio->be_move_done = ctl_config_move_done;
5642 		ctl_datamove((union ctl_io *)ctsio);
5643 
5644 		return (CTL_RETVAL_COMPLETE);
5645 	}
5646 
5647 	defect_list_len = 0;
5648 
5649 	if (cdb->byte2 & SF_FMTDATA) {
5650 		if (cdb->byte2 & SF_LONGLIST) {
5651 			struct scsi_format_header_long *header;
5652 
5653 			header = (struct scsi_format_header_long *)
5654 				ctsio->kern_data_ptr;
5655 
5656 			defect_list_len = scsi_4btoul(header->defect_list_len);
5657 			if (defect_list_len != 0) {
5658 				ctl_set_invalid_field(ctsio,
5659 						      /*sks_valid*/ 1,
5660 						      /*command*/ 0,
5661 						      /*field*/ 2,
5662 						      /*bit_valid*/ 0,
5663 						      /*bit*/ 0);
5664 				goto bailout;
5665 			}
5666 		} else {
5667 			struct scsi_format_header_short *header;
5668 
5669 			header = (struct scsi_format_header_short *)
5670 				ctsio->kern_data_ptr;
5671 
5672 			defect_list_len = scsi_2btoul(header->defect_list_len);
5673 			if (defect_list_len != 0) {
5674 				ctl_set_invalid_field(ctsio,
5675 						      /*sks_valid*/ 1,
5676 						      /*command*/ 0,
5677 						      /*field*/ 2,
5678 						      /*bit_valid*/ 0,
5679 						      /*bit*/ 0);
5680 				goto bailout;
5681 			}
5682 		}
5683 	}
5684 
5685 	/*
5686 	 * The format command will clear out the "Medium format corrupted"
5687 	 * status if set by the configuration code.  That status is really
5688 	 * just a way to notify the host that we have lost the media, and
5689 	 * get them to issue a command that will basically make them think
5690 	 * they're blowing away the media.
5691 	 */
5692 	mtx_lock(&lun->lun_lock);
5693 	lun->flags &= ~CTL_LUN_INOPERABLE;
5694 	mtx_unlock(&lun->lun_lock);
5695 
5696 	ctl_set_success(ctsio);
5697 bailout:
5698 
5699 	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5700 		free(ctsio->kern_data_ptr, M_CTL);
5701 		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5702 	}
5703 
5704 	ctl_done((union ctl_io *)ctsio);
5705 	return (CTL_RETVAL_COMPLETE);
5706 }
5707 
5708 int
5709 ctl_read_buffer(struct ctl_scsiio *ctsio)
5710 {
5711 	struct scsi_read_buffer *cdb;
5712 	struct ctl_lun *lun;
5713 	int buffer_offset, len;
5714 	static uint8_t descr[4];
5715 	static uint8_t echo_descr[4] = { 0 };
5716 
5717 	CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5718 
5719 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5720 	cdb = (struct scsi_read_buffer *)ctsio->cdb;
5721 
5722 	if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA &&
5723 	    (cdb->byte2 & RWB_MODE) != RWB_MODE_ECHO_DESCR &&
5724 	    (cdb->byte2 & RWB_MODE) != RWB_MODE_DESCR) {
5725 		ctl_set_invalid_field(ctsio,
5726 				      /*sks_valid*/ 1,
5727 				      /*command*/ 1,
5728 				      /*field*/ 1,
5729 				      /*bit_valid*/ 1,
5730 				      /*bit*/ 4);
5731 		ctl_done((union ctl_io *)ctsio);
5732 		return (CTL_RETVAL_COMPLETE);
5733 	}
5734 
5735 	len = scsi_3btoul(cdb->length);
5736 	buffer_offset = scsi_3btoul(cdb->offset);
5737 
5738 	if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5739 		ctl_set_invalid_field(ctsio,
5740 				      /*sks_valid*/ 1,
5741 				      /*command*/ 1,
5742 				      /*field*/ 6,
5743 				      /*bit_valid*/ 0,
5744 				      /*bit*/ 0);
5745 		ctl_done((union ctl_io *)ctsio);
5746 		return (CTL_RETVAL_COMPLETE);
5747 	}
5748 
5749 	if ((cdb->byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5750 		descr[0] = 0;
5751 		scsi_ulto3b(CTL_WRITE_BUFFER_SIZE, &descr[1]);
5752 		ctsio->kern_data_ptr = descr;
5753 		len = min(len, sizeof(descr));
5754 	} else if ((cdb->byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5755 		ctsio->kern_data_ptr = echo_descr;
5756 		len = min(len, sizeof(echo_descr));
5757 	} else {
5758 		if (lun->write_buffer == NULL) {
5759 			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5760 			    M_CTL, M_WAITOK);
5761 		}
5762 		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5763 	}
5764 	ctsio->kern_data_len = len;
5765 	ctsio->kern_total_len = len;
5766 	ctsio->kern_data_resid = 0;
5767 	ctsio->kern_rel_offset = 0;
5768 	ctsio->kern_sg_entries = 0;
5769 	ctl_set_success(ctsio);
5770 	ctsio->be_move_done = ctl_config_move_done;
5771 	ctl_datamove((union ctl_io *)ctsio);
5772 	return (CTL_RETVAL_COMPLETE);
5773 }
5774 
5775 int
5776 ctl_write_buffer(struct ctl_scsiio *ctsio)
5777 {
5778 	struct scsi_write_buffer *cdb;
5779 	struct ctl_lun *lun;
5780 	int buffer_offset, len;
5781 
5782 	CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5783 
5784 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5785 	cdb = (struct scsi_write_buffer *)ctsio->cdb;
5786 
5787 	if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA) {
5788 		ctl_set_invalid_field(ctsio,
5789 				      /*sks_valid*/ 1,
5790 				      /*command*/ 1,
5791 				      /*field*/ 1,
5792 				      /*bit_valid*/ 1,
5793 				      /*bit*/ 4);
5794 		ctl_done((union ctl_io *)ctsio);
5795 		return (CTL_RETVAL_COMPLETE);
5796 	}
5797 
5798 	len = scsi_3btoul(cdb->length);
5799 	buffer_offset = scsi_3btoul(cdb->offset);
5800 
5801 	if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5802 		ctl_set_invalid_field(ctsio,
5803 				      /*sks_valid*/ 1,
5804 				      /*command*/ 1,
5805 				      /*field*/ 6,
5806 				      /*bit_valid*/ 0,
5807 				      /*bit*/ 0);
5808 		ctl_done((union ctl_io *)ctsio);
5809 		return (CTL_RETVAL_COMPLETE);
5810 	}
5811 
5812 	/*
5813 	 * If we've got a kernel request that hasn't been malloced yet,
5814 	 * malloc it and tell the caller the data buffer is here.
5815 	 */
5816 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5817 		if (lun->write_buffer == NULL) {
5818 			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5819 			    M_CTL, M_WAITOK);
5820 		}
5821 		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5822 		ctsio->kern_data_len = len;
5823 		ctsio->kern_total_len = len;
5824 		ctsio->kern_data_resid = 0;
5825 		ctsio->kern_rel_offset = 0;
5826 		ctsio->kern_sg_entries = 0;
5827 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5828 		ctsio->be_move_done = ctl_config_move_done;
5829 		ctl_datamove((union ctl_io *)ctsio);
5830 
5831 		return (CTL_RETVAL_COMPLETE);
5832 	}
5833 
5834 	ctl_set_success(ctsio);
5835 	ctl_done((union ctl_io *)ctsio);
5836 	return (CTL_RETVAL_COMPLETE);
5837 }
5838 
5839 int
5840 ctl_write_same(struct ctl_scsiio *ctsio)
5841 {
5842 	struct ctl_lun *lun;
5843 	struct ctl_lba_len_flags *lbalen;
5844 	uint64_t lba;
5845 	uint32_t num_blocks;
5846 	int len, retval;
5847 	uint8_t byte2;
5848 
5849 	retval = CTL_RETVAL_COMPLETE;
5850 
5851 	CTL_DEBUG_PRINT(("ctl_write_same\n"));
5852 
5853 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5854 
5855 	switch (ctsio->cdb[0]) {
5856 	case WRITE_SAME_10: {
5857 		struct scsi_write_same_10 *cdb;
5858 
5859 		cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5860 
5861 		lba = scsi_4btoul(cdb->addr);
5862 		num_blocks = scsi_2btoul(cdb->length);
5863 		byte2 = cdb->byte2;
5864 		break;
5865 	}
5866 	case WRITE_SAME_16: {
5867 		struct scsi_write_same_16 *cdb;
5868 
5869 		cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5870 
5871 		lba = scsi_8btou64(cdb->addr);
5872 		num_blocks = scsi_4btoul(cdb->length);
5873 		byte2 = cdb->byte2;
5874 		break;
5875 	}
5876 	default:
5877 		/*
5878 		 * We got a command we don't support.  This shouldn't
5879 		 * happen, commands should be filtered out above us.
5880 		 */
5881 		ctl_set_invalid_opcode(ctsio);
5882 		ctl_done((union ctl_io *)ctsio);
5883 
5884 		return (CTL_RETVAL_COMPLETE);
5885 		break; /* NOTREACHED */
5886 	}
5887 
5888 	/* NDOB and ANCHOR flags can be used only together with UNMAP */
5889 	if ((byte2 & SWS_UNMAP) == 0 &&
5890 	    (byte2 & (SWS_NDOB | SWS_ANCHOR)) != 0) {
5891 		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
5892 		    /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
5893 		ctl_done((union ctl_io *)ctsio);
5894 		return (CTL_RETVAL_COMPLETE);
5895 	}
5896 
5897 	/*
5898 	 * The first check is to make sure we're in bounds, the second
5899 	 * check is to catch wrap-around problems.  If the lba + num blocks
5900 	 * is less than the lba, then we've wrapped around and the block
5901 	 * range is invalid anyway.
5902 	 */
5903 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5904 	 || ((lba + num_blocks) < lba)) {
5905 		ctl_set_lba_out_of_range(ctsio);
5906 		ctl_done((union ctl_io *)ctsio);
5907 		return (CTL_RETVAL_COMPLETE);
5908 	}
5909 
5910 	/* Zero number of blocks means "to the last logical block" */
5911 	if (num_blocks == 0) {
5912 		if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5913 			ctl_set_invalid_field(ctsio,
5914 					      /*sks_valid*/ 0,
5915 					      /*command*/ 1,
5916 					      /*field*/ 0,
5917 					      /*bit_valid*/ 0,
5918 					      /*bit*/ 0);
5919 			ctl_done((union ctl_io *)ctsio);
5920 			return (CTL_RETVAL_COMPLETE);
5921 		}
5922 		num_blocks = (lun->be_lun->maxlba + 1) - lba;
5923 	}
5924 
5925 	len = lun->be_lun->blocksize;
5926 
5927 	/*
5928 	 * If we've got a kernel request that hasn't been malloced yet,
5929 	 * malloc it and tell the caller the data buffer is here.
5930 	 */
5931 	if ((byte2 & SWS_NDOB) == 0 &&
5932 	    (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5933 		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5934 		ctsio->kern_data_len = len;
5935 		ctsio->kern_total_len = len;
5936 		ctsio->kern_data_resid = 0;
5937 		ctsio->kern_rel_offset = 0;
5938 		ctsio->kern_sg_entries = 0;
5939 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5940 		ctsio->be_move_done = ctl_config_move_done;
5941 		ctl_datamove((union ctl_io *)ctsio);
5942 
5943 		return (CTL_RETVAL_COMPLETE);
5944 	}
5945 
5946 	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5947 	lbalen->lba = lba;
5948 	lbalen->len = num_blocks;
5949 	lbalen->flags = byte2;
5950 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5951 
5952 	return (retval);
5953 }
5954 
5955 int
5956 ctl_unmap(struct ctl_scsiio *ctsio)
5957 {
5958 	struct ctl_lun *lun;
5959 	struct scsi_unmap *cdb;
5960 	struct ctl_ptr_len_flags *ptrlen;
5961 	struct scsi_unmap_header *hdr;
5962 	struct scsi_unmap_desc *buf, *end, *endnz, *range;
5963 	uint64_t lba;
5964 	uint32_t num_blocks;
5965 	int len, retval;
5966 	uint8_t byte2;
5967 
5968 	retval = CTL_RETVAL_COMPLETE;
5969 
5970 	CTL_DEBUG_PRINT(("ctl_unmap\n"));
5971 
5972 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5973 	cdb = (struct scsi_unmap *)ctsio->cdb;
5974 
5975 	len = scsi_2btoul(cdb->length);
5976 	byte2 = cdb->byte2;
5977 
5978 	/*
5979 	 * If we've got a kernel request that hasn't been malloced yet,
5980 	 * malloc it and tell the caller the data buffer is here.
5981 	 */
5982 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5983 		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5984 		ctsio->kern_data_len = len;
5985 		ctsio->kern_total_len = len;
5986 		ctsio->kern_data_resid = 0;
5987 		ctsio->kern_rel_offset = 0;
5988 		ctsio->kern_sg_entries = 0;
5989 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5990 		ctsio->be_move_done = ctl_config_move_done;
5991 		ctl_datamove((union ctl_io *)ctsio);
5992 
5993 		return (CTL_RETVAL_COMPLETE);
5994 	}
5995 
5996 	len = ctsio->kern_total_len - ctsio->kern_data_resid;
5997 	hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
5998 	if (len < sizeof (*hdr) ||
5999 	    len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
6000 	    len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
6001 	    scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
6002 		ctl_set_invalid_field(ctsio,
6003 				      /*sks_valid*/ 0,
6004 				      /*command*/ 0,
6005 				      /*field*/ 0,
6006 				      /*bit_valid*/ 0,
6007 				      /*bit*/ 0);
6008 		goto done;
6009 	}
6010 	len = scsi_2btoul(hdr->desc_length);
6011 	buf = (struct scsi_unmap_desc *)(hdr + 1);
6012 	end = buf + len / sizeof(*buf);
6013 
6014 	endnz = buf;
6015 	for (range = buf; range < end; range++) {
6016 		lba = scsi_8btou64(range->lba);
6017 		num_blocks = scsi_4btoul(range->length);
6018 		if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
6019 		 || ((lba + num_blocks) < lba)) {
6020 			ctl_set_lba_out_of_range(ctsio);
6021 			ctl_done((union ctl_io *)ctsio);
6022 			return (CTL_RETVAL_COMPLETE);
6023 		}
6024 		if (num_blocks != 0)
6025 			endnz = range + 1;
6026 	}
6027 
6028 	/*
6029 	 * Block backend can not handle zero last range.
6030 	 * Filter it out and return if there is nothing left.
6031 	 */
6032 	len = (uint8_t *)endnz - (uint8_t *)buf;
6033 	if (len == 0) {
6034 		ctl_set_success(ctsio);
6035 		goto done;
6036 	}
6037 
6038 	mtx_lock(&lun->lun_lock);
6039 	ptrlen = (struct ctl_ptr_len_flags *)
6040 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
6041 	ptrlen->ptr = (void *)buf;
6042 	ptrlen->len = len;
6043 	ptrlen->flags = byte2;
6044 	ctl_check_blocked(lun);
6045 	mtx_unlock(&lun->lun_lock);
6046 
6047 	retval = lun->backend->config_write((union ctl_io *)ctsio);
6048 	return (retval);
6049 
6050 done:
6051 	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
6052 		free(ctsio->kern_data_ptr, M_CTL);
6053 		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
6054 	}
6055 	ctl_done((union ctl_io *)ctsio);
6056 	return (CTL_RETVAL_COMPLETE);
6057 }
6058 
6059 /*
6060  * Note that this function currently doesn't actually do anything inside
6061  * CTL to enforce things if the DQue bit is turned on.
6062  *
6063  * Also note that this function can't be used in the default case, because
6064  * the DQue bit isn't set in the changeable mask for the control mode page
6065  * anyway.  This is just here as an example for how to implement a page
6066  * handler, and a placeholder in case we want to allow the user to turn
6067  * tagged queueing on and off.
6068  *
6069  * The D_SENSE bit handling is functional, however, and will turn
6070  * descriptor sense on and off for a given LUN.
6071  */
6072 int
6073 ctl_control_page_handler(struct ctl_scsiio *ctsio,
6074 			 struct ctl_page_index *page_index, uint8_t *page_ptr)
6075 {
6076 	struct scsi_control_page *current_cp, *saved_cp, *user_cp;
6077 	struct ctl_lun *lun;
6078 	struct ctl_softc *softc;
6079 	int set_ua;
6080 	uint32_t initidx;
6081 
6082 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6083 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6084 	set_ua = 0;
6085 
6086 	user_cp = (struct scsi_control_page *)page_ptr;
6087 	current_cp = (struct scsi_control_page *)
6088 		(page_index->page_data + (page_index->page_len *
6089 		CTL_PAGE_CURRENT));
6090 	saved_cp = (struct scsi_control_page *)
6091 		(page_index->page_data + (page_index->page_len *
6092 		CTL_PAGE_SAVED));
6093 
6094 	softc = control_softc;
6095 
6096 	mtx_lock(&lun->lun_lock);
6097 	if (((current_cp->rlec & SCP_DSENSE) == 0)
6098 	 && ((user_cp->rlec & SCP_DSENSE) != 0)) {
6099 		/*
6100 		 * Descriptor sense is currently turned off and the user
6101 		 * wants to turn it on.
6102 		 */
6103 		current_cp->rlec |= SCP_DSENSE;
6104 		saved_cp->rlec |= SCP_DSENSE;
6105 		lun->flags |= CTL_LUN_SENSE_DESC;
6106 		set_ua = 1;
6107 	} else if (((current_cp->rlec & SCP_DSENSE) != 0)
6108 		&& ((user_cp->rlec & SCP_DSENSE) == 0)) {
6109 		/*
6110 		 * Descriptor sense is currently turned on, and the user
6111 		 * wants to turn it off.
6112 		 */
6113 		current_cp->rlec &= ~SCP_DSENSE;
6114 		saved_cp->rlec &= ~SCP_DSENSE;
6115 		lun->flags &= ~CTL_LUN_SENSE_DESC;
6116 		set_ua = 1;
6117 	}
6118 	if ((current_cp->queue_flags & SCP_QUEUE_ALG_MASK) !=
6119 	    (user_cp->queue_flags & SCP_QUEUE_ALG_MASK)) {
6120 		current_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
6121 		current_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
6122 		saved_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
6123 		saved_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
6124 		set_ua = 1;
6125 	}
6126 	if ((current_cp->eca_and_aen & SCP_SWP) !=
6127 	    (user_cp->eca_and_aen & SCP_SWP)) {
6128 		current_cp->eca_and_aen &= ~SCP_SWP;
6129 		current_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
6130 		saved_cp->eca_and_aen &= ~SCP_SWP;
6131 		saved_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
6132 		set_ua = 1;
6133 	}
6134 	if (set_ua != 0)
6135 		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
6136 	mtx_unlock(&lun->lun_lock);
6137 
6138 	return (0);
6139 }
6140 
6141 int
6142 ctl_caching_sp_handler(struct ctl_scsiio *ctsio,
6143 		     struct ctl_page_index *page_index, uint8_t *page_ptr)
6144 {
6145 	struct scsi_caching_page *current_cp, *saved_cp, *user_cp;
6146 	struct ctl_lun *lun;
6147 	int set_ua;
6148 	uint32_t initidx;
6149 
6150 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6151 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6152 	set_ua = 0;
6153 
6154 	user_cp = (struct scsi_caching_page *)page_ptr;
6155 	current_cp = (struct scsi_caching_page *)
6156 		(page_index->page_data + (page_index->page_len *
6157 		CTL_PAGE_CURRENT));
6158 	saved_cp = (struct scsi_caching_page *)
6159 		(page_index->page_data + (page_index->page_len *
6160 		CTL_PAGE_SAVED));
6161 
6162 	mtx_lock(&lun->lun_lock);
6163 	if ((current_cp->flags1 & (SCP_WCE | SCP_RCD)) !=
6164 	    (user_cp->flags1 & (SCP_WCE | SCP_RCD))) {
6165 		current_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6166 		current_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6167 		saved_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6168 		saved_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6169 		set_ua = 1;
6170 	}
6171 	if (set_ua != 0)
6172 		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
6173 	mtx_unlock(&lun->lun_lock);
6174 
6175 	return (0);
6176 }
6177 
6178 int
6179 ctl_debugconf_sp_select_handler(struct ctl_scsiio *ctsio,
6180 				struct ctl_page_index *page_index,
6181 				uint8_t *page_ptr)
6182 {
6183 	uint8_t *c;
6184 	int i;
6185 
6186 	c = ((struct copan_debugconf_subpage *)page_ptr)->ctl_time_io_secs;
6187 	ctl_time_io_secs =
6188 		(c[0] << 8) |
6189 		(c[1] << 0) |
6190 		0;
6191 	CTL_DEBUG_PRINT(("set ctl_time_io_secs to %d\n", ctl_time_io_secs));
6192 	printf("set ctl_time_io_secs to %d\n", ctl_time_io_secs);
6193 	printf("page data:");
6194 	for (i=0; i<8; i++)
6195 		printf(" %.2x",page_ptr[i]);
6196 	printf("\n");
6197 	return (0);
6198 }
6199 
6200 int
6201 ctl_debugconf_sp_sense_handler(struct ctl_scsiio *ctsio,
6202 			       struct ctl_page_index *page_index,
6203 			       int pc)
6204 {
6205 	struct copan_debugconf_subpage *page;
6206 
6207 	page = (struct copan_debugconf_subpage *)page_index->page_data +
6208 		(page_index->page_len * pc);
6209 
6210 	switch (pc) {
6211 	case SMS_PAGE_CTRL_CHANGEABLE >> 6:
6212 	case SMS_PAGE_CTRL_DEFAULT >> 6:
6213 	case SMS_PAGE_CTRL_SAVED >> 6:
6214 		/*
6215 		 * We don't update the changable or default bits for this page.
6216 		 */
6217 		break;
6218 	case SMS_PAGE_CTRL_CURRENT >> 6:
6219 		page->ctl_time_io_secs[0] = ctl_time_io_secs >> 8;
6220 		page->ctl_time_io_secs[1] = ctl_time_io_secs >> 0;
6221 		break;
6222 	default:
6223 #ifdef NEEDTOPORT
6224 		EPRINT(0, "Invalid PC %d!!", pc);
6225 #endif /* NEEDTOPORT */
6226 		break;
6227 	}
6228 	return (0);
6229 }
6230 
6231 
6232 static int
6233 ctl_do_mode_select(union ctl_io *io)
6234 {
6235 	struct scsi_mode_page_header *page_header;
6236 	struct ctl_page_index *page_index;
6237 	struct ctl_scsiio *ctsio;
6238 	int control_dev, page_len;
6239 	int page_len_offset, page_len_size;
6240 	union ctl_modepage_info *modepage_info;
6241 	struct ctl_lun *lun;
6242 	int *len_left, *len_used;
6243 	int retval, i;
6244 
6245 	ctsio = &io->scsiio;
6246 	page_index = NULL;
6247 	page_len = 0;
6248 	retval = CTL_RETVAL_COMPLETE;
6249 
6250 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6251 
6252 	if (lun->be_lun->lun_type != T_DIRECT)
6253 		control_dev = 1;
6254 	else
6255 		control_dev = 0;
6256 
6257 	modepage_info = (union ctl_modepage_info *)
6258 		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6259 	len_left = &modepage_info->header.len_left;
6260 	len_used = &modepage_info->header.len_used;
6261 
6262 do_next_page:
6263 
6264 	page_header = (struct scsi_mode_page_header *)
6265 		(ctsio->kern_data_ptr + *len_used);
6266 
6267 	if (*len_left == 0) {
6268 		free(ctsio->kern_data_ptr, M_CTL);
6269 		ctl_set_success(ctsio);
6270 		ctl_done((union ctl_io *)ctsio);
6271 		return (CTL_RETVAL_COMPLETE);
6272 	} else if (*len_left < sizeof(struct scsi_mode_page_header)) {
6273 
6274 		free(ctsio->kern_data_ptr, M_CTL);
6275 		ctl_set_param_len_error(ctsio);
6276 		ctl_done((union ctl_io *)ctsio);
6277 		return (CTL_RETVAL_COMPLETE);
6278 
6279 	} else if ((page_header->page_code & SMPH_SPF)
6280 		&& (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
6281 
6282 		free(ctsio->kern_data_ptr, M_CTL);
6283 		ctl_set_param_len_error(ctsio);
6284 		ctl_done((union ctl_io *)ctsio);
6285 		return (CTL_RETVAL_COMPLETE);
6286 	}
6287 
6288 
6289 	/*
6290 	 * XXX KDM should we do something with the block descriptor?
6291 	 */
6292 	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6293 
6294 		if ((control_dev != 0)
6295 		 && (lun->mode_pages.index[i].page_flags &
6296 		     CTL_PAGE_FLAG_DISK_ONLY))
6297 			continue;
6298 
6299 		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
6300 		    (page_header->page_code & SMPH_PC_MASK))
6301 			continue;
6302 
6303 		/*
6304 		 * If neither page has a subpage code, then we've got a
6305 		 * match.
6306 		 */
6307 		if (((lun->mode_pages.index[i].page_code & SMPH_SPF) == 0)
6308 		 && ((page_header->page_code & SMPH_SPF) == 0)) {
6309 			page_index = &lun->mode_pages.index[i];
6310 			page_len = page_header->page_length;
6311 			break;
6312 		}
6313 
6314 		/*
6315 		 * If both pages have subpages, then the subpage numbers
6316 		 * have to match.
6317 		 */
6318 		if ((lun->mode_pages.index[i].page_code & SMPH_SPF)
6319 		  && (page_header->page_code & SMPH_SPF)) {
6320 			struct scsi_mode_page_header_sp *sph;
6321 
6322 			sph = (struct scsi_mode_page_header_sp *)page_header;
6323 
6324 			if (lun->mode_pages.index[i].subpage ==
6325 			    sph->subpage) {
6326 				page_index = &lun->mode_pages.index[i];
6327 				page_len = scsi_2btoul(sph->page_length);
6328 				break;
6329 			}
6330 		}
6331 	}
6332 
6333 	/*
6334 	 * If we couldn't find the page, or if we don't have a mode select
6335 	 * handler for it, send back an error to the user.
6336 	 */
6337 	if ((page_index == NULL)
6338 	 || (page_index->select_handler == NULL)) {
6339 		ctl_set_invalid_field(ctsio,
6340 				      /*sks_valid*/ 1,
6341 				      /*command*/ 0,
6342 				      /*field*/ *len_used,
6343 				      /*bit_valid*/ 0,
6344 				      /*bit*/ 0);
6345 		free(ctsio->kern_data_ptr, M_CTL);
6346 		ctl_done((union ctl_io *)ctsio);
6347 		return (CTL_RETVAL_COMPLETE);
6348 	}
6349 
6350 	if (page_index->page_code & SMPH_SPF) {
6351 		page_len_offset = 2;
6352 		page_len_size = 2;
6353 	} else {
6354 		page_len_size = 1;
6355 		page_len_offset = 1;
6356 	}
6357 
6358 	/*
6359 	 * If the length the initiator gives us isn't the one we specify in
6360 	 * the mode page header, or if they didn't specify enough data in
6361 	 * the CDB to avoid truncating this page, kick out the request.
6362 	 */
6363 	if ((page_len != (page_index->page_len - page_len_offset -
6364 			  page_len_size))
6365 	 || (*len_left < page_index->page_len)) {
6366 
6367 
6368 		ctl_set_invalid_field(ctsio,
6369 				      /*sks_valid*/ 1,
6370 				      /*command*/ 0,
6371 				      /*field*/ *len_used + page_len_offset,
6372 				      /*bit_valid*/ 0,
6373 				      /*bit*/ 0);
6374 		free(ctsio->kern_data_ptr, M_CTL);
6375 		ctl_done((union ctl_io *)ctsio);
6376 		return (CTL_RETVAL_COMPLETE);
6377 	}
6378 
6379 	/*
6380 	 * Run through the mode page, checking to make sure that the bits
6381 	 * the user changed are actually legal for him to change.
6382 	 */
6383 	for (i = 0; i < page_index->page_len; i++) {
6384 		uint8_t *user_byte, *change_mask, *current_byte;
6385 		int bad_bit;
6386 		int j;
6387 
6388 		user_byte = (uint8_t *)page_header + i;
6389 		change_mask = page_index->page_data +
6390 			      (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6391 		current_byte = page_index->page_data +
6392 			       (page_index->page_len * CTL_PAGE_CURRENT) + i;
6393 
6394 		/*
6395 		 * Check to see whether the user set any bits in this byte
6396 		 * that he is not allowed to set.
6397 		 */
6398 		if ((*user_byte & ~(*change_mask)) ==
6399 		    (*current_byte & ~(*change_mask)))
6400 			continue;
6401 
6402 		/*
6403 		 * Go through bit by bit to determine which one is illegal.
6404 		 */
6405 		bad_bit = 0;
6406 		for (j = 7; j >= 0; j--) {
6407 			if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6408 			    (((1 << i) & ~(*change_mask)) & *current_byte)) {
6409 				bad_bit = i;
6410 				break;
6411 			}
6412 		}
6413 		ctl_set_invalid_field(ctsio,
6414 				      /*sks_valid*/ 1,
6415 				      /*command*/ 0,
6416 				      /*field*/ *len_used + i,
6417 				      /*bit_valid*/ 1,
6418 				      /*bit*/ bad_bit);
6419 		free(ctsio->kern_data_ptr, M_CTL);
6420 		ctl_done((union ctl_io *)ctsio);
6421 		return (CTL_RETVAL_COMPLETE);
6422 	}
6423 
6424 	/*
6425 	 * Decrement these before we call the page handler, since we may
6426 	 * end up getting called back one way or another before the handler
6427 	 * returns to this context.
6428 	 */
6429 	*len_left -= page_index->page_len;
6430 	*len_used += page_index->page_len;
6431 
6432 	retval = page_index->select_handler(ctsio, page_index,
6433 					    (uint8_t *)page_header);
6434 
6435 	/*
6436 	 * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6437 	 * wait until this queued command completes to finish processing
6438 	 * the mode page.  If it returns anything other than
6439 	 * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6440 	 * already set the sense information, freed the data pointer, and
6441 	 * completed the io for us.
6442 	 */
6443 	if (retval != CTL_RETVAL_COMPLETE)
6444 		goto bailout_no_done;
6445 
6446 	/*
6447 	 * If the initiator sent us more than one page, parse the next one.
6448 	 */
6449 	if (*len_left > 0)
6450 		goto do_next_page;
6451 
6452 	ctl_set_success(ctsio);
6453 	free(ctsio->kern_data_ptr, M_CTL);
6454 	ctl_done((union ctl_io *)ctsio);
6455 
6456 bailout_no_done:
6457 
6458 	return (CTL_RETVAL_COMPLETE);
6459 
6460 }
6461 
6462 int
6463 ctl_mode_select(struct ctl_scsiio *ctsio)
6464 {
6465 	int param_len, pf, sp;
6466 	int header_size, bd_len;
6467 	int len_left, len_used;
6468 	struct ctl_page_index *page_index;
6469 	struct ctl_lun *lun;
6470 	int control_dev, page_len;
6471 	union ctl_modepage_info *modepage_info;
6472 	int retval;
6473 
6474 	pf = 0;
6475 	sp = 0;
6476 	page_len = 0;
6477 	len_used = 0;
6478 	len_left = 0;
6479 	retval = 0;
6480 	bd_len = 0;
6481 	page_index = NULL;
6482 
6483 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6484 
6485 	if (lun->be_lun->lun_type != T_DIRECT)
6486 		control_dev = 1;
6487 	else
6488 		control_dev = 0;
6489 
6490 	switch (ctsio->cdb[0]) {
6491 	case MODE_SELECT_6: {
6492 		struct scsi_mode_select_6 *cdb;
6493 
6494 		cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6495 
6496 		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6497 		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6498 
6499 		param_len = cdb->length;
6500 		header_size = sizeof(struct scsi_mode_header_6);
6501 		break;
6502 	}
6503 	case MODE_SELECT_10: {
6504 		struct scsi_mode_select_10 *cdb;
6505 
6506 		cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6507 
6508 		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6509 		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6510 
6511 		param_len = scsi_2btoul(cdb->length);
6512 		header_size = sizeof(struct scsi_mode_header_10);
6513 		break;
6514 	}
6515 	default:
6516 		ctl_set_invalid_opcode(ctsio);
6517 		ctl_done((union ctl_io *)ctsio);
6518 		return (CTL_RETVAL_COMPLETE);
6519 		break; /* NOTREACHED */
6520 	}
6521 
6522 	/*
6523 	 * From SPC-3:
6524 	 * "A parameter list length of zero indicates that the Data-Out Buffer
6525 	 * shall be empty. This condition shall not be considered as an error."
6526 	 */
6527 	if (param_len == 0) {
6528 		ctl_set_success(ctsio);
6529 		ctl_done((union ctl_io *)ctsio);
6530 		return (CTL_RETVAL_COMPLETE);
6531 	}
6532 
6533 	/*
6534 	 * Since we'll hit this the first time through, prior to
6535 	 * allocation, we don't need to free a data buffer here.
6536 	 */
6537 	if (param_len < header_size) {
6538 		ctl_set_param_len_error(ctsio);
6539 		ctl_done((union ctl_io *)ctsio);
6540 		return (CTL_RETVAL_COMPLETE);
6541 	}
6542 
6543 	/*
6544 	 * Allocate the data buffer and grab the user's data.  In theory,
6545 	 * we shouldn't have to sanity check the parameter list length here
6546 	 * because the maximum size is 64K.  We should be able to malloc
6547 	 * that much without too many problems.
6548 	 */
6549 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6550 		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6551 		ctsio->kern_data_len = param_len;
6552 		ctsio->kern_total_len = param_len;
6553 		ctsio->kern_data_resid = 0;
6554 		ctsio->kern_rel_offset = 0;
6555 		ctsio->kern_sg_entries = 0;
6556 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6557 		ctsio->be_move_done = ctl_config_move_done;
6558 		ctl_datamove((union ctl_io *)ctsio);
6559 
6560 		return (CTL_RETVAL_COMPLETE);
6561 	}
6562 
6563 	switch (ctsio->cdb[0]) {
6564 	case MODE_SELECT_6: {
6565 		struct scsi_mode_header_6 *mh6;
6566 
6567 		mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6568 		bd_len = mh6->blk_desc_len;
6569 		break;
6570 	}
6571 	case MODE_SELECT_10: {
6572 		struct scsi_mode_header_10 *mh10;
6573 
6574 		mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6575 		bd_len = scsi_2btoul(mh10->blk_desc_len);
6576 		break;
6577 	}
6578 	default:
6579 		panic("Invalid CDB type %#x", ctsio->cdb[0]);
6580 		break;
6581 	}
6582 
6583 	if (param_len < (header_size + bd_len)) {
6584 		free(ctsio->kern_data_ptr, M_CTL);
6585 		ctl_set_param_len_error(ctsio);
6586 		ctl_done((union ctl_io *)ctsio);
6587 		return (CTL_RETVAL_COMPLETE);
6588 	}
6589 
6590 	/*
6591 	 * Set the IO_CONT flag, so that if this I/O gets passed to
6592 	 * ctl_config_write_done(), it'll get passed back to
6593 	 * ctl_do_mode_select() for further processing, or completion if
6594 	 * we're all done.
6595 	 */
6596 	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6597 	ctsio->io_cont = ctl_do_mode_select;
6598 
6599 	modepage_info = (union ctl_modepage_info *)
6600 		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6601 
6602 	memset(modepage_info, 0, sizeof(*modepage_info));
6603 
6604 	len_left = param_len - header_size - bd_len;
6605 	len_used = header_size + bd_len;
6606 
6607 	modepage_info->header.len_left = len_left;
6608 	modepage_info->header.len_used = len_used;
6609 
6610 	return (ctl_do_mode_select((union ctl_io *)ctsio));
6611 }
6612 
6613 int
6614 ctl_mode_sense(struct ctl_scsiio *ctsio)
6615 {
6616 	struct ctl_lun *lun;
6617 	int pc, page_code, dbd, llba, subpage;
6618 	int alloc_len, page_len, header_len, total_len;
6619 	struct scsi_mode_block_descr *block_desc;
6620 	struct ctl_page_index *page_index;
6621 	int control_dev;
6622 
6623 	dbd = 0;
6624 	llba = 0;
6625 	block_desc = NULL;
6626 	page_index = NULL;
6627 
6628 	CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6629 
6630 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6631 
6632 	if (lun->be_lun->lun_type != T_DIRECT)
6633 		control_dev = 1;
6634 	else
6635 		control_dev = 0;
6636 
6637 	switch (ctsio->cdb[0]) {
6638 	case MODE_SENSE_6: {
6639 		struct scsi_mode_sense_6 *cdb;
6640 
6641 		cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6642 
6643 		header_len = sizeof(struct scsi_mode_hdr_6);
6644 		if (cdb->byte2 & SMS_DBD)
6645 			dbd = 1;
6646 		else
6647 			header_len += sizeof(struct scsi_mode_block_descr);
6648 
6649 		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6650 		page_code = cdb->page & SMS_PAGE_CODE;
6651 		subpage = cdb->subpage;
6652 		alloc_len = cdb->length;
6653 		break;
6654 	}
6655 	case MODE_SENSE_10: {
6656 		struct scsi_mode_sense_10 *cdb;
6657 
6658 		cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6659 
6660 		header_len = sizeof(struct scsi_mode_hdr_10);
6661 
6662 		if (cdb->byte2 & SMS_DBD)
6663 			dbd = 1;
6664 		else
6665 			header_len += sizeof(struct scsi_mode_block_descr);
6666 		if (cdb->byte2 & SMS10_LLBAA)
6667 			llba = 1;
6668 		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6669 		page_code = cdb->page & SMS_PAGE_CODE;
6670 		subpage = cdb->subpage;
6671 		alloc_len = scsi_2btoul(cdb->length);
6672 		break;
6673 	}
6674 	default:
6675 		ctl_set_invalid_opcode(ctsio);
6676 		ctl_done((union ctl_io *)ctsio);
6677 		return (CTL_RETVAL_COMPLETE);
6678 		break; /* NOTREACHED */
6679 	}
6680 
6681 	/*
6682 	 * We have to make a first pass through to calculate the size of
6683 	 * the pages that match the user's query.  Then we allocate enough
6684 	 * memory to hold it, and actually copy the data into the buffer.
6685 	 */
6686 	switch (page_code) {
6687 	case SMS_ALL_PAGES_PAGE: {
6688 		int i;
6689 
6690 		page_len = 0;
6691 
6692 		/*
6693 		 * At the moment, values other than 0 and 0xff here are
6694 		 * reserved according to SPC-3.
6695 		 */
6696 		if ((subpage != SMS_SUBPAGE_PAGE_0)
6697 		 && (subpage != SMS_SUBPAGE_ALL)) {
6698 			ctl_set_invalid_field(ctsio,
6699 					      /*sks_valid*/ 1,
6700 					      /*command*/ 1,
6701 					      /*field*/ 3,
6702 					      /*bit_valid*/ 0,
6703 					      /*bit*/ 0);
6704 			ctl_done((union ctl_io *)ctsio);
6705 			return (CTL_RETVAL_COMPLETE);
6706 		}
6707 
6708 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6709 			if ((control_dev != 0)
6710 			 && (lun->mode_pages.index[i].page_flags &
6711 			     CTL_PAGE_FLAG_DISK_ONLY))
6712 				continue;
6713 
6714 			/*
6715 			 * We don't use this subpage if the user didn't
6716 			 * request all subpages.
6717 			 */
6718 			if ((lun->mode_pages.index[i].subpage != 0)
6719 			 && (subpage == SMS_SUBPAGE_PAGE_0))
6720 				continue;
6721 
6722 #if 0
6723 			printf("found page %#x len %d\n",
6724 			       lun->mode_pages.index[i].page_code &
6725 			       SMPH_PC_MASK,
6726 			       lun->mode_pages.index[i].page_len);
6727 #endif
6728 			page_len += lun->mode_pages.index[i].page_len;
6729 		}
6730 		break;
6731 	}
6732 	default: {
6733 		int i;
6734 
6735 		page_len = 0;
6736 
6737 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6738 			/* Look for the right page code */
6739 			if ((lun->mode_pages.index[i].page_code &
6740 			     SMPH_PC_MASK) != page_code)
6741 				continue;
6742 
6743 			/* Look for the right subpage or the subpage wildcard*/
6744 			if ((lun->mode_pages.index[i].subpage != subpage)
6745 			 && (subpage != SMS_SUBPAGE_ALL))
6746 				continue;
6747 
6748 			/* Make sure the page is supported for this dev type */
6749 			if ((control_dev != 0)
6750 			 && (lun->mode_pages.index[i].page_flags &
6751 			     CTL_PAGE_FLAG_DISK_ONLY))
6752 				continue;
6753 
6754 #if 0
6755 			printf("found page %#x len %d\n",
6756 			       lun->mode_pages.index[i].page_code &
6757 			       SMPH_PC_MASK,
6758 			       lun->mode_pages.index[i].page_len);
6759 #endif
6760 
6761 			page_len += lun->mode_pages.index[i].page_len;
6762 		}
6763 
6764 		if (page_len == 0) {
6765 			ctl_set_invalid_field(ctsio,
6766 					      /*sks_valid*/ 1,
6767 					      /*command*/ 1,
6768 					      /*field*/ 2,
6769 					      /*bit_valid*/ 1,
6770 					      /*bit*/ 5);
6771 			ctl_done((union ctl_io *)ctsio);
6772 			return (CTL_RETVAL_COMPLETE);
6773 		}
6774 		break;
6775 	}
6776 	}
6777 
6778 	total_len = header_len + page_len;
6779 #if 0
6780 	printf("header_len = %d, page_len = %d, total_len = %d\n",
6781 	       header_len, page_len, total_len);
6782 #endif
6783 
6784 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6785 	ctsio->kern_sg_entries = 0;
6786 	ctsio->kern_data_resid = 0;
6787 	ctsio->kern_rel_offset = 0;
6788 	if (total_len < alloc_len) {
6789 		ctsio->residual = alloc_len - total_len;
6790 		ctsio->kern_data_len = total_len;
6791 		ctsio->kern_total_len = total_len;
6792 	} else {
6793 		ctsio->residual = 0;
6794 		ctsio->kern_data_len = alloc_len;
6795 		ctsio->kern_total_len = alloc_len;
6796 	}
6797 
6798 	switch (ctsio->cdb[0]) {
6799 	case MODE_SENSE_6: {
6800 		struct scsi_mode_hdr_6 *header;
6801 
6802 		header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6803 
6804 		header->datalen = ctl_min(total_len - 1, 254);
6805 		if (control_dev == 0) {
6806 			header->dev_specific = 0x10; /* DPOFUA */
6807 			if ((lun->flags & CTL_LUN_READONLY) ||
6808 			    (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6809 			    .eca_and_aen & SCP_SWP) != 0)
6810 				    header->dev_specific |= 0x80; /* WP */
6811 		}
6812 		if (dbd)
6813 			header->block_descr_len = 0;
6814 		else
6815 			header->block_descr_len =
6816 				sizeof(struct scsi_mode_block_descr);
6817 		block_desc = (struct scsi_mode_block_descr *)&header[1];
6818 		break;
6819 	}
6820 	case MODE_SENSE_10: {
6821 		struct scsi_mode_hdr_10 *header;
6822 		int datalen;
6823 
6824 		header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6825 
6826 		datalen = ctl_min(total_len - 2, 65533);
6827 		scsi_ulto2b(datalen, header->datalen);
6828 		if (control_dev == 0) {
6829 			header->dev_specific = 0x10; /* DPOFUA */
6830 			if ((lun->flags & CTL_LUN_READONLY) ||
6831 			    (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6832 			    .eca_and_aen & SCP_SWP) != 0)
6833 				    header->dev_specific |= 0x80; /* WP */
6834 		}
6835 		if (dbd)
6836 			scsi_ulto2b(0, header->block_descr_len);
6837 		else
6838 			scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
6839 				    header->block_descr_len);
6840 		block_desc = (struct scsi_mode_block_descr *)&header[1];
6841 		break;
6842 	}
6843 	default:
6844 		panic("invalid CDB type %#x", ctsio->cdb[0]);
6845 		break; /* NOTREACHED */
6846 	}
6847 
6848 	/*
6849 	 * If we've got a disk, use its blocksize in the block
6850 	 * descriptor.  Otherwise, just set it to 0.
6851 	 */
6852 	if (dbd == 0) {
6853 		if (control_dev == 0)
6854 			scsi_ulto3b(lun->be_lun->blocksize,
6855 				    block_desc->block_len);
6856 		else
6857 			scsi_ulto3b(0, block_desc->block_len);
6858 	}
6859 
6860 	switch (page_code) {
6861 	case SMS_ALL_PAGES_PAGE: {
6862 		int i, data_used;
6863 
6864 		data_used = header_len;
6865 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6866 			struct ctl_page_index *page_index;
6867 
6868 			page_index = &lun->mode_pages.index[i];
6869 
6870 			if ((control_dev != 0)
6871 			 && (page_index->page_flags &
6872 			    CTL_PAGE_FLAG_DISK_ONLY))
6873 				continue;
6874 
6875 			/*
6876 			 * We don't use this subpage if the user didn't
6877 			 * request all subpages.  We already checked (above)
6878 			 * to make sure the user only specified a subpage
6879 			 * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
6880 			 */
6881 			if ((page_index->subpage != 0)
6882 			 && (subpage == SMS_SUBPAGE_PAGE_0))
6883 				continue;
6884 
6885 			/*
6886 			 * Call the handler, if it exists, to update the
6887 			 * page to the latest values.
6888 			 */
6889 			if (page_index->sense_handler != NULL)
6890 				page_index->sense_handler(ctsio, page_index,pc);
6891 
6892 			memcpy(ctsio->kern_data_ptr + data_used,
6893 			       page_index->page_data +
6894 			       (page_index->page_len * pc),
6895 			       page_index->page_len);
6896 			data_used += page_index->page_len;
6897 		}
6898 		break;
6899 	}
6900 	default: {
6901 		int i, data_used;
6902 
6903 		data_used = header_len;
6904 
6905 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6906 			struct ctl_page_index *page_index;
6907 
6908 			page_index = &lun->mode_pages.index[i];
6909 
6910 			/* Look for the right page code */
6911 			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6912 				continue;
6913 
6914 			/* Look for the right subpage or the subpage wildcard*/
6915 			if ((page_index->subpage != subpage)
6916 			 && (subpage != SMS_SUBPAGE_ALL))
6917 				continue;
6918 
6919 			/* Make sure the page is supported for this dev type */
6920 			if ((control_dev != 0)
6921 			 && (page_index->page_flags &
6922 			     CTL_PAGE_FLAG_DISK_ONLY))
6923 				continue;
6924 
6925 			/*
6926 			 * Call the handler, if it exists, to update the
6927 			 * page to the latest values.
6928 			 */
6929 			if (page_index->sense_handler != NULL)
6930 				page_index->sense_handler(ctsio, page_index,pc);
6931 
6932 			memcpy(ctsio->kern_data_ptr + data_used,
6933 			       page_index->page_data +
6934 			       (page_index->page_len * pc),
6935 			       page_index->page_len);
6936 			data_used += page_index->page_len;
6937 		}
6938 		break;
6939 	}
6940 	}
6941 
6942 	ctl_set_success(ctsio);
6943 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6944 	ctsio->be_move_done = ctl_config_move_done;
6945 	ctl_datamove((union ctl_io *)ctsio);
6946 	return (CTL_RETVAL_COMPLETE);
6947 }
6948 
6949 int
6950 ctl_lbp_log_sense_handler(struct ctl_scsiio *ctsio,
6951 			       struct ctl_page_index *page_index,
6952 			       int pc)
6953 {
6954 	struct ctl_lun *lun;
6955 	struct scsi_log_param_header *phdr;
6956 	uint8_t *data;
6957 	uint64_t val;
6958 
6959 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6960 	data = page_index->page_data;
6961 
6962 	if (lun->backend->lun_attr != NULL &&
6963 	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksavail"))
6964 	     != UINT64_MAX) {
6965 		phdr = (struct scsi_log_param_header *)data;
6966 		scsi_ulto2b(0x0001, phdr->param_code);
6967 		phdr->param_control = SLP_LBIN | SLP_LP;
6968 		phdr->param_len = 8;
6969 		data = (uint8_t *)(phdr + 1);
6970 		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6971 		data[4] = 0x02; /* per-pool */
6972 		data += phdr->param_len;
6973 	}
6974 
6975 	if (lun->backend->lun_attr != NULL &&
6976 	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksused"))
6977 	     != UINT64_MAX) {
6978 		phdr = (struct scsi_log_param_header *)data;
6979 		scsi_ulto2b(0x0002, phdr->param_code);
6980 		phdr->param_control = SLP_LBIN | SLP_LP;
6981 		phdr->param_len = 8;
6982 		data = (uint8_t *)(phdr + 1);
6983 		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6984 		data[4] = 0x01; /* per-LUN */
6985 		data += phdr->param_len;
6986 	}
6987 
6988 	if (lun->backend->lun_attr != NULL &&
6989 	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksavail"))
6990 	     != UINT64_MAX) {
6991 		phdr = (struct scsi_log_param_header *)data;
6992 		scsi_ulto2b(0x00f1, phdr->param_code);
6993 		phdr->param_control = SLP_LBIN | SLP_LP;
6994 		phdr->param_len = 8;
6995 		data = (uint8_t *)(phdr + 1);
6996 		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6997 		data[4] = 0x02; /* per-pool */
6998 		data += phdr->param_len;
6999 	}
7000 
7001 	if (lun->backend->lun_attr != NULL &&
7002 	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksused"))
7003 	     != UINT64_MAX) {
7004 		phdr = (struct scsi_log_param_header *)data;
7005 		scsi_ulto2b(0x00f2, phdr->param_code);
7006 		phdr->param_control = SLP_LBIN | SLP_LP;
7007 		phdr->param_len = 8;
7008 		data = (uint8_t *)(phdr + 1);
7009 		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
7010 		data[4] = 0x02; /* per-pool */
7011 		data += phdr->param_len;
7012 	}
7013 
7014 	page_index->page_len = data - page_index->page_data;
7015 	return (0);
7016 }
7017 
7018 int
7019 ctl_log_sense(struct ctl_scsiio *ctsio)
7020 {
7021 	struct ctl_lun *lun;
7022 	int i, pc, page_code, subpage;
7023 	int alloc_len, total_len;
7024 	struct ctl_page_index *page_index;
7025 	struct scsi_log_sense *cdb;
7026 	struct scsi_log_header *header;
7027 
7028 	CTL_DEBUG_PRINT(("ctl_log_sense\n"));
7029 
7030 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7031 	cdb = (struct scsi_log_sense *)ctsio->cdb;
7032 	pc = (cdb->page & SLS_PAGE_CTRL_MASK) >> 6;
7033 	page_code = cdb->page & SLS_PAGE_CODE;
7034 	subpage = cdb->subpage;
7035 	alloc_len = scsi_2btoul(cdb->length);
7036 
7037 	page_index = NULL;
7038 	for (i = 0; i < CTL_NUM_LOG_PAGES; i++) {
7039 		page_index = &lun->log_pages.index[i];
7040 
7041 		/* Look for the right page code */
7042 		if ((page_index->page_code & SL_PAGE_CODE) != page_code)
7043 			continue;
7044 
7045 		/* Look for the right subpage or the subpage wildcard*/
7046 		if (page_index->subpage != subpage)
7047 			continue;
7048 
7049 		break;
7050 	}
7051 	if (i >= CTL_NUM_LOG_PAGES) {
7052 		ctl_set_invalid_field(ctsio,
7053 				      /*sks_valid*/ 1,
7054 				      /*command*/ 1,
7055 				      /*field*/ 2,
7056 				      /*bit_valid*/ 0,
7057 				      /*bit*/ 0);
7058 		ctl_done((union ctl_io *)ctsio);
7059 		return (CTL_RETVAL_COMPLETE);
7060 	}
7061 
7062 	total_len = sizeof(struct scsi_log_header) + page_index->page_len;
7063 
7064 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7065 	ctsio->kern_sg_entries = 0;
7066 	ctsio->kern_data_resid = 0;
7067 	ctsio->kern_rel_offset = 0;
7068 	if (total_len < alloc_len) {
7069 		ctsio->residual = alloc_len - total_len;
7070 		ctsio->kern_data_len = total_len;
7071 		ctsio->kern_total_len = total_len;
7072 	} else {
7073 		ctsio->residual = 0;
7074 		ctsio->kern_data_len = alloc_len;
7075 		ctsio->kern_total_len = alloc_len;
7076 	}
7077 
7078 	header = (struct scsi_log_header *)ctsio->kern_data_ptr;
7079 	header->page = page_index->page_code;
7080 	if (page_index->subpage) {
7081 		header->page |= SL_SPF;
7082 		header->subpage = page_index->subpage;
7083 	}
7084 	scsi_ulto2b(page_index->page_len, header->datalen);
7085 
7086 	/*
7087 	 * Call the handler, if it exists, to update the
7088 	 * page to the latest values.
7089 	 */
7090 	if (page_index->sense_handler != NULL)
7091 		page_index->sense_handler(ctsio, page_index, pc);
7092 
7093 	memcpy(header + 1, page_index->page_data, page_index->page_len);
7094 
7095 	ctl_set_success(ctsio);
7096 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7097 	ctsio->be_move_done = ctl_config_move_done;
7098 	ctl_datamove((union ctl_io *)ctsio);
7099 	return (CTL_RETVAL_COMPLETE);
7100 }
7101 
7102 int
7103 ctl_read_capacity(struct ctl_scsiio *ctsio)
7104 {
7105 	struct scsi_read_capacity *cdb;
7106 	struct scsi_read_capacity_data *data;
7107 	struct ctl_lun *lun;
7108 	uint32_t lba;
7109 
7110 	CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
7111 
7112 	cdb = (struct scsi_read_capacity *)ctsio->cdb;
7113 
7114 	lba = scsi_4btoul(cdb->addr);
7115 	if (((cdb->pmi & SRC_PMI) == 0)
7116 	 && (lba != 0)) {
7117 		ctl_set_invalid_field(/*ctsio*/ ctsio,
7118 				      /*sks_valid*/ 1,
7119 				      /*command*/ 1,
7120 				      /*field*/ 2,
7121 				      /*bit_valid*/ 0,
7122 				      /*bit*/ 0);
7123 		ctl_done((union ctl_io *)ctsio);
7124 		return (CTL_RETVAL_COMPLETE);
7125 	}
7126 
7127 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7128 
7129 	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7130 	data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
7131 	ctsio->residual = 0;
7132 	ctsio->kern_data_len = sizeof(*data);
7133 	ctsio->kern_total_len = sizeof(*data);
7134 	ctsio->kern_data_resid = 0;
7135 	ctsio->kern_rel_offset = 0;
7136 	ctsio->kern_sg_entries = 0;
7137 
7138 	/*
7139 	 * If the maximum LBA is greater than 0xfffffffe, the user must
7140 	 * issue a SERVICE ACTION IN (16) command, with the read capacity
7141 	 * serivce action set.
7142 	 */
7143 	if (lun->be_lun->maxlba > 0xfffffffe)
7144 		scsi_ulto4b(0xffffffff, data->addr);
7145 	else
7146 		scsi_ulto4b(lun->be_lun->maxlba, data->addr);
7147 
7148 	/*
7149 	 * XXX KDM this may not be 512 bytes...
7150 	 */
7151 	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7152 
7153 	ctl_set_success(ctsio);
7154 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7155 	ctsio->be_move_done = ctl_config_move_done;
7156 	ctl_datamove((union ctl_io *)ctsio);
7157 	return (CTL_RETVAL_COMPLETE);
7158 }
7159 
7160 int
7161 ctl_read_capacity_16(struct ctl_scsiio *ctsio)
7162 {
7163 	struct scsi_read_capacity_16 *cdb;
7164 	struct scsi_read_capacity_data_long *data;
7165 	struct ctl_lun *lun;
7166 	uint64_t lba;
7167 	uint32_t alloc_len;
7168 
7169 	CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
7170 
7171 	cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
7172 
7173 	alloc_len = scsi_4btoul(cdb->alloc_len);
7174 	lba = scsi_8btou64(cdb->addr);
7175 
7176 	if ((cdb->reladr & SRC16_PMI)
7177 	 && (lba != 0)) {
7178 		ctl_set_invalid_field(/*ctsio*/ ctsio,
7179 				      /*sks_valid*/ 1,
7180 				      /*command*/ 1,
7181 				      /*field*/ 2,
7182 				      /*bit_valid*/ 0,
7183 				      /*bit*/ 0);
7184 		ctl_done((union ctl_io *)ctsio);
7185 		return (CTL_RETVAL_COMPLETE);
7186 	}
7187 
7188 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7189 
7190 	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7191 	data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
7192 
7193 	if (sizeof(*data) < alloc_len) {
7194 		ctsio->residual = alloc_len - sizeof(*data);
7195 		ctsio->kern_data_len = sizeof(*data);
7196 		ctsio->kern_total_len = sizeof(*data);
7197 	} else {
7198 		ctsio->residual = 0;
7199 		ctsio->kern_data_len = alloc_len;
7200 		ctsio->kern_total_len = alloc_len;
7201 	}
7202 	ctsio->kern_data_resid = 0;
7203 	ctsio->kern_rel_offset = 0;
7204 	ctsio->kern_sg_entries = 0;
7205 
7206 	scsi_u64to8b(lun->be_lun->maxlba, data->addr);
7207 	/* XXX KDM this may not be 512 bytes... */
7208 	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7209 	data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
7210 	scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
7211 	if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
7212 		data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
7213 
7214 	ctl_set_success(ctsio);
7215 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7216 	ctsio->be_move_done = ctl_config_move_done;
7217 	ctl_datamove((union ctl_io *)ctsio);
7218 	return (CTL_RETVAL_COMPLETE);
7219 }
7220 
7221 int
7222 ctl_get_lba_status(struct ctl_scsiio *ctsio)
7223 {
7224 	struct scsi_get_lba_status *cdb;
7225 	struct scsi_get_lba_status_data *data;
7226 	struct ctl_lun *lun;
7227 	struct ctl_lba_len_flags *lbalen;
7228 	uint64_t lba;
7229 	uint32_t alloc_len, total_len;
7230 	int retval;
7231 
7232 	CTL_DEBUG_PRINT(("ctl_get_lba_status\n"));
7233 
7234 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7235 	cdb = (struct scsi_get_lba_status *)ctsio->cdb;
7236 	lba = scsi_8btou64(cdb->addr);
7237 	alloc_len = scsi_4btoul(cdb->alloc_len);
7238 
7239 	if (lba > lun->be_lun->maxlba) {
7240 		ctl_set_lba_out_of_range(ctsio);
7241 		ctl_done((union ctl_io *)ctsio);
7242 		return (CTL_RETVAL_COMPLETE);
7243 	}
7244 
7245 	total_len = sizeof(*data) + sizeof(data->descr[0]);
7246 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7247 	data = (struct scsi_get_lba_status_data *)ctsio->kern_data_ptr;
7248 
7249 	if (total_len < alloc_len) {
7250 		ctsio->residual = alloc_len - total_len;
7251 		ctsio->kern_data_len = total_len;
7252 		ctsio->kern_total_len = total_len;
7253 	} else {
7254 		ctsio->residual = 0;
7255 		ctsio->kern_data_len = alloc_len;
7256 		ctsio->kern_total_len = alloc_len;
7257 	}
7258 	ctsio->kern_data_resid = 0;
7259 	ctsio->kern_rel_offset = 0;
7260 	ctsio->kern_sg_entries = 0;
7261 
7262 	/* Fill dummy data in case backend can't tell anything. */
7263 	scsi_ulto4b(4 + sizeof(data->descr[0]), data->length);
7264 	scsi_u64to8b(lba, data->descr[0].addr);
7265 	scsi_ulto4b(MIN(UINT32_MAX, lun->be_lun->maxlba + 1 - lba),
7266 	    data->descr[0].length);
7267 	data->descr[0].status = 0; /* Mapped or unknown. */
7268 
7269 	ctl_set_success(ctsio);
7270 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7271 	ctsio->be_move_done = ctl_config_move_done;
7272 
7273 	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
7274 	lbalen->lba = lba;
7275 	lbalen->len = total_len;
7276 	lbalen->flags = 0;
7277 	retval = lun->backend->config_read((union ctl_io *)ctsio);
7278 	return (CTL_RETVAL_COMPLETE);
7279 }
7280 
7281 int
7282 ctl_read_defect(struct ctl_scsiio *ctsio)
7283 {
7284 	struct scsi_read_defect_data_10 *ccb10;
7285 	struct scsi_read_defect_data_12 *ccb12;
7286 	struct scsi_read_defect_data_hdr_10 *data10;
7287 	struct scsi_read_defect_data_hdr_12 *data12;
7288 	uint32_t alloc_len, data_len;
7289 	uint8_t format;
7290 
7291 	CTL_DEBUG_PRINT(("ctl_read_defect\n"));
7292 
7293 	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7294 		ccb10 = (struct scsi_read_defect_data_10 *)&ctsio->cdb;
7295 		format = ccb10->format;
7296 		alloc_len = scsi_2btoul(ccb10->alloc_length);
7297 		data_len = sizeof(*data10);
7298 	} else {
7299 		ccb12 = (struct scsi_read_defect_data_12 *)&ctsio->cdb;
7300 		format = ccb12->format;
7301 		alloc_len = scsi_4btoul(ccb12->alloc_length);
7302 		data_len = sizeof(*data12);
7303 	}
7304 	if (alloc_len == 0) {
7305 		ctl_set_success(ctsio);
7306 		ctl_done((union ctl_io *)ctsio);
7307 		return (CTL_RETVAL_COMPLETE);
7308 	}
7309 
7310 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
7311 	if (data_len < alloc_len) {
7312 		ctsio->residual = alloc_len - data_len;
7313 		ctsio->kern_data_len = data_len;
7314 		ctsio->kern_total_len = data_len;
7315 	} else {
7316 		ctsio->residual = 0;
7317 		ctsio->kern_data_len = alloc_len;
7318 		ctsio->kern_total_len = alloc_len;
7319 	}
7320 	ctsio->kern_data_resid = 0;
7321 	ctsio->kern_rel_offset = 0;
7322 	ctsio->kern_sg_entries = 0;
7323 
7324 	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7325 		data10 = (struct scsi_read_defect_data_hdr_10 *)
7326 		    ctsio->kern_data_ptr;
7327 		data10->format = format;
7328 		scsi_ulto2b(0, data10->length);
7329 	} else {
7330 		data12 = (struct scsi_read_defect_data_hdr_12 *)
7331 		    ctsio->kern_data_ptr;
7332 		data12->format = format;
7333 		scsi_ulto2b(0, data12->generation);
7334 		scsi_ulto4b(0, data12->length);
7335 	}
7336 
7337 	ctl_set_success(ctsio);
7338 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7339 	ctsio->be_move_done = ctl_config_move_done;
7340 	ctl_datamove((union ctl_io *)ctsio);
7341 	return (CTL_RETVAL_COMPLETE);
7342 }
7343 
7344 int
7345 ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7346 {
7347 	struct scsi_maintenance_in *cdb;
7348 	int retval;
7349 	int alloc_len, ext, total_len = 0, g, p, pc, pg, gs, os;
7350 	int num_target_port_groups, num_target_ports;
7351 	struct ctl_lun *lun;
7352 	struct ctl_softc *softc;
7353 	struct ctl_port *port;
7354 	struct scsi_target_group_data *rtg_ptr;
7355 	struct scsi_target_group_data_extended *rtg_ext_ptr;
7356 	struct scsi_target_port_group_descriptor *tpg_desc;
7357 
7358 	CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7359 
7360 	cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7361 	softc = control_softc;
7362 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7363 
7364 	retval = CTL_RETVAL_COMPLETE;
7365 
7366 	switch (cdb->byte2 & STG_PDF_MASK) {
7367 	case STG_PDF_LENGTH:
7368 		ext = 0;
7369 		break;
7370 	case STG_PDF_EXTENDED:
7371 		ext = 1;
7372 		break;
7373 	default:
7374 		ctl_set_invalid_field(/*ctsio*/ ctsio,
7375 				      /*sks_valid*/ 1,
7376 				      /*command*/ 1,
7377 				      /*field*/ 2,
7378 				      /*bit_valid*/ 1,
7379 				      /*bit*/ 5);
7380 		ctl_done((union ctl_io *)ctsio);
7381 		return(retval);
7382 	}
7383 
7384 	if (softc->is_single)
7385 		num_target_port_groups = 1;
7386 	else
7387 		num_target_port_groups = NUM_TARGET_PORT_GROUPS;
7388 	num_target_ports = 0;
7389 	mtx_lock(&softc->ctl_lock);
7390 	STAILQ_FOREACH(port, &softc->port_list, links) {
7391 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7392 			continue;
7393 		if (ctl_map_lun_back(port->targ_port, lun->lun) >= CTL_MAX_LUNS)
7394 			continue;
7395 		num_target_ports++;
7396 	}
7397 	mtx_unlock(&softc->ctl_lock);
7398 
7399 	if (ext)
7400 		total_len = sizeof(struct scsi_target_group_data_extended);
7401 	else
7402 		total_len = sizeof(struct scsi_target_group_data);
7403 	total_len += sizeof(struct scsi_target_port_group_descriptor) *
7404 		num_target_port_groups +
7405 	    sizeof(struct scsi_target_port_descriptor) *
7406 		num_target_ports * num_target_port_groups;
7407 
7408 	alloc_len = scsi_4btoul(cdb->length);
7409 
7410 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7411 
7412 	ctsio->kern_sg_entries = 0;
7413 
7414 	if (total_len < alloc_len) {
7415 		ctsio->residual = alloc_len - total_len;
7416 		ctsio->kern_data_len = total_len;
7417 		ctsio->kern_total_len = total_len;
7418 	} else {
7419 		ctsio->residual = 0;
7420 		ctsio->kern_data_len = alloc_len;
7421 		ctsio->kern_total_len = alloc_len;
7422 	}
7423 	ctsio->kern_data_resid = 0;
7424 	ctsio->kern_rel_offset = 0;
7425 
7426 	if (ext) {
7427 		rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7428 		    ctsio->kern_data_ptr;
7429 		scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7430 		rtg_ext_ptr->format_type = 0x10;
7431 		rtg_ext_ptr->implicit_transition_time = 0;
7432 		tpg_desc = &rtg_ext_ptr->groups[0];
7433 	} else {
7434 		rtg_ptr = (struct scsi_target_group_data *)
7435 		    ctsio->kern_data_ptr;
7436 		scsi_ulto4b(total_len - 4, rtg_ptr->length);
7437 		tpg_desc = &rtg_ptr->groups[0];
7438 	}
7439 
7440 	mtx_lock(&softc->ctl_lock);
7441 	pg = softc->port_offset / CTL_MAX_PORTS;
7442 	if (softc->flags & CTL_FLAG_ACTIVE_SHELF) {
7443 		if (softc->ha_mode == CTL_HA_MODE_ACT_STBY) {
7444 			gs = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7445 			os = TPG_ASYMMETRIC_ACCESS_STANDBY;
7446 		} else if (lun->flags & CTL_LUN_PRIMARY_SC) {
7447 			gs = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7448 			os = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7449 		} else {
7450 			gs = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7451 			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7452 		}
7453 	} else {
7454 		gs = TPG_ASYMMETRIC_ACCESS_STANDBY;
7455 		os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7456 	}
7457 	for (g = 0; g < num_target_port_groups; g++) {
7458 		tpg_desc->pref_state = (g == pg) ? gs : os;
7459 		tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP;
7460 		scsi_ulto2b(g + 1, tpg_desc->target_port_group);
7461 		tpg_desc->status = TPG_IMPLICIT;
7462 		pc = 0;
7463 		STAILQ_FOREACH(port, &softc->port_list, links) {
7464 			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7465 				continue;
7466 			if (ctl_map_lun_back(port->targ_port, lun->lun) >=
7467 			    CTL_MAX_LUNS)
7468 				continue;
7469 			p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
7470 			scsi_ulto2b(p, tpg_desc->descriptors[pc].
7471 			    relative_target_port_identifier);
7472 			pc++;
7473 		}
7474 		tpg_desc->target_port_count = pc;
7475 		tpg_desc = (struct scsi_target_port_group_descriptor *)
7476 		    &tpg_desc->descriptors[pc];
7477 	}
7478 	mtx_unlock(&softc->ctl_lock);
7479 
7480 	ctl_set_success(ctsio);
7481 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7482 	ctsio->be_move_done = ctl_config_move_done;
7483 	ctl_datamove((union ctl_io *)ctsio);
7484 	return(retval);
7485 }
7486 
7487 int
7488 ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7489 {
7490 	struct ctl_lun *lun;
7491 	struct scsi_report_supported_opcodes *cdb;
7492 	const struct ctl_cmd_entry *entry, *sentry;
7493 	struct scsi_report_supported_opcodes_all *all;
7494 	struct scsi_report_supported_opcodes_descr *descr;
7495 	struct scsi_report_supported_opcodes_one *one;
7496 	int retval;
7497 	int alloc_len, total_len;
7498 	int opcode, service_action, i, j, num;
7499 
7500 	CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7501 
7502 	cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7503 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7504 
7505 	retval = CTL_RETVAL_COMPLETE;
7506 
7507 	opcode = cdb->requested_opcode;
7508 	service_action = scsi_2btoul(cdb->requested_service_action);
7509 	switch (cdb->options & RSO_OPTIONS_MASK) {
7510 	case RSO_OPTIONS_ALL:
7511 		num = 0;
7512 		for (i = 0; i < 256; i++) {
7513 			entry = &ctl_cmd_table[i];
7514 			if (entry->flags & CTL_CMD_FLAG_SA5) {
7515 				for (j = 0; j < 32; j++) {
7516 					sentry = &((const struct ctl_cmd_entry *)
7517 					    entry->execute)[j];
7518 					if (ctl_cmd_applicable(
7519 					    lun->be_lun->lun_type, sentry))
7520 						num++;
7521 				}
7522 			} else {
7523 				if (ctl_cmd_applicable(lun->be_lun->lun_type,
7524 				    entry))
7525 					num++;
7526 			}
7527 		}
7528 		total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7529 		    num * sizeof(struct scsi_report_supported_opcodes_descr);
7530 		break;
7531 	case RSO_OPTIONS_OC:
7532 		if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7533 			ctl_set_invalid_field(/*ctsio*/ ctsio,
7534 					      /*sks_valid*/ 1,
7535 					      /*command*/ 1,
7536 					      /*field*/ 2,
7537 					      /*bit_valid*/ 1,
7538 					      /*bit*/ 2);
7539 			ctl_done((union ctl_io *)ctsio);
7540 			return (CTL_RETVAL_COMPLETE);
7541 		}
7542 		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7543 		break;
7544 	case RSO_OPTIONS_OC_SA:
7545 		if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7546 		    service_action >= 32) {
7547 			ctl_set_invalid_field(/*ctsio*/ ctsio,
7548 					      /*sks_valid*/ 1,
7549 					      /*command*/ 1,
7550 					      /*field*/ 2,
7551 					      /*bit_valid*/ 1,
7552 					      /*bit*/ 2);
7553 			ctl_done((union ctl_io *)ctsio);
7554 			return (CTL_RETVAL_COMPLETE);
7555 		}
7556 		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7557 		break;
7558 	default:
7559 		ctl_set_invalid_field(/*ctsio*/ ctsio,
7560 				      /*sks_valid*/ 1,
7561 				      /*command*/ 1,
7562 				      /*field*/ 2,
7563 				      /*bit_valid*/ 1,
7564 				      /*bit*/ 2);
7565 		ctl_done((union ctl_io *)ctsio);
7566 		return (CTL_RETVAL_COMPLETE);
7567 	}
7568 
7569 	alloc_len = scsi_4btoul(cdb->length);
7570 
7571 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7572 
7573 	ctsio->kern_sg_entries = 0;
7574 
7575 	if (total_len < alloc_len) {
7576 		ctsio->residual = alloc_len - total_len;
7577 		ctsio->kern_data_len = total_len;
7578 		ctsio->kern_total_len = total_len;
7579 	} else {
7580 		ctsio->residual = 0;
7581 		ctsio->kern_data_len = alloc_len;
7582 		ctsio->kern_total_len = alloc_len;
7583 	}
7584 	ctsio->kern_data_resid = 0;
7585 	ctsio->kern_rel_offset = 0;
7586 
7587 	switch (cdb->options & RSO_OPTIONS_MASK) {
7588 	case RSO_OPTIONS_ALL:
7589 		all = (struct scsi_report_supported_opcodes_all *)
7590 		    ctsio->kern_data_ptr;
7591 		num = 0;
7592 		for (i = 0; i < 256; i++) {
7593 			entry = &ctl_cmd_table[i];
7594 			if (entry->flags & CTL_CMD_FLAG_SA5) {
7595 				for (j = 0; j < 32; j++) {
7596 					sentry = &((const struct ctl_cmd_entry *)
7597 					    entry->execute)[j];
7598 					if (!ctl_cmd_applicable(
7599 					    lun->be_lun->lun_type, sentry))
7600 						continue;
7601 					descr = &all->descr[num++];
7602 					descr->opcode = i;
7603 					scsi_ulto2b(j, descr->service_action);
7604 					descr->flags = RSO_SERVACTV;
7605 					scsi_ulto2b(sentry->length,
7606 					    descr->cdb_length);
7607 				}
7608 			} else {
7609 				if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7610 				    entry))
7611 					continue;
7612 				descr = &all->descr[num++];
7613 				descr->opcode = i;
7614 				scsi_ulto2b(0, descr->service_action);
7615 				descr->flags = 0;
7616 				scsi_ulto2b(entry->length, descr->cdb_length);
7617 			}
7618 		}
7619 		scsi_ulto4b(
7620 		    num * sizeof(struct scsi_report_supported_opcodes_descr),
7621 		    all->length);
7622 		break;
7623 	case RSO_OPTIONS_OC:
7624 		one = (struct scsi_report_supported_opcodes_one *)
7625 		    ctsio->kern_data_ptr;
7626 		entry = &ctl_cmd_table[opcode];
7627 		goto fill_one;
7628 	case RSO_OPTIONS_OC_SA:
7629 		one = (struct scsi_report_supported_opcodes_one *)
7630 		    ctsio->kern_data_ptr;
7631 		entry = &ctl_cmd_table[opcode];
7632 		entry = &((const struct ctl_cmd_entry *)
7633 		    entry->execute)[service_action];
7634 fill_one:
7635 		if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7636 			one->support = 3;
7637 			scsi_ulto2b(entry->length, one->cdb_length);
7638 			one->cdb_usage[0] = opcode;
7639 			memcpy(&one->cdb_usage[1], entry->usage,
7640 			    entry->length - 1);
7641 		} else
7642 			one->support = 1;
7643 		break;
7644 	}
7645 
7646 	ctl_set_success(ctsio);
7647 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7648 	ctsio->be_move_done = ctl_config_move_done;
7649 	ctl_datamove((union ctl_io *)ctsio);
7650 	return(retval);
7651 }
7652 
7653 int
7654 ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7655 {
7656 	struct scsi_report_supported_tmf *cdb;
7657 	struct scsi_report_supported_tmf_data *data;
7658 	int retval;
7659 	int alloc_len, total_len;
7660 
7661 	CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7662 
7663 	cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7664 
7665 	retval = CTL_RETVAL_COMPLETE;
7666 
7667 	total_len = sizeof(struct scsi_report_supported_tmf_data);
7668 	alloc_len = scsi_4btoul(cdb->length);
7669 
7670 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7671 
7672 	ctsio->kern_sg_entries = 0;
7673 
7674 	if (total_len < alloc_len) {
7675 		ctsio->residual = alloc_len - total_len;
7676 		ctsio->kern_data_len = total_len;
7677 		ctsio->kern_total_len = total_len;
7678 	} else {
7679 		ctsio->residual = 0;
7680 		ctsio->kern_data_len = alloc_len;
7681 		ctsio->kern_total_len = alloc_len;
7682 	}
7683 	ctsio->kern_data_resid = 0;
7684 	ctsio->kern_rel_offset = 0;
7685 
7686 	data = (struct scsi_report_supported_tmf_data *)ctsio->kern_data_ptr;
7687 	data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_TRS;
7688 	data->byte2 |= RST_ITNRS;
7689 
7690 	ctl_set_success(ctsio);
7691 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7692 	ctsio->be_move_done = ctl_config_move_done;
7693 	ctl_datamove((union ctl_io *)ctsio);
7694 	return (retval);
7695 }
7696 
7697 int
7698 ctl_report_timestamp(struct ctl_scsiio *ctsio)
7699 {
7700 	struct scsi_report_timestamp *cdb;
7701 	struct scsi_report_timestamp_data *data;
7702 	struct timeval tv;
7703 	int64_t timestamp;
7704 	int retval;
7705 	int alloc_len, total_len;
7706 
7707 	CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7708 
7709 	cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7710 
7711 	retval = CTL_RETVAL_COMPLETE;
7712 
7713 	total_len = sizeof(struct scsi_report_timestamp_data);
7714 	alloc_len = scsi_4btoul(cdb->length);
7715 
7716 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7717 
7718 	ctsio->kern_sg_entries = 0;
7719 
7720 	if (total_len < alloc_len) {
7721 		ctsio->residual = alloc_len - total_len;
7722 		ctsio->kern_data_len = total_len;
7723 		ctsio->kern_total_len = total_len;
7724 	} else {
7725 		ctsio->residual = 0;
7726 		ctsio->kern_data_len = alloc_len;
7727 		ctsio->kern_total_len = alloc_len;
7728 	}
7729 	ctsio->kern_data_resid = 0;
7730 	ctsio->kern_rel_offset = 0;
7731 
7732 	data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7733 	scsi_ulto2b(sizeof(*data) - 2, data->length);
7734 	data->origin = RTS_ORIG_OUTSIDE;
7735 	getmicrotime(&tv);
7736 	timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7737 	scsi_ulto4b(timestamp >> 16, data->timestamp);
7738 	scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7739 
7740 	ctl_set_success(ctsio);
7741 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7742 	ctsio->be_move_done = ctl_config_move_done;
7743 	ctl_datamove((union ctl_io *)ctsio);
7744 	return (retval);
7745 }
7746 
7747 int
7748 ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7749 {
7750 	struct scsi_per_res_in *cdb;
7751 	int alloc_len, total_len = 0;
7752 	/* struct scsi_per_res_in_rsrv in_data; */
7753 	struct ctl_lun *lun;
7754 	struct ctl_softc *softc;
7755 	uint64_t key;
7756 
7757 	CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7758 
7759 	softc = control_softc;
7760 
7761 	cdb = (struct scsi_per_res_in *)ctsio->cdb;
7762 
7763 	alloc_len = scsi_2btoul(cdb->length);
7764 
7765 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7766 
7767 retry:
7768 	mtx_lock(&lun->lun_lock);
7769 	switch (cdb->action) {
7770 	case SPRI_RK: /* read keys */
7771 		total_len = sizeof(struct scsi_per_res_in_keys) +
7772 			lun->pr_key_count *
7773 			sizeof(struct scsi_per_res_key);
7774 		break;
7775 	case SPRI_RR: /* read reservation */
7776 		if (lun->flags & CTL_LUN_PR_RESERVED)
7777 			total_len = sizeof(struct scsi_per_res_in_rsrv);
7778 		else
7779 			total_len = sizeof(struct scsi_per_res_in_header);
7780 		break;
7781 	case SPRI_RC: /* report capabilities */
7782 		total_len = sizeof(struct scsi_per_res_cap);
7783 		break;
7784 	case SPRI_RS: /* read full status */
7785 		total_len = sizeof(struct scsi_per_res_in_header) +
7786 		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7787 		    lun->pr_key_count;
7788 		break;
7789 	default:
7790 		panic("Invalid PR type %x", cdb->action);
7791 	}
7792 	mtx_unlock(&lun->lun_lock);
7793 
7794 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7795 
7796 	if (total_len < alloc_len) {
7797 		ctsio->residual = alloc_len - total_len;
7798 		ctsio->kern_data_len = total_len;
7799 		ctsio->kern_total_len = total_len;
7800 	} else {
7801 		ctsio->residual = 0;
7802 		ctsio->kern_data_len = alloc_len;
7803 		ctsio->kern_total_len = alloc_len;
7804 	}
7805 
7806 	ctsio->kern_data_resid = 0;
7807 	ctsio->kern_rel_offset = 0;
7808 	ctsio->kern_sg_entries = 0;
7809 
7810 	mtx_lock(&lun->lun_lock);
7811 	switch (cdb->action) {
7812 	case SPRI_RK: { // read keys
7813         struct scsi_per_res_in_keys *res_keys;
7814 		int i, key_count;
7815 
7816 		res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7817 
7818 		/*
7819 		 * We had to drop the lock to allocate our buffer, which
7820 		 * leaves time for someone to come in with another
7821 		 * persistent reservation.  (That is unlikely, though,
7822 		 * since this should be the only persistent reservation
7823 		 * command active right now.)
7824 		 */
7825 		if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7826 		    (lun->pr_key_count *
7827 		     sizeof(struct scsi_per_res_key)))){
7828 			mtx_unlock(&lun->lun_lock);
7829 			free(ctsio->kern_data_ptr, M_CTL);
7830 			printf("%s: reservation length changed, retrying\n",
7831 			       __func__);
7832 			goto retry;
7833 		}
7834 
7835 		scsi_ulto4b(lun->PRGeneration, res_keys->header.generation);
7836 
7837 		scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7838 			     lun->pr_key_count, res_keys->header.length);
7839 
7840 		for (i = 0, key_count = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7841 			if ((key = ctl_get_prkey(lun, i)) == 0)
7842 				continue;
7843 
7844 			/*
7845 			 * We used lun->pr_key_count to calculate the
7846 			 * size to allocate.  If it turns out the number of
7847 			 * initiators with the registered flag set is
7848 			 * larger than that (i.e. they haven't been kept in
7849 			 * sync), we've got a problem.
7850 			 */
7851 			if (key_count >= lun->pr_key_count) {
7852 #ifdef NEEDTOPORT
7853 				csevent_log(CSC_CTL | CSC_SHELF_SW |
7854 					    CTL_PR_ERROR,
7855 					    csevent_LogType_Fault,
7856 					    csevent_AlertLevel_Yellow,
7857 					    csevent_FRU_ShelfController,
7858 					    csevent_FRU_Firmware,
7859 				        csevent_FRU_Unknown,
7860 					    "registered keys %d >= key "
7861 					    "count %d", key_count,
7862 					    lun->pr_key_count);
7863 #endif
7864 				key_count++;
7865 				continue;
7866 			}
7867 			scsi_u64to8b(key, res_keys->keys[key_count].key);
7868 			key_count++;
7869 		}
7870 		break;
7871 	}
7872 	case SPRI_RR: { // read reservation
7873 		struct scsi_per_res_in_rsrv *res;
7874 		int tmp_len, header_only;
7875 
7876 		res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7877 
7878 		scsi_ulto4b(lun->PRGeneration, res->header.generation);
7879 
7880 		if (lun->flags & CTL_LUN_PR_RESERVED)
7881 		{
7882 			tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7883 			scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7884 				    res->header.length);
7885 			header_only = 0;
7886 		} else {
7887 			tmp_len = sizeof(struct scsi_per_res_in_header);
7888 			scsi_ulto4b(0, res->header.length);
7889 			header_only = 1;
7890 		}
7891 
7892 		/*
7893 		 * We had to drop the lock to allocate our buffer, which
7894 		 * leaves time for someone to come in with another
7895 		 * persistent reservation.  (That is unlikely, though,
7896 		 * since this should be the only persistent reservation
7897 		 * command active right now.)
7898 		 */
7899 		if (tmp_len != total_len) {
7900 			mtx_unlock(&lun->lun_lock);
7901 			free(ctsio->kern_data_ptr, M_CTL);
7902 			printf("%s: reservation status changed, retrying\n",
7903 			       __func__);
7904 			goto retry;
7905 		}
7906 
7907 		/*
7908 		 * No reservation held, so we're done.
7909 		 */
7910 		if (header_only != 0)
7911 			break;
7912 
7913 		/*
7914 		 * If the registration is an All Registrants type, the key
7915 		 * is 0, since it doesn't really matter.
7916 		 */
7917 		if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7918 			scsi_u64to8b(ctl_get_prkey(lun, lun->pr_res_idx),
7919 			    res->data.reservation);
7920 		}
7921 		res->data.scopetype = lun->res_type;
7922 		break;
7923 	}
7924 	case SPRI_RC:     //report capabilities
7925 	{
7926 		struct scsi_per_res_cap *res_cap;
7927 		uint16_t type_mask;
7928 
7929 		res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7930 		scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7931 		res_cap->flags2 |= SPRI_TMV | SPRI_ALLOW_5;
7932 		type_mask = SPRI_TM_WR_EX_AR |
7933 			    SPRI_TM_EX_AC_RO |
7934 			    SPRI_TM_WR_EX_RO |
7935 			    SPRI_TM_EX_AC |
7936 			    SPRI_TM_WR_EX |
7937 			    SPRI_TM_EX_AC_AR;
7938 		scsi_ulto2b(type_mask, res_cap->type_mask);
7939 		break;
7940 	}
7941 	case SPRI_RS: { // read full status
7942 		struct scsi_per_res_in_full *res_status;
7943 		struct scsi_per_res_in_full_desc *res_desc;
7944 		struct ctl_port *port;
7945 		int i, len;
7946 
7947 		res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7948 
7949 		/*
7950 		 * We had to drop the lock to allocate our buffer, which
7951 		 * leaves time for someone to come in with another
7952 		 * persistent reservation.  (That is unlikely, though,
7953 		 * since this should be the only persistent reservation
7954 		 * command active right now.)
7955 		 */
7956 		if (total_len < (sizeof(struct scsi_per_res_in_header) +
7957 		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7958 		     lun->pr_key_count)){
7959 			mtx_unlock(&lun->lun_lock);
7960 			free(ctsio->kern_data_ptr, M_CTL);
7961 			printf("%s: reservation length changed, retrying\n",
7962 			       __func__);
7963 			goto retry;
7964 		}
7965 
7966 		scsi_ulto4b(lun->PRGeneration, res_status->header.generation);
7967 
7968 		res_desc = &res_status->desc[0];
7969 		for (i = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7970 			if ((key = ctl_get_prkey(lun, i)) == 0)
7971 				continue;
7972 
7973 			scsi_u64to8b(key, res_desc->res_key.key);
7974 			if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7975 			    (lun->pr_res_idx == i ||
7976 			     lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7977 				res_desc->flags = SPRI_FULL_R_HOLDER;
7978 				res_desc->scopetype = lun->res_type;
7979 			}
7980 			scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7981 			    res_desc->rel_trgt_port_id);
7982 			len = 0;
7983 			port = softc->ctl_ports[
7984 			    ctl_port_idx(i / CTL_MAX_INIT_PER_PORT)];
7985 			if (port != NULL)
7986 				len = ctl_create_iid(port,
7987 				    i % CTL_MAX_INIT_PER_PORT,
7988 				    res_desc->transport_id);
7989 			scsi_ulto4b(len, res_desc->additional_length);
7990 			res_desc = (struct scsi_per_res_in_full_desc *)
7991 			    &res_desc->transport_id[len];
7992 		}
7993 		scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7994 		    res_status->header.length);
7995 		break;
7996 	}
7997 	default:
7998 		/*
7999 		 * This is a bug, because we just checked for this above,
8000 		 * and should have returned an error.
8001 		 */
8002 		panic("Invalid PR type %x", cdb->action);
8003 		break; /* NOTREACHED */
8004 	}
8005 	mtx_unlock(&lun->lun_lock);
8006 
8007 	ctl_set_success(ctsio);
8008 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8009 	ctsio->be_move_done = ctl_config_move_done;
8010 	ctl_datamove((union ctl_io *)ctsio);
8011 	return (CTL_RETVAL_COMPLETE);
8012 }
8013 
8014 static void
8015 ctl_est_res_ua(struct ctl_lun *lun, uint32_t residx, ctl_ua_type ua)
8016 {
8017 	int off = lun->ctl_softc->persis_offset;
8018 
8019 	if (residx >= off && residx < off + CTL_MAX_INITIATORS)
8020 		ctl_est_ua(lun, residx - off, ua);
8021 }
8022 
8023 /*
8024  * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
8025  * it should return.
8026  */
8027 static int
8028 ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
8029 		uint64_t sa_res_key, uint8_t type, uint32_t residx,
8030 		struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
8031 		struct scsi_per_res_out_parms* param)
8032 {
8033 	union ctl_ha_msg persis_io;
8034 	int retval, i;
8035 	int isc_retval;
8036 
8037 	retval = 0;
8038 
8039 	mtx_lock(&lun->lun_lock);
8040 	if (sa_res_key == 0) {
8041 		if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8042 			/* validate scope and type */
8043 			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8044 			     SPR_LU_SCOPE) {
8045 				mtx_unlock(&lun->lun_lock);
8046 				ctl_set_invalid_field(/*ctsio*/ ctsio,
8047 						      /*sks_valid*/ 1,
8048 						      /*command*/ 1,
8049 						      /*field*/ 2,
8050 						      /*bit_valid*/ 1,
8051 						      /*bit*/ 4);
8052 				ctl_done((union ctl_io *)ctsio);
8053 				return (1);
8054 			}
8055 
8056 		        if (type>8 || type==2 || type==4 || type==0) {
8057 				mtx_unlock(&lun->lun_lock);
8058 				ctl_set_invalid_field(/*ctsio*/ ctsio,
8059        	           				      /*sks_valid*/ 1,
8060 						      /*command*/ 1,
8061 						      /*field*/ 2,
8062 						      /*bit_valid*/ 1,
8063 						      /*bit*/ 0);
8064 				ctl_done((union ctl_io *)ctsio);
8065 				return (1);
8066 		        }
8067 
8068 			/*
8069 			 * Unregister everybody else and build UA for
8070 			 * them
8071 			 */
8072 			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8073 				if (i == residx || ctl_get_prkey(lun, i) == 0)
8074 					continue;
8075 
8076 				ctl_clr_prkey(lun, i);
8077 				ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8078 			}
8079 			lun->pr_key_count = 1;
8080 			lun->res_type = type;
8081 			if (lun->res_type != SPR_TYPE_WR_EX_AR
8082 			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8083 				lun->pr_res_idx = residx;
8084 
8085 			/* send msg to other side */
8086 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8087 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8088 			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8089 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8090 			persis_io.pr.pr_info.res_type = type;
8091 			memcpy(persis_io.pr.pr_info.sa_res_key,
8092 			       param->serv_act_res_key,
8093 			       sizeof(param->serv_act_res_key));
8094 			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8095 			     &persis_io, sizeof(persis_io), 0)) >
8096 			     CTL_HA_STATUS_SUCCESS) {
8097 				printf("CTL:Persis Out error returned "
8098 				       "from ctl_ha_msg_send %d\n",
8099 				       isc_retval);
8100 			}
8101 		} else {
8102 			/* not all registrants */
8103 			mtx_unlock(&lun->lun_lock);
8104 			free(ctsio->kern_data_ptr, M_CTL);
8105 			ctl_set_invalid_field(ctsio,
8106 					      /*sks_valid*/ 1,
8107 					      /*command*/ 0,
8108 					      /*field*/ 8,
8109 					      /*bit_valid*/ 0,
8110 					      /*bit*/ 0);
8111 			ctl_done((union ctl_io *)ctsio);
8112 			return (1);
8113 		}
8114 	} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8115 		|| !(lun->flags & CTL_LUN_PR_RESERVED)) {
8116 		int found = 0;
8117 
8118 		if (res_key == sa_res_key) {
8119 			/* special case */
8120 			/*
8121 			 * The spec implies this is not good but doesn't
8122 			 * say what to do. There are two choices either
8123 			 * generate a res conflict or check condition
8124 			 * with illegal field in parameter data. Since
8125 			 * that is what is done when the sa_res_key is
8126 			 * zero I'll take that approach since this has
8127 			 * to do with the sa_res_key.
8128 			 */
8129 			mtx_unlock(&lun->lun_lock);
8130 			free(ctsio->kern_data_ptr, M_CTL);
8131 			ctl_set_invalid_field(ctsio,
8132 					      /*sks_valid*/ 1,
8133 					      /*command*/ 0,
8134 					      /*field*/ 8,
8135 					      /*bit_valid*/ 0,
8136 					      /*bit*/ 0);
8137 			ctl_done((union ctl_io *)ctsio);
8138 			return (1);
8139 		}
8140 
8141 		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8142 			if (ctl_get_prkey(lun, i) != sa_res_key)
8143 				continue;
8144 
8145 			found = 1;
8146 			ctl_clr_prkey(lun, i);
8147 			lun->pr_key_count--;
8148 			ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8149 		}
8150 		if (!found) {
8151 			mtx_unlock(&lun->lun_lock);
8152 			free(ctsio->kern_data_ptr, M_CTL);
8153 			ctl_set_reservation_conflict(ctsio);
8154 			ctl_done((union ctl_io *)ctsio);
8155 			return (CTL_RETVAL_COMPLETE);
8156 		}
8157 		/* send msg to other side */
8158 		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8159 		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8160 		persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8161 		persis_io.pr.pr_info.residx = lun->pr_res_idx;
8162 		persis_io.pr.pr_info.res_type = type;
8163 		memcpy(persis_io.pr.pr_info.sa_res_key,
8164 		       param->serv_act_res_key,
8165 		       sizeof(param->serv_act_res_key));
8166 		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8167 		     &persis_io, sizeof(persis_io), 0)) >
8168 		     CTL_HA_STATUS_SUCCESS) {
8169 			printf("CTL:Persis Out error returned from "
8170 			       "ctl_ha_msg_send %d\n", isc_retval);
8171 		}
8172 	} else {
8173 		/* Reserved but not all registrants */
8174 		/* sa_res_key is res holder */
8175 		if (sa_res_key == ctl_get_prkey(lun, lun->pr_res_idx)) {
8176 			/* validate scope and type */
8177 			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8178 			     SPR_LU_SCOPE) {
8179 				mtx_unlock(&lun->lun_lock);
8180 				ctl_set_invalid_field(/*ctsio*/ ctsio,
8181 						      /*sks_valid*/ 1,
8182 						      /*command*/ 1,
8183 						      /*field*/ 2,
8184 						      /*bit_valid*/ 1,
8185 						      /*bit*/ 4);
8186 				ctl_done((union ctl_io *)ctsio);
8187 				return (1);
8188 			}
8189 
8190 			if (type>8 || type==2 || type==4 || type==0) {
8191 				mtx_unlock(&lun->lun_lock);
8192 				ctl_set_invalid_field(/*ctsio*/ ctsio,
8193 						      /*sks_valid*/ 1,
8194 						      /*command*/ 1,
8195 						      /*field*/ 2,
8196 						      /*bit_valid*/ 1,
8197 						      /*bit*/ 0);
8198 				ctl_done((union ctl_io *)ctsio);
8199 				return (1);
8200 			}
8201 
8202 			/*
8203 			 * Do the following:
8204 			 * if sa_res_key != res_key remove all
8205 			 * registrants w/sa_res_key and generate UA
8206 			 * for these registrants(Registrations
8207 			 * Preempted) if it wasn't an exclusive
8208 			 * reservation generate UA(Reservations
8209 			 * Preempted) for all other registered nexuses
8210 			 * if the type has changed. Establish the new
8211 			 * reservation and holder. If res_key and
8212 			 * sa_res_key are the same do the above
8213 			 * except don't unregister the res holder.
8214 			 */
8215 
8216 			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8217 				if (i == residx || ctl_get_prkey(lun, i) == 0)
8218 					continue;
8219 
8220 				if (sa_res_key == ctl_get_prkey(lun, i)) {
8221 					ctl_clr_prkey(lun, i);
8222 					lun->pr_key_count--;
8223 					ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8224 				} else if (type != lun->res_type
8225 					&& (lun->res_type == SPR_TYPE_WR_EX_RO
8226 					 || lun->res_type ==SPR_TYPE_EX_AC_RO)){
8227 					ctl_est_res_ua(lun, i, CTL_UA_RES_RELEASE);
8228 				}
8229 			}
8230 			lun->res_type = type;
8231 			if (lun->res_type != SPR_TYPE_WR_EX_AR
8232 			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8233 				lun->pr_res_idx = residx;
8234 			else
8235 				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8236 
8237 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8238 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8239 			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8240 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8241 			persis_io.pr.pr_info.res_type = type;
8242 			memcpy(persis_io.pr.pr_info.sa_res_key,
8243 			       param->serv_act_res_key,
8244 			       sizeof(param->serv_act_res_key));
8245 			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8246 			     &persis_io, sizeof(persis_io), 0)) >
8247 			     CTL_HA_STATUS_SUCCESS) {
8248 				printf("CTL:Persis Out error returned "
8249 				       "from ctl_ha_msg_send %d\n",
8250 				       isc_retval);
8251 			}
8252 		} else {
8253 			/*
8254 			 * sa_res_key is not the res holder just
8255 			 * remove registrants
8256 			 */
8257 			int found=0;
8258 
8259 			for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8260 				if (sa_res_key != ctl_get_prkey(lun, i))
8261 					continue;
8262 
8263 				found = 1;
8264 				ctl_clr_prkey(lun, i);
8265 				lun->pr_key_count--;
8266 				ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8267 			}
8268 
8269 			if (!found) {
8270 				mtx_unlock(&lun->lun_lock);
8271 				free(ctsio->kern_data_ptr, M_CTL);
8272 				ctl_set_reservation_conflict(ctsio);
8273 				ctl_done((union ctl_io *)ctsio);
8274 		        	return (1);
8275 			}
8276 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8277 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8278 			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8279 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8280 			persis_io.pr.pr_info.res_type = type;
8281 			memcpy(persis_io.pr.pr_info.sa_res_key,
8282 			       param->serv_act_res_key,
8283 			       sizeof(param->serv_act_res_key));
8284 			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8285 			     &persis_io, sizeof(persis_io), 0)) >
8286 			     CTL_HA_STATUS_SUCCESS) {
8287 				printf("CTL:Persis Out error returned "
8288 				       "from ctl_ha_msg_send %d\n",
8289 				isc_retval);
8290 			}
8291 		}
8292 	}
8293 
8294 	lun->PRGeneration++;
8295 	mtx_unlock(&lun->lun_lock);
8296 
8297 	return (retval);
8298 }
8299 
8300 static void
8301 ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8302 {
8303 	uint64_t sa_res_key;
8304 	int i;
8305 
8306 	sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8307 
8308 	if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8309 	 || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8310 	 || sa_res_key != ctl_get_prkey(lun, lun->pr_res_idx)) {
8311 		if (sa_res_key == 0) {
8312 			/*
8313 			 * Unregister everybody else and build UA for
8314 			 * them
8315 			 */
8316 			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8317 				if (i == msg->pr.pr_info.residx ||
8318 				    ctl_get_prkey(lun, i) == 0)
8319 					continue;
8320 
8321 				ctl_clr_prkey(lun, i);
8322 				ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8323 			}
8324 
8325 			lun->pr_key_count = 1;
8326 			lun->res_type = msg->pr.pr_info.res_type;
8327 			if (lun->res_type != SPR_TYPE_WR_EX_AR
8328 			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8329 				lun->pr_res_idx = msg->pr.pr_info.residx;
8330 		} else {
8331 		        for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8332 				if (sa_res_key == ctl_get_prkey(lun, i))
8333 					continue;
8334 
8335 				ctl_clr_prkey(lun, i);
8336 				lun->pr_key_count--;
8337 				ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8338 			}
8339 		}
8340 	} else {
8341 		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8342 			if (i == msg->pr.pr_info.residx ||
8343 			    ctl_get_prkey(lun, i) == 0)
8344 				continue;
8345 
8346 			if (sa_res_key == ctl_get_prkey(lun, i)) {
8347 				ctl_clr_prkey(lun, i);
8348 				lun->pr_key_count--;
8349 				ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8350 			} else if (msg->pr.pr_info.res_type != lun->res_type
8351 				&& (lun->res_type == SPR_TYPE_WR_EX_RO
8352 				 || lun->res_type == SPR_TYPE_EX_AC_RO)) {
8353 				ctl_est_res_ua(lun, i, CTL_UA_RES_RELEASE);
8354 			}
8355 		}
8356 		lun->res_type = msg->pr.pr_info.res_type;
8357 		if (lun->res_type != SPR_TYPE_WR_EX_AR
8358 		 && lun->res_type != SPR_TYPE_EX_AC_AR)
8359 			lun->pr_res_idx = msg->pr.pr_info.residx;
8360 		else
8361 			lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8362 	}
8363 	lun->PRGeneration++;
8364 
8365 }
8366 
8367 
8368 int
8369 ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8370 {
8371 	int retval;
8372 	int isc_retval;
8373 	u_int32_t param_len;
8374 	struct scsi_per_res_out *cdb;
8375 	struct ctl_lun *lun;
8376 	struct scsi_per_res_out_parms* param;
8377 	struct ctl_softc *softc;
8378 	uint32_t residx;
8379 	uint64_t res_key, sa_res_key, key;
8380 	uint8_t type;
8381 	union ctl_ha_msg persis_io;
8382 	int    i;
8383 
8384 	CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8385 
8386 	retval = CTL_RETVAL_COMPLETE;
8387 
8388 	softc = control_softc;
8389 
8390 	cdb = (struct scsi_per_res_out *)ctsio->cdb;
8391 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8392 
8393 	/*
8394 	 * We only support whole-LUN scope.  The scope & type are ignored for
8395 	 * register, register and ignore existing key and clear.
8396 	 * We sometimes ignore scope and type on preempts too!!
8397 	 * Verify reservation type here as well.
8398 	 */
8399 	type = cdb->scope_type & SPR_TYPE_MASK;
8400 	if ((cdb->action == SPRO_RESERVE)
8401 	 || (cdb->action == SPRO_RELEASE)) {
8402 		if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8403 			ctl_set_invalid_field(/*ctsio*/ ctsio,
8404 					      /*sks_valid*/ 1,
8405 					      /*command*/ 1,
8406 					      /*field*/ 2,
8407 					      /*bit_valid*/ 1,
8408 					      /*bit*/ 4);
8409 			ctl_done((union ctl_io *)ctsio);
8410 			return (CTL_RETVAL_COMPLETE);
8411 		}
8412 
8413 		if (type>8 || type==2 || type==4 || type==0) {
8414 			ctl_set_invalid_field(/*ctsio*/ ctsio,
8415 					      /*sks_valid*/ 1,
8416 					      /*command*/ 1,
8417 					      /*field*/ 2,
8418 					      /*bit_valid*/ 1,
8419 					      /*bit*/ 0);
8420 			ctl_done((union ctl_io *)ctsio);
8421 			return (CTL_RETVAL_COMPLETE);
8422 		}
8423 	}
8424 
8425 	param_len = scsi_4btoul(cdb->length);
8426 
8427 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8428 		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8429 		ctsio->kern_data_len = param_len;
8430 		ctsio->kern_total_len = param_len;
8431 		ctsio->kern_data_resid = 0;
8432 		ctsio->kern_rel_offset = 0;
8433 		ctsio->kern_sg_entries = 0;
8434 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8435 		ctsio->be_move_done = ctl_config_move_done;
8436 		ctl_datamove((union ctl_io *)ctsio);
8437 
8438 		return (CTL_RETVAL_COMPLETE);
8439 	}
8440 
8441 	param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8442 
8443 	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
8444 	res_key = scsi_8btou64(param->res_key.key);
8445 	sa_res_key = scsi_8btou64(param->serv_act_res_key);
8446 
8447 	/*
8448 	 * Validate the reservation key here except for SPRO_REG_IGNO
8449 	 * This must be done for all other service actions
8450 	 */
8451 	if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8452 		mtx_lock(&lun->lun_lock);
8453 		if ((key = ctl_get_prkey(lun, residx)) != 0) {
8454 			if (res_key != key) {
8455 				/*
8456 				 * The current key passed in doesn't match
8457 				 * the one the initiator previously
8458 				 * registered.
8459 				 */
8460 				mtx_unlock(&lun->lun_lock);
8461 				free(ctsio->kern_data_ptr, M_CTL);
8462 				ctl_set_reservation_conflict(ctsio);
8463 				ctl_done((union ctl_io *)ctsio);
8464 				return (CTL_RETVAL_COMPLETE);
8465 			}
8466 		} else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8467 			/*
8468 			 * We are not registered
8469 			 */
8470 			mtx_unlock(&lun->lun_lock);
8471 			free(ctsio->kern_data_ptr, M_CTL);
8472 			ctl_set_reservation_conflict(ctsio);
8473 			ctl_done((union ctl_io *)ctsio);
8474 			return (CTL_RETVAL_COMPLETE);
8475 		} else if (res_key != 0) {
8476 			/*
8477 			 * We are not registered and trying to register but
8478 			 * the register key isn't zero.
8479 			 */
8480 			mtx_unlock(&lun->lun_lock);
8481 			free(ctsio->kern_data_ptr, M_CTL);
8482 			ctl_set_reservation_conflict(ctsio);
8483 			ctl_done((union ctl_io *)ctsio);
8484 			return (CTL_RETVAL_COMPLETE);
8485 		}
8486 		mtx_unlock(&lun->lun_lock);
8487 	}
8488 
8489 	switch (cdb->action & SPRO_ACTION_MASK) {
8490 	case SPRO_REGISTER:
8491 	case SPRO_REG_IGNO: {
8492 
8493 #if 0
8494 		printf("Registration received\n");
8495 #endif
8496 
8497 		/*
8498 		 * We don't support any of these options, as we report in
8499 		 * the read capabilities request (see
8500 		 * ctl_persistent_reserve_in(), above).
8501 		 */
8502 		if ((param->flags & SPR_SPEC_I_PT)
8503 		 || (param->flags & SPR_ALL_TG_PT)
8504 		 || (param->flags & SPR_APTPL)) {
8505 			int bit_ptr;
8506 
8507 			if (param->flags & SPR_APTPL)
8508 				bit_ptr = 0;
8509 			else if (param->flags & SPR_ALL_TG_PT)
8510 				bit_ptr = 2;
8511 			else /* SPR_SPEC_I_PT */
8512 				bit_ptr = 3;
8513 
8514 			free(ctsio->kern_data_ptr, M_CTL);
8515 			ctl_set_invalid_field(ctsio,
8516 					      /*sks_valid*/ 1,
8517 					      /*command*/ 0,
8518 					      /*field*/ 20,
8519 					      /*bit_valid*/ 1,
8520 					      /*bit*/ bit_ptr);
8521 			ctl_done((union ctl_io *)ctsio);
8522 			return (CTL_RETVAL_COMPLETE);
8523 		}
8524 
8525 		mtx_lock(&lun->lun_lock);
8526 
8527 		/*
8528 		 * The initiator wants to clear the
8529 		 * key/unregister.
8530 		 */
8531 		if (sa_res_key == 0) {
8532 			if ((res_key == 0
8533 			  && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8534 			 || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8535 			  && ctl_get_prkey(lun, residx) == 0)) {
8536 				mtx_unlock(&lun->lun_lock);
8537 				goto done;
8538 			}
8539 
8540 			ctl_clr_prkey(lun, residx);
8541 			lun->pr_key_count--;
8542 
8543 			if (residx == lun->pr_res_idx) {
8544 				lun->flags &= ~CTL_LUN_PR_RESERVED;
8545 				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8546 
8547 				if ((lun->res_type == SPR_TYPE_WR_EX_RO
8548 				  || lun->res_type == SPR_TYPE_EX_AC_RO)
8549 				 && lun->pr_key_count) {
8550 					/*
8551 					 * If the reservation is a registrants
8552 					 * only type we need to generate a UA
8553 					 * for other registered inits.  The
8554 					 * sense code should be RESERVATIONS
8555 					 * RELEASED
8556 					 */
8557 
8558 					for (i = 0; i < CTL_MAX_INITIATORS;i++){
8559 						if (ctl_get_prkey(lun, i +
8560 						    softc->persis_offset) == 0)
8561 							continue;
8562 						ctl_est_ua(lun, i,
8563 						    CTL_UA_RES_RELEASE);
8564 					}
8565 				}
8566 				lun->res_type = 0;
8567 			} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8568 				if (lun->pr_key_count==0) {
8569 					lun->flags &= ~CTL_LUN_PR_RESERVED;
8570 					lun->res_type = 0;
8571 					lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8572 				}
8573 			}
8574 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8575 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8576 			persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8577 			persis_io.pr.pr_info.residx = residx;
8578 			if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8579 			     &persis_io, sizeof(persis_io), 0 )) >
8580 			     CTL_HA_STATUS_SUCCESS) {
8581 				printf("CTL:Persis Out error returned from "
8582 				       "ctl_ha_msg_send %d\n", isc_retval);
8583 			}
8584 		} else /* sa_res_key != 0 */ {
8585 
8586 			/*
8587 			 * If we aren't registered currently then increment
8588 			 * the key count and set the registered flag.
8589 			 */
8590 			ctl_alloc_prkey(lun, residx);
8591 			if (ctl_get_prkey(lun, residx) == 0)
8592 				lun->pr_key_count++;
8593 			ctl_set_prkey(lun, residx, sa_res_key);
8594 
8595 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8596 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8597 			persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8598 			persis_io.pr.pr_info.residx = residx;
8599 			memcpy(persis_io.pr.pr_info.sa_res_key,
8600 			       param->serv_act_res_key,
8601 			       sizeof(param->serv_act_res_key));
8602 			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8603 			     &persis_io, sizeof(persis_io), 0)) >
8604 			     CTL_HA_STATUS_SUCCESS) {
8605 				printf("CTL:Persis Out error returned from "
8606 				       "ctl_ha_msg_send %d\n", isc_retval);
8607 			}
8608 		}
8609 		lun->PRGeneration++;
8610 		mtx_unlock(&lun->lun_lock);
8611 
8612 		break;
8613 	}
8614 	case SPRO_RESERVE:
8615 #if 0
8616                 printf("Reserve executed type %d\n", type);
8617 #endif
8618 		mtx_lock(&lun->lun_lock);
8619 		if (lun->flags & CTL_LUN_PR_RESERVED) {
8620 			/*
8621 			 * if this isn't the reservation holder and it's
8622 			 * not a "all registrants" type or if the type is
8623 			 * different then we have a conflict
8624 			 */
8625 			if ((lun->pr_res_idx != residx
8626 			  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8627 			 || lun->res_type != type) {
8628 				mtx_unlock(&lun->lun_lock);
8629 				free(ctsio->kern_data_ptr, M_CTL);
8630 				ctl_set_reservation_conflict(ctsio);
8631 				ctl_done((union ctl_io *)ctsio);
8632 				return (CTL_RETVAL_COMPLETE);
8633 			}
8634 			mtx_unlock(&lun->lun_lock);
8635 		} else /* create a reservation */ {
8636 			/*
8637 			 * If it's not an "all registrants" type record
8638 			 * reservation holder
8639 			 */
8640 			if (type != SPR_TYPE_WR_EX_AR
8641 			 && type != SPR_TYPE_EX_AC_AR)
8642 				lun->pr_res_idx = residx; /* Res holder */
8643 			else
8644 				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8645 
8646 			lun->flags |= CTL_LUN_PR_RESERVED;
8647 			lun->res_type = type;
8648 
8649 			mtx_unlock(&lun->lun_lock);
8650 
8651 			/* send msg to other side */
8652 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8653 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8654 			persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8655 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8656 			persis_io.pr.pr_info.res_type = type;
8657 			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8658 			     &persis_io, sizeof(persis_io), 0)) >
8659 			     CTL_HA_STATUS_SUCCESS) {
8660 				printf("CTL:Persis Out error returned from "
8661 				       "ctl_ha_msg_send %d\n", isc_retval);
8662 			}
8663 		}
8664 		break;
8665 
8666 	case SPRO_RELEASE:
8667 		mtx_lock(&lun->lun_lock);
8668 		if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8669 			/* No reservation exists return good status */
8670 			mtx_unlock(&lun->lun_lock);
8671 			goto done;
8672 		}
8673 		/*
8674 		 * Is this nexus a reservation holder?
8675 		 */
8676 		if (lun->pr_res_idx != residx
8677 		 && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8678 			/*
8679 			 * not a res holder return good status but
8680 			 * do nothing
8681 			 */
8682 			mtx_unlock(&lun->lun_lock);
8683 			goto done;
8684 		}
8685 
8686 		if (lun->res_type != type) {
8687 			mtx_unlock(&lun->lun_lock);
8688 			free(ctsio->kern_data_ptr, M_CTL);
8689 			ctl_set_illegal_pr_release(ctsio);
8690 			ctl_done((union ctl_io *)ctsio);
8691 			return (CTL_RETVAL_COMPLETE);
8692 		}
8693 
8694 		/* okay to release */
8695 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8696 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8697 		lun->res_type = 0;
8698 
8699 		/*
8700 		 * if this isn't an exclusive access
8701 		 * res generate UA for all other
8702 		 * registrants.
8703 		 */
8704 		if (type != SPR_TYPE_EX_AC
8705 		 && type != SPR_TYPE_WR_EX) {
8706 			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8707 				if (i == residx ||
8708 				    ctl_get_prkey(lun,
8709 				     i + softc->persis_offset) == 0)
8710 					continue;
8711 				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8712 			}
8713 		}
8714 		mtx_unlock(&lun->lun_lock);
8715 		/* Send msg to other side */
8716 		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8717 		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8718 		persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8719 		if ((isc_retval=ctl_ha_msg_send( CTL_HA_CHAN_CTL, &persis_io,
8720 		     sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8721 			printf("CTL:Persis Out error returned from "
8722 			       "ctl_ha_msg_send %d\n", isc_retval);
8723 		}
8724 		break;
8725 
8726 	case SPRO_CLEAR:
8727 		/* send msg to other side */
8728 
8729 		mtx_lock(&lun->lun_lock);
8730 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8731 		lun->res_type = 0;
8732 		lun->pr_key_count = 0;
8733 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8734 
8735 		ctl_clr_prkey(lun, residx);
8736 		for (i=0; i < 2*CTL_MAX_INITIATORS; i++)
8737 			if (ctl_get_prkey(lun, i) != 0) {
8738 				ctl_clr_prkey(lun, i);
8739 				ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8740 			}
8741 		lun->PRGeneration++;
8742 		mtx_unlock(&lun->lun_lock);
8743 		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8744 		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8745 		persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8746 		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8747 		     sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8748 			printf("CTL:Persis Out error returned from "
8749 			       "ctl_ha_msg_send %d\n", isc_retval);
8750 		}
8751 		break;
8752 
8753 	case SPRO_PREEMPT:
8754 	case SPRO_PRE_ABO: {
8755 		int nretval;
8756 
8757 		nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8758 					  residx, ctsio, cdb, param);
8759 		if (nretval != 0)
8760 			return (CTL_RETVAL_COMPLETE);
8761 		break;
8762 	}
8763 	default:
8764 		panic("Invalid PR type %x", cdb->action);
8765 	}
8766 
8767 done:
8768 	free(ctsio->kern_data_ptr, M_CTL);
8769 	ctl_set_success(ctsio);
8770 	ctl_done((union ctl_io *)ctsio);
8771 
8772 	return (retval);
8773 }
8774 
8775 /*
8776  * This routine is for handling a message from the other SC pertaining to
8777  * persistent reserve out. All the error checking will have been done
8778  * so only perorming the action need be done here to keep the two
8779  * in sync.
8780  */
8781 static void
8782 ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg)
8783 {
8784 	struct ctl_lun *lun;
8785 	struct ctl_softc *softc;
8786 	int i;
8787 	uint32_t targ_lun;
8788 
8789 	softc = control_softc;
8790 
8791 	targ_lun = msg->hdr.nexus.targ_mapped_lun;
8792 	lun = softc->ctl_luns[targ_lun];
8793 	mtx_lock(&lun->lun_lock);
8794 	switch(msg->pr.pr_info.action) {
8795 	case CTL_PR_REG_KEY:
8796 		ctl_alloc_prkey(lun, msg->pr.pr_info.residx);
8797 		if (ctl_get_prkey(lun, msg->pr.pr_info.residx) == 0)
8798 			lun->pr_key_count++;
8799 		ctl_set_prkey(lun, msg->pr.pr_info.residx,
8800 		    scsi_8btou64(msg->pr.pr_info.sa_res_key));
8801 		lun->PRGeneration++;
8802 		break;
8803 
8804 	case CTL_PR_UNREG_KEY:
8805 		ctl_clr_prkey(lun, msg->pr.pr_info.residx);
8806 		lun->pr_key_count--;
8807 
8808 		/* XXX Need to see if the reservation has been released */
8809 		/* if so do we need to generate UA? */
8810 		if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8811 			lun->flags &= ~CTL_LUN_PR_RESERVED;
8812 			lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8813 
8814 			if ((lun->res_type == SPR_TYPE_WR_EX_RO
8815 			  || lun->res_type == SPR_TYPE_EX_AC_RO)
8816 			 && lun->pr_key_count) {
8817 				/*
8818 				 * If the reservation is a registrants
8819 				 * only type we need to generate a UA
8820 				 * for other registered inits.  The
8821 				 * sense code should be RESERVATIONS
8822 				 * RELEASED
8823 				 */
8824 
8825 				for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8826 					if (ctl_get_prkey(lun, i +
8827 					    softc->persis_offset) == 0)
8828 						continue;
8829 
8830 					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8831 				}
8832 			}
8833 			lun->res_type = 0;
8834 		} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8835 			if (lun->pr_key_count==0) {
8836 				lun->flags &= ~CTL_LUN_PR_RESERVED;
8837 				lun->res_type = 0;
8838 				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8839 			}
8840 		}
8841 		lun->PRGeneration++;
8842 		break;
8843 
8844 	case CTL_PR_RESERVE:
8845 		lun->flags |= CTL_LUN_PR_RESERVED;
8846 		lun->res_type = msg->pr.pr_info.res_type;
8847 		lun->pr_res_idx = msg->pr.pr_info.residx;
8848 
8849 		break;
8850 
8851 	case CTL_PR_RELEASE:
8852 		/*
8853 		 * if this isn't an exclusive access res generate UA for all
8854 		 * other registrants.
8855 		 */
8856 		if (lun->res_type != SPR_TYPE_EX_AC
8857 		 && lun->res_type != SPR_TYPE_WR_EX) {
8858 			for (i = 0; i < CTL_MAX_INITIATORS; i++)
8859 				if (ctl_get_prkey(lun, i + softc->persis_offset) != 0)
8860 					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8861 		}
8862 
8863 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8864 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8865 		lun->res_type = 0;
8866 		break;
8867 
8868 	case CTL_PR_PREEMPT:
8869 		ctl_pro_preempt_other(lun, msg);
8870 		break;
8871 	case CTL_PR_CLEAR:
8872 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8873 		lun->res_type = 0;
8874 		lun->pr_key_count = 0;
8875 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8876 
8877 		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8878 			if (ctl_get_prkey(lun, i) == 0)
8879 				continue;
8880 			ctl_clr_prkey(lun, i);
8881 			ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8882 		}
8883 		lun->PRGeneration++;
8884 		break;
8885 	}
8886 
8887 	mtx_unlock(&lun->lun_lock);
8888 }
8889 
8890 int
8891 ctl_read_write(struct ctl_scsiio *ctsio)
8892 {
8893 	struct ctl_lun *lun;
8894 	struct ctl_lba_len_flags *lbalen;
8895 	uint64_t lba;
8896 	uint32_t num_blocks;
8897 	int flags, retval;
8898 	int isread;
8899 
8900 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8901 
8902 	CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8903 
8904 	flags = 0;
8905 	retval = CTL_RETVAL_COMPLETE;
8906 
8907 	isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8908 	      || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8909 	switch (ctsio->cdb[0]) {
8910 	case READ_6:
8911 	case WRITE_6: {
8912 		struct scsi_rw_6 *cdb;
8913 
8914 		cdb = (struct scsi_rw_6 *)ctsio->cdb;
8915 
8916 		lba = scsi_3btoul(cdb->addr);
8917 		/* only 5 bits are valid in the most significant address byte */
8918 		lba &= 0x1fffff;
8919 		num_blocks = cdb->length;
8920 		/*
8921 		 * This is correct according to SBC-2.
8922 		 */
8923 		if (num_blocks == 0)
8924 			num_blocks = 256;
8925 		break;
8926 	}
8927 	case READ_10:
8928 	case WRITE_10: {
8929 		struct scsi_rw_10 *cdb;
8930 
8931 		cdb = (struct scsi_rw_10 *)ctsio->cdb;
8932 		if (cdb->byte2 & SRW10_FUA)
8933 			flags |= CTL_LLF_FUA;
8934 		if (cdb->byte2 & SRW10_DPO)
8935 			flags |= CTL_LLF_DPO;
8936 		lba = scsi_4btoul(cdb->addr);
8937 		num_blocks = scsi_2btoul(cdb->length);
8938 		break;
8939 	}
8940 	case WRITE_VERIFY_10: {
8941 		struct scsi_write_verify_10 *cdb;
8942 
8943 		cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
8944 		flags |= CTL_LLF_FUA;
8945 		if (cdb->byte2 & SWV_DPO)
8946 			flags |= CTL_LLF_DPO;
8947 		lba = scsi_4btoul(cdb->addr);
8948 		num_blocks = scsi_2btoul(cdb->length);
8949 		break;
8950 	}
8951 	case READ_12:
8952 	case WRITE_12: {
8953 		struct scsi_rw_12 *cdb;
8954 
8955 		cdb = (struct scsi_rw_12 *)ctsio->cdb;
8956 		if (cdb->byte2 & SRW12_FUA)
8957 			flags |= CTL_LLF_FUA;
8958 		if (cdb->byte2 & SRW12_DPO)
8959 			flags |= CTL_LLF_DPO;
8960 		lba = scsi_4btoul(cdb->addr);
8961 		num_blocks = scsi_4btoul(cdb->length);
8962 		break;
8963 	}
8964 	case WRITE_VERIFY_12: {
8965 		struct scsi_write_verify_12 *cdb;
8966 
8967 		cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
8968 		flags |= CTL_LLF_FUA;
8969 		if (cdb->byte2 & SWV_DPO)
8970 			flags |= CTL_LLF_DPO;
8971 		lba = scsi_4btoul(cdb->addr);
8972 		num_blocks = scsi_4btoul(cdb->length);
8973 		break;
8974 	}
8975 	case READ_16:
8976 	case WRITE_16: {
8977 		struct scsi_rw_16 *cdb;
8978 
8979 		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8980 		if (cdb->byte2 & SRW12_FUA)
8981 			flags |= CTL_LLF_FUA;
8982 		if (cdb->byte2 & SRW12_DPO)
8983 			flags |= CTL_LLF_DPO;
8984 		lba = scsi_8btou64(cdb->addr);
8985 		num_blocks = scsi_4btoul(cdb->length);
8986 		break;
8987 	}
8988 	case WRITE_ATOMIC_16: {
8989 		struct scsi_rw_16 *cdb;
8990 
8991 		if (lun->be_lun->atomicblock == 0) {
8992 			ctl_set_invalid_opcode(ctsio);
8993 			ctl_done((union ctl_io *)ctsio);
8994 			return (CTL_RETVAL_COMPLETE);
8995 		}
8996 
8997 		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8998 		if (cdb->byte2 & SRW12_FUA)
8999 			flags |= CTL_LLF_FUA;
9000 		if (cdb->byte2 & SRW12_DPO)
9001 			flags |= CTL_LLF_DPO;
9002 		lba = scsi_8btou64(cdb->addr);
9003 		num_blocks = scsi_4btoul(cdb->length);
9004 		if (num_blocks > lun->be_lun->atomicblock) {
9005 			ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
9006 			    /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
9007 			    /*bit*/ 0);
9008 			ctl_done((union ctl_io *)ctsio);
9009 			return (CTL_RETVAL_COMPLETE);
9010 		}
9011 		break;
9012 	}
9013 	case WRITE_VERIFY_16: {
9014 		struct scsi_write_verify_16 *cdb;
9015 
9016 		cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
9017 		flags |= CTL_LLF_FUA;
9018 		if (cdb->byte2 & SWV_DPO)
9019 			flags |= CTL_LLF_DPO;
9020 		lba = scsi_8btou64(cdb->addr);
9021 		num_blocks = scsi_4btoul(cdb->length);
9022 		break;
9023 	}
9024 	default:
9025 		/*
9026 		 * We got a command we don't support.  This shouldn't
9027 		 * happen, commands should be filtered out above us.
9028 		 */
9029 		ctl_set_invalid_opcode(ctsio);
9030 		ctl_done((union ctl_io *)ctsio);
9031 
9032 		return (CTL_RETVAL_COMPLETE);
9033 		break; /* NOTREACHED */
9034 	}
9035 
9036 	/*
9037 	 * The first check is to make sure we're in bounds, the second
9038 	 * check is to catch wrap-around problems.  If the lba + num blocks
9039 	 * is less than the lba, then we've wrapped around and the block
9040 	 * range is invalid anyway.
9041 	 */
9042 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9043 	 || ((lba + num_blocks) < lba)) {
9044 		ctl_set_lba_out_of_range(ctsio);
9045 		ctl_done((union ctl_io *)ctsio);
9046 		return (CTL_RETVAL_COMPLETE);
9047 	}
9048 
9049 	/*
9050 	 * According to SBC-3, a transfer length of 0 is not an error.
9051 	 * Note that this cannot happen with WRITE(6) or READ(6), since 0
9052 	 * translates to 256 blocks for those commands.
9053 	 */
9054 	if (num_blocks == 0) {
9055 		ctl_set_success(ctsio);
9056 		ctl_done((union ctl_io *)ctsio);
9057 		return (CTL_RETVAL_COMPLETE);
9058 	}
9059 
9060 	/* Set FUA and/or DPO if caches are disabled. */
9061 	if (isread) {
9062 		if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9063 		    SCP_RCD) != 0)
9064 			flags |= CTL_LLF_FUA | CTL_LLF_DPO;
9065 	} else {
9066 		if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9067 		    SCP_WCE) == 0)
9068 			flags |= CTL_LLF_FUA;
9069 	}
9070 
9071 	lbalen = (struct ctl_lba_len_flags *)
9072 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9073 	lbalen->lba = lba;
9074 	lbalen->len = num_blocks;
9075 	lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
9076 
9077 	ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9078 	ctsio->kern_rel_offset = 0;
9079 
9080 	CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
9081 
9082 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9083 
9084 	return (retval);
9085 }
9086 
9087 static int
9088 ctl_cnw_cont(union ctl_io *io)
9089 {
9090 	struct ctl_scsiio *ctsio;
9091 	struct ctl_lun *lun;
9092 	struct ctl_lba_len_flags *lbalen;
9093 	int retval;
9094 
9095 	ctsio = &io->scsiio;
9096 	ctsio->io_hdr.status = CTL_STATUS_NONE;
9097 	ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
9098 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9099 	lbalen = (struct ctl_lba_len_flags *)
9100 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9101 	lbalen->flags &= ~CTL_LLF_COMPARE;
9102 	lbalen->flags |= CTL_LLF_WRITE;
9103 
9104 	CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
9105 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9106 	return (retval);
9107 }
9108 
9109 int
9110 ctl_cnw(struct ctl_scsiio *ctsio)
9111 {
9112 	struct ctl_lun *lun;
9113 	struct ctl_lba_len_flags *lbalen;
9114 	uint64_t lba;
9115 	uint32_t num_blocks;
9116 	int flags, retval;
9117 
9118 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9119 
9120 	CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
9121 
9122 	flags = 0;
9123 	retval = CTL_RETVAL_COMPLETE;
9124 
9125 	switch (ctsio->cdb[0]) {
9126 	case COMPARE_AND_WRITE: {
9127 		struct scsi_compare_and_write *cdb;
9128 
9129 		cdb = (struct scsi_compare_and_write *)ctsio->cdb;
9130 		if (cdb->byte2 & SRW10_FUA)
9131 			flags |= CTL_LLF_FUA;
9132 		if (cdb->byte2 & SRW10_DPO)
9133 			flags |= CTL_LLF_DPO;
9134 		lba = scsi_8btou64(cdb->addr);
9135 		num_blocks = cdb->length;
9136 		break;
9137 	}
9138 	default:
9139 		/*
9140 		 * We got a command we don't support.  This shouldn't
9141 		 * happen, commands should be filtered out above us.
9142 		 */
9143 		ctl_set_invalid_opcode(ctsio);
9144 		ctl_done((union ctl_io *)ctsio);
9145 
9146 		return (CTL_RETVAL_COMPLETE);
9147 		break; /* NOTREACHED */
9148 	}
9149 
9150 	/*
9151 	 * The first check is to make sure we're in bounds, the second
9152 	 * check is to catch wrap-around problems.  If the lba + num blocks
9153 	 * is less than the lba, then we've wrapped around and the block
9154 	 * range is invalid anyway.
9155 	 */
9156 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9157 	 || ((lba + num_blocks) < lba)) {
9158 		ctl_set_lba_out_of_range(ctsio);
9159 		ctl_done((union ctl_io *)ctsio);
9160 		return (CTL_RETVAL_COMPLETE);
9161 	}
9162 
9163 	/*
9164 	 * According to SBC-3, a transfer length of 0 is not an error.
9165 	 */
9166 	if (num_blocks == 0) {
9167 		ctl_set_success(ctsio);
9168 		ctl_done((union ctl_io *)ctsio);
9169 		return (CTL_RETVAL_COMPLETE);
9170 	}
9171 
9172 	/* Set FUA if write cache is disabled. */
9173 	if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9174 	    SCP_WCE) == 0)
9175 		flags |= CTL_LLF_FUA;
9176 
9177 	ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
9178 	ctsio->kern_rel_offset = 0;
9179 
9180 	/*
9181 	 * Set the IO_CONT flag, so that if this I/O gets passed to
9182 	 * ctl_data_submit_done(), it'll get passed back to
9183 	 * ctl_ctl_cnw_cont() for further processing.
9184 	 */
9185 	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
9186 	ctsio->io_cont = ctl_cnw_cont;
9187 
9188 	lbalen = (struct ctl_lba_len_flags *)
9189 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9190 	lbalen->lba = lba;
9191 	lbalen->len = num_blocks;
9192 	lbalen->flags = CTL_LLF_COMPARE | flags;
9193 
9194 	CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
9195 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9196 	return (retval);
9197 }
9198 
9199 int
9200 ctl_verify(struct ctl_scsiio *ctsio)
9201 {
9202 	struct ctl_lun *lun;
9203 	struct ctl_lba_len_flags *lbalen;
9204 	uint64_t lba;
9205 	uint32_t num_blocks;
9206 	int bytchk, flags;
9207 	int retval;
9208 
9209 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9210 
9211 	CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
9212 
9213 	bytchk = 0;
9214 	flags = CTL_LLF_FUA;
9215 	retval = CTL_RETVAL_COMPLETE;
9216 
9217 	switch (ctsio->cdb[0]) {
9218 	case VERIFY_10: {
9219 		struct scsi_verify_10 *cdb;
9220 
9221 		cdb = (struct scsi_verify_10 *)ctsio->cdb;
9222 		if (cdb->byte2 & SVFY_BYTCHK)
9223 			bytchk = 1;
9224 		if (cdb->byte2 & SVFY_DPO)
9225 			flags |= CTL_LLF_DPO;
9226 		lba = scsi_4btoul(cdb->addr);
9227 		num_blocks = scsi_2btoul(cdb->length);
9228 		break;
9229 	}
9230 	case VERIFY_12: {
9231 		struct scsi_verify_12 *cdb;
9232 
9233 		cdb = (struct scsi_verify_12 *)ctsio->cdb;
9234 		if (cdb->byte2 & SVFY_BYTCHK)
9235 			bytchk = 1;
9236 		if (cdb->byte2 & SVFY_DPO)
9237 			flags |= CTL_LLF_DPO;
9238 		lba = scsi_4btoul(cdb->addr);
9239 		num_blocks = scsi_4btoul(cdb->length);
9240 		break;
9241 	}
9242 	case VERIFY_16: {
9243 		struct scsi_rw_16 *cdb;
9244 
9245 		cdb = (struct scsi_rw_16 *)ctsio->cdb;
9246 		if (cdb->byte2 & SVFY_BYTCHK)
9247 			bytchk = 1;
9248 		if (cdb->byte2 & SVFY_DPO)
9249 			flags |= CTL_LLF_DPO;
9250 		lba = scsi_8btou64(cdb->addr);
9251 		num_blocks = scsi_4btoul(cdb->length);
9252 		break;
9253 	}
9254 	default:
9255 		/*
9256 		 * We got a command we don't support.  This shouldn't
9257 		 * happen, commands should be filtered out above us.
9258 		 */
9259 		ctl_set_invalid_opcode(ctsio);
9260 		ctl_done((union ctl_io *)ctsio);
9261 		return (CTL_RETVAL_COMPLETE);
9262 	}
9263 
9264 	/*
9265 	 * The first check is to make sure we're in bounds, the second
9266 	 * check is to catch wrap-around problems.  If the lba + num blocks
9267 	 * is less than the lba, then we've wrapped around and the block
9268 	 * range is invalid anyway.
9269 	 */
9270 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9271 	 || ((lba + num_blocks) < lba)) {
9272 		ctl_set_lba_out_of_range(ctsio);
9273 		ctl_done((union ctl_io *)ctsio);
9274 		return (CTL_RETVAL_COMPLETE);
9275 	}
9276 
9277 	/*
9278 	 * According to SBC-3, a transfer length of 0 is not an error.
9279 	 */
9280 	if (num_blocks == 0) {
9281 		ctl_set_success(ctsio);
9282 		ctl_done((union ctl_io *)ctsio);
9283 		return (CTL_RETVAL_COMPLETE);
9284 	}
9285 
9286 	lbalen = (struct ctl_lba_len_flags *)
9287 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9288 	lbalen->lba = lba;
9289 	lbalen->len = num_blocks;
9290 	if (bytchk) {
9291 		lbalen->flags = CTL_LLF_COMPARE | flags;
9292 		ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9293 	} else {
9294 		lbalen->flags = CTL_LLF_VERIFY | flags;
9295 		ctsio->kern_total_len = 0;
9296 	}
9297 	ctsio->kern_rel_offset = 0;
9298 
9299 	CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9300 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9301 	return (retval);
9302 }
9303 
9304 int
9305 ctl_report_luns(struct ctl_scsiio *ctsio)
9306 {
9307 	struct scsi_report_luns *cdb;
9308 	struct scsi_report_luns_data *lun_data;
9309 	struct ctl_lun *lun, *request_lun;
9310 	int num_luns, retval;
9311 	uint32_t alloc_len, lun_datalen;
9312 	int num_filled, well_known;
9313 	uint32_t initidx, targ_lun_id, lun_id;
9314 
9315 	retval = CTL_RETVAL_COMPLETE;
9316 	well_known = 0;
9317 
9318 	cdb = (struct scsi_report_luns *)ctsio->cdb;
9319 
9320 	CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9321 
9322 	mtx_lock(&control_softc->ctl_lock);
9323 	num_luns = control_softc->num_luns;
9324 	mtx_unlock(&control_softc->ctl_lock);
9325 
9326 	switch (cdb->select_report) {
9327 	case RPL_REPORT_DEFAULT:
9328 	case RPL_REPORT_ALL:
9329 		break;
9330 	case RPL_REPORT_WELLKNOWN:
9331 		well_known = 1;
9332 		num_luns = 0;
9333 		break;
9334 	default:
9335 		ctl_set_invalid_field(ctsio,
9336 				      /*sks_valid*/ 1,
9337 				      /*command*/ 1,
9338 				      /*field*/ 2,
9339 				      /*bit_valid*/ 0,
9340 				      /*bit*/ 0);
9341 		ctl_done((union ctl_io *)ctsio);
9342 		return (retval);
9343 		break; /* NOTREACHED */
9344 	}
9345 
9346 	alloc_len = scsi_4btoul(cdb->length);
9347 	/*
9348 	 * The initiator has to allocate at least 16 bytes for this request,
9349 	 * so he can at least get the header and the first LUN.  Otherwise
9350 	 * we reject the request (per SPC-3 rev 14, section 6.21).
9351 	 */
9352 	if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9353 	    sizeof(struct scsi_report_luns_lundata))) {
9354 		ctl_set_invalid_field(ctsio,
9355 				      /*sks_valid*/ 1,
9356 				      /*command*/ 1,
9357 				      /*field*/ 6,
9358 				      /*bit_valid*/ 0,
9359 				      /*bit*/ 0);
9360 		ctl_done((union ctl_io *)ctsio);
9361 		return (retval);
9362 	}
9363 
9364 	request_lun = (struct ctl_lun *)
9365 		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9366 
9367 	lun_datalen = sizeof(*lun_data) +
9368 		(num_luns * sizeof(struct scsi_report_luns_lundata));
9369 
9370 	ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9371 	lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9372 	ctsio->kern_sg_entries = 0;
9373 
9374 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9375 
9376 	mtx_lock(&control_softc->ctl_lock);
9377 	for (targ_lun_id = 0, num_filled = 0; targ_lun_id < CTL_MAX_LUNS && num_filled < num_luns; targ_lun_id++) {
9378 		lun_id = ctl_map_lun(ctsio->io_hdr.nexus.targ_port, targ_lun_id);
9379 		if (lun_id >= CTL_MAX_LUNS)
9380 			continue;
9381 		lun = control_softc->ctl_luns[lun_id];
9382 		if (lun == NULL)
9383 			continue;
9384 
9385 		if (targ_lun_id <= 0xff) {
9386 			/*
9387 			 * Peripheral addressing method, bus number 0.
9388 			 */
9389 			lun_data->luns[num_filled].lundata[0] =
9390 				RPL_LUNDATA_ATYP_PERIPH;
9391 			lun_data->luns[num_filled].lundata[1] = targ_lun_id;
9392 			num_filled++;
9393 		} else if (targ_lun_id <= 0x3fff) {
9394 			/*
9395 			 * Flat addressing method.
9396 			 */
9397 			lun_data->luns[num_filled].lundata[0] =
9398 				RPL_LUNDATA_ATYP_FLAT | (targ_lun_id >> 8);
9399 			lun_data->luns[num_filled].lundata[1] =
9400 				(targ_lun_id & 0xff);
9401 			num_filled++;
9402 		} else if (targ_lun_id <= 0xffffff) {
9403 			/*
9404 			 * Extended flat addressing method.
9405 			 */
9406 			lun_data->luns[num_filled].lundata[0] =
9407 			    RPL_LUNDATA_ATYP_EXTLUN | 0x12;
9408 			scsi_ulto3b(targ_lun_id,
9409 			    &lun_data->luns[num_filled].lundata[1]);
9410 			num_filled++;
9411 		} else {
9412 			printf("ctl_report_luns: bogus LUN number %jd, "
9413 			       "skipping\n", (intmax_t)targ_lun_id);
9414 		}
9415 		/*
9416 		 * According to SPC-3, rev 14 section 6.21:
9417 		 *
9418 		 * "The execution of a REPORT LUNS command to any valid and
9419 		 * installed logical unit shall clear the REPORTED LUNS DATA
9420 		 * HAS CHANGED unit attention condition for all logical
9421 		 * units of that target with respect to the requesting
9422 		 * initiator. A valid and installed logical unit is one
9423 		 * having a PERIPHERAL QUALIFIER of 000b in the standard
9424 		 * INQUIRY data (see 6.4.2)."
9425 		 *
9426 		 * If request_lun is NULL, the LUN this report luns command
9427 		 * was issued to is either disabled or doesn't exist. In that
9428 		 * case, we shouldn't clear any pending lun change unit
9429 		 * attention.
9430 		 */
9431 		if (request_lun != NULL) {
9432 			mtx_lock(&lun->lun_lock);
9433 			ctl_clr_ua(lun, initidx, CTL_UA_RES_RELEASE);
9434 			mtx_unlock(&lun->lun_lock);
9435 		}
9436 	}
9437 	mtx_unlock(&control_softc->ctl_lock);
9438 
9439 	/*
9440 	 * It's quite possible that we've returned fewer LUNs than we allocated
9441 	 * space for.  Trim it.
9442 	 */
9443 	lun_datalen = sizeof(*lun_data) +
9444 		(num_filled * sizeof(struct scsi_report_luns_lundata));
9445 
9446 	if (lun_datalen < alloc_len) {
9447 		ctsio->residual = alloc_len - lun_datalen;
9448 		ctsio->kern_data_len = lun_datalen;
9449 		ctsio->kern_total_len = lun_datalen;
9450 	} else {
9451 		ctsio->residual = 0;
9452 		ctsio->kern_data_len = alloc_len;
9453 		ctsio->kern_total_len = alloc_len;
9454 	}
9455 	ctsio->kern_data_resid = 0;
9456 	ctsio->kern_rel_offset = 0;
9457 	ctsio->kern_sg_entries = 0;
9458 
9459 	/*
9460 	 * We set this to the actual data length, regardless of how much
9461 	 * space we actually have to return results.  If the user looks at
9462 	 * this value, he'll know whether or not he allocated enough space
9463 	 * and reissue the command if necessary.  We don't support well
9464 	 * known logical units, so if the user asks for that, return none.
9465 	 */
9466 	scsi_ulto4b(lun_datalen - 8, lun_data->length);
9467 
9468 	/*
9469 	 * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9470 	 * this request.
9471 	 */
9472 	ctl_set_success(ctsio);
9473 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9474 	ctsio->be_move_done = ctl_config_move_done;
9475 	ctl_datamove((union ctl_io *)ctsio);
9476 	return (retval);
9477 }
9478 
9479 int
9480 ctl_request_sense(struct ctl_scsiio *ctsio)
9481 {
9482 	struct scsi_request_sense *cdb;
9483 	struct scsi_sense_data *sense_ptr;
9484 	struct ctl_lun *lun;
9485 	uint32_t initidx;
9486 	int have_error;
9487 	scsi_sense_data_type sense_format;
9488 	ctl_ua_type ua_type;
9489 
9490 	cdb = (struct scsi_request_sense *)ctsio->cdb;
9491 
9492 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9493 
9494 	CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9495 
9496 	/*
9497 	 * Determine which sense format the user wants.
9498 	 */
9499 	if (cdb->byte2 & SRS_DESC)
9500 		sense_format = SSD_TYPE_DESC;
9501 	else
9502 		sense_format = SSD_TYPE_FIXED;
9503 
9504 	ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9505 	sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9506 	ctsio->kern_sg_entries = 0;
9507 
9508 	/*
9509 	 * struct scsi_sense_data, which is currently set to 256 bytes, is
9510 	 * larger than the largest allowed value for the length field in the
9511 	 * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9512 	 */
9513 	ctsio->residual = 0;
9514 	ctsio->kern_data_len = cdb->length;
9515 	ctsio->kern_total_len = cdb->length;
9516 
9517 	ctsio->kern_data_resid = 0;
9518 	ctsio->kern_rel_offset = 0;
9519 	ctsio->kern_sg_entries = 0;
9520 
9521 	/*
9522 	 * If we don't have a LUN, we don't have any pending sense.
9523 	 */
9524 	if (lun == NULL)
9525 		goto no_sense;
9526 
9527 	have_error = 0;
9528 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9529 	/*
9530 	 * Check for pending sense, and then for pending unit attentions.
9531 	 * Pending sense gets returned first, then pending unit attentions.
9532 	 */
9533 	mtx_lock(&lun->lun_lock);
9534 #ifdef CTL_WITH_CA
9535 	if (ctl_is_set(lun->have_ca, initidx)) {
9536 		scsi_sense_data_type stored_format;
9537 
9538 		/*
9539 		 * Check to see which sense format was used for the stored
9540 		 * sense data.
9541 		 */
9542 		stored_format = scsi_sense_type(&lun->pending_sense[initidx]);
9543 
9544 		/*
9545 		 * If the user requested a different sense format than the
9546 		 * one we stored, then we need to convert it to the other
9547 		 * format.  If we're going from descriptor to fixed format
9548 		 * sense data, we may lose things in translation, depending
9549 		 * on what options were used.
9550 		 *
9551 		 * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9552 		 * for some reason we'll just copy it out as-is.
9553 		 */
9554 		if ((stored_format == SSD_TYPE_FIXED)
9555 		 && (sense_format == SSD_TYPE_DESC))
9556 			ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9557 			    &lun->pending_sense[initidx],
9558 			    (struct scsi_sense_data_desc *)sense_ptr);
9559 		else if ((stored_format == SSD_TYPE_DESC)
9560 		      && (sense_format == SSD_TYPE_FIXED))
9561 			ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9562 			    &lun->pending_sense[initidx],
9563 			    (struct scsi_sense_data_fixed *)sense_ptr);
9564 		else
9565 			memcpy(sense_ptr, &lun->pending_sense[initidx],
9566 			       ctl_min(sizeof(*sense_ptr),
9567 			       sizeof(lun->pending_sense[initidx])));
9568 
9569 		ctl_clear_mask(lun->have_ca, initidx);
9570 		have_error = 1;
9571 	} else
9572 #endif
9573 	{
9574 		ua_type = ctl_build_ua(lun, initidx, sense_ptr, sense_format);
9575 		if (ua_type != CTL_UA_NONE)
9576 			have_error = 1;
9577 	}
9578 	mtx_unlock(&lun->lun_lock);
9579 
9580 	/*
9581 	 * We already have a pending error, return it.
9582 	 */
9583 	if (have_error != 0) {
9584 		/*
9585 		 * We report the SCSI status as OK, since the status of the
9586 		 * request sense command itself is OK.
9587 		 * We report 0 for the sense length, because we aren't doing
9588 		 * autosense in this case.  We're reporting sense as
9589 		 * parameter data.
9590 		 */
9591 		ctl_set_success(ctsio);
9592 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9593 		ctsio->be_move_done = ctl_config_move_done;
9594 		ctl_datamove((union ctl_io *)ctsio);
9595 		return (CTL_RETVAL_COMPLETE);
9596 	}
9597 
9598 no_sense:
9599 
9600 	/*
9601 	 * No sense information to report, so we report that everything is
9602 	 * okay.
9603 	 */
9604 	ctl_set_sense_data(sense_ptr,
9605 			   lun,
9606 			   sense_format,
9607 			   /*current_error*/ 1,
9608 			   /*sense_key*/ SSD_KEY_NO_SENSE,
9609 			   /*asc*/ 0x00,
9610 			   /*ascq*/ 0x00,
9611 			   SSD_ELEM_NONE);
9612 
9613 	/*
9614 	 * We report 0 for the sense length, because we aren't doing
9615 	 * autosense in this case.  We're reporting sense as parameter data.
9616 	 */
9617 	ctl_set_success(ctsio);
9618 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9619 	ctsio->be_move_done = ctl_config_move_done;
9620 	ctl_datamove((union ctl_io *)ctsio);
9621 	return (CTL_RETVAL_COMPLETE);
9622 }
9623 
9624 int
9625 ctl_tur(struct ctl_scsiio *ctsio)
9626 {
9627 
9628 	CTL_DEBUG_PRINT(("ctl_tur\n"));
9629 
9630 	ctl_set_success(ctsio);
9631 	ctl_done((union ctl_io *)ctsio);
9632 
9633 	return (CTL_RETVAL_COMPLETE);
9634 }
9635 
9636 #ifdef notyet
9637 static int
9638 ctl_cmddt_inquiry(struct ctl_scsiio *ctsio)
9639 {
9640 
9641 }
9642 #endif
9643 
9644 static int
9645 ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9646 {
9647 	struct scsi_vpd_supported_pages *pages;
9648 	int sup_page_size;
9649 	struct ctl_lun *lun;
9650 
9651 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9652 
9653 	sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9654 	    SCSI_EVPD_NUM_SUPPORTED_PAGES;
9655 	ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9656 	pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9657 	ctsio->kern_sg_entries = 0;
9658 
9659 	if (sup_page_size < alloc_len) {
9660 		ctsio->residual = alloc_len - sup_page_size;
9661 		ctsio->kern_data_len = sup_page_size;
9662 		ctsio->kern_total_len = sup_page_size;
9663 	} else {
9664 		ctsio->residual = 0;
9665 		ctsio->kern_data_len = alloc_len;
9666 		ctsio->kern_total_len = alloc_len;
9667 	}
9668 	ctsio->kern_data_resid = 0;
9669 	ctsio->kern_rel_offset = 0;
9670 	ctsio->kern_sg_entries = 0;
9671 
9672 	/*
9673 	 * The control device is always connected.  The disk device, on the
9674 	 * other hand, may not be online all the time.  Need to change this
9675 	 * to figure out whether the disk device is actually online or not.
9676 	 */
9677 	if (lun != NULL)
9678 		pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9679 				lun->be_lun->lun_type;
9680 	else
9681 		pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9682 
9683 	pages->length = SCSI_EVPD_NUM_SUPPORTED_PAGES;
9684 	/* Supported VPD pages */
9685 	pages->page_list[0] = SVPD_SUPPORTED_PAGES;
9686 	/* Serial Number */
9687 	pages->page_list[1] = SVPD_UNIT_SERIAL_NUMBER;
9688 	/* Device Identification */
9689 	pages->page_list[2] = SVPD_DEVICE_ID;
9690 	/* Extended INQUIRY Data */
9691 	pages->page_list[3] = SVPD_EXTENDED_INQUIRY_DATA;
9692 	/* Mode Page Policy */
9693 	pages->page_list[4] = SVPD_MODE_PAGE_POLICY;
9694 	/* SCSI Ports */
9695 	pages->page_list[5] = SVPD_SCSI_PORTS;
9696 	/* Third-party Copy */
9697 	pages->page_list[6] = SVPD_SCSI_TPC;
9698 	/* Block limits */
9699 	pages->page_list[7] = SVPD_BLOCK_LIMITS;
9700 	/* Block Device Characteristics */
9701 	pages->page_list[8] = SVPD_BDC;
9702 	/* Logical Block Provisioning */
9703 	pages->page_list[9] = SVPD_LBP;
9704 
9705 	ctl_set_success(ctsio);
9706 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9707 	ctsio->be_move_done = ctl_config_move_done;
9708 	ctl_datamove((union ctl_io *)ctsio);
9709 	return (CTL_RETVAL_COMPLETE);
9710 }
9711 
9712 static int
9713 ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9714 {
9715 	struct scsi_vpd_unit_serial_number *sn_ptr;
9716 	struct ctl_lun *lun;
9717 	int data_len;
9718 
9719 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9720 
9721 	data_len = 4 + CTL_SN_LEN;
9722 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9723 	sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9724 	if (data_len < alloc_len) {
9725 		ctsio->residual = alloc_len - data_len;
9726 		ctsio->kern_data_len = data_len;
9727 		ctsio->kern_total_len = data_len;
9728 	} else {
9729 		ctsio->residual = 0;
9730 		ctsio->kern_data_len = alloc_len;
9731 		ctsio->kern_total_len = alloc_len;
9732 	}
9733 	ctsio->kern_data_resid = 0;
9734 	ctsio->kern_rel_offset = 0;
9735 	ctsio->kern_sg_entries = 0;
9736 
9737 	/*
9738 	 * The control device is always connected.  The disk device, on the
9739 	 * other hand, may not be online all the time.  Need to change this
9740 	 * to figure out whether the disk device is actually online or not.
9741 	 */
9742 	if (lun != NULL)
9743 		sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9744 				  lun->be_lun->lun_type;
9745 	else
9746 		sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9747 
9748 	sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9749 	sn_ptr->length = CTL_SN_LEN;
9750 	/*
9751 	 * If we don't have a LUN, we just leave the serial number as
9752 	 * all spaces.
9753 	 */
9754 	if (lun != NULL) {
9755 		strncpy((char *)sn_ptr->serial_num,
9756 			(char *)lun->be_lun->serial_num, CTL_SN_LEN);
9757 	} else
9758 		memset(sn_ptr->serial_num, 0x20, CTL_SN_LEN);
9759 
9760 	ctl_set_success(ctsio);
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 	return (CTL_RETVAL_COMPLETE);
9765 }
9766 
9767 
9768 static int
9769 ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9770 {
9771 	struct scsi_vpd_extended_inquiry_data *eid_ptr;
9772 	struct ctl_lun *lun;
9773 	int data_len;
9774 
9775 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9776 
9777 	data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
9778 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9779 	eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9780 	ctsio->kern_sg_entries = 0;
9781 
9782 	if (data_len < alloc_len) {
9783 		ctsio->residual = alloc_len - data_len;
9784 		ctsio->kern_data_len = data_len;
9785 		ctsio->kern_total_len = data_len;
9786 	} else {
9787 		ctsio->residual = 0;
9788 		ctsio->kern_data_len = alloc_len;
9789 		ctsio->kern_total_len = alloc_len;
9790 	}
9791 	ctsio->kern_data_resid = 0;
9792 	ctsio->kern_rel_offset = 0;
9793 	ctsio->kern_sg_entries = 0;
9794 
9795 	/*
9796 	 * The control device is always connected.  The disk device, on the
9797 	 * other hand, may not be online all the time.
9798 	 */
9799 	if (lun != NULL)
9800 		eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9801 				     lun->be_lun->lun_type;
9802 	else
9803 		eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9804 	eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9805 	eid_ptr->page_length = data_len - 4;
9806 	eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9807 	eid_ptr->flags3 = SVPD_EID_V_SUP;
9808 
9809 	ctl_set_success(ctsio);
9810 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9811 	ctsio->be_move_done = ctl_config_move_done;
9812 	ctl_datamove((union ctl_io *)ctsio);
9813 	return (CTL_RETVAL_COMPLETE);
9814 }
9815 
9816 static int
9817 ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
9818 {
9819 	struct scsi_vpd_mode_page_policy *mpp_ptr;
9820 	struct ctl_lun *lun;
9821 	int data_len;
9822 
9823 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9824 
9825 	data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9826 	    sizeof(struct scsi_vpd_mode_page_policy_descr);
9827 
9828 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9829 	mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
9830 	ctsio->kern_sg_entries = 0;
9831 
9832 	if (data_len < alloc_len) {
9833 		ctsio->residual = alloc_len - data_len;
9834 		ctsio->kern_data_len = data_len;
9835 		ctsio->kern_total_len = data_len;
9836 	} else {
9837 		ctsio->residual = 0;
9838 		ctsio->kern_data_len = alloc_len;
9839 		ctsio->kern_total_len = alloc_len;
9840 	}
9841 	ctsio->kern_data_resid = 0;
9842 	ctsio->kern_rel_offset = 0;
9843 	ctsio->kern_sg_entries = 0;
9844 
9845 	/*
9846 	 * The control device is always connected.  The disk device, on the
9847 	 * other hand, may not be online all the time.
9848 	 */
9849 	if (lun != NULL)
9850 		mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9851 				     lun->be_lun->lun_type;
9852 	else
9853 		mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9854 	mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
9855 	scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
9856 	mpp_ptr->descr[0].page_code = 0x3f;
9857 	mpp_ptr->descr[0].subpage_code = 0xff;
9858 	mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
9859 
9860 	ctl_set_success(ctsio);
9861 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9862 	ctsio->be_move_done = ctl_config_move_done;
9863 	ctl_datamove((union ctl_io *)ctsio);
9864 	return (CTL_RETVAL_COMPLETE);
9865 }
9866 
9867 static int
9868 ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9869 {
9870 	struct scsi_vpd_device_id *devid_ptr;
9871 	struct scsi_vpd_id_descriptor *desc;
9872 	struct ctl_softc *ctl_softc;
9873 	struct ctl_lun *lun;
9874 	struct ctl_port *port;
9875 	int data_len;
9876 	uint8_t proto;
9877 
9878 	ctl_softc = control_softc;
9879 
9880 	port = ctl_softc->ctl_ports[ctl_port_idx(ctsio->io_hdr.nexus.targ_port)];
9881 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9882 
9883 	data_len = sizeof(struct scsi_vpd_device_id) +
9884 	    sizeof(struct scsi_vpd_id_descriptor) +
9885 		sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9886 	    sizeof(struct scsi_vpd_id_descriptor) +
9887 		sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9888 	if (lun && lun->lun_devid)
9889 		data_len += lun->lun_devid->len;
9890 	if (port->port_devid)
9891 		data_len += port->port_devid->len;
9892 	if (port->target_devid)
9893 		data_len += port->target_devid->len;
9894 
9895 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9896 	devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9897 	ctsio->kern_sg_entries = 0;
9898 
9899 	if (data_len < alloc_len) {
9900 		ctsio->residual = alloc_len - data_len;
9901 		ctsio->kern_data_len = data_len;
9902 		ctsio->kern_total_len = data_len;
9903 	} else {
9904 		ctsio->residual = 0;
9905 		ctsio->kern_data_len = alloc_len;
9906 		ctsio->kern_total_len = alloc_len;
9907 	}
9908 	ctsio->kern_data_resid = 0;
9909 	ctsio->kern_rel_offset = 0;
9910 	ctsio->kern_sg_entries = 0;
9911 
9912 	/*
9913 	 * The control device is always connected.  The disk device, on the
9914 	 * other hand, may not be online all the time.
9915 	 */
9916 	if (lun != NULL)
9917 		devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9918 				     lun->be_lun->lun_type;
9919 	else
9920 		devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9921 	devid_ptr->page_code = SVPD_DEVICE_ID;
9922 	scsi_ulto2b(data_len - 4, devid_ptr->length);
9923 
9924 	if (port->port_type == CTL_PORT_FC)
9925 		proto = SCSI_PROTO_FC << 4;
9926 	else if (port->port_type == CTL_PORT_ISCSI)
9927 		proto = SCSI_PROTO_ISCSI << 4;
9928 	else
9929 		proto = SCSI_PROTO_SPI << 4;
9930 	desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
9931 
9932 	/*
9933 	 * We're using a LUN association here.  i.e., this device ID is a
9934 	 * per-LUN identifier.
9935 	 */
9936 	if (lun && lun->lun_devid) {
9937 		memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
9938 		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9939 		    lun->lun_devid->len);
9940 	}
9941 
9942 	/*
9943 	 * This is for the WWPN which is a port association.
9944 	 */
9945 	if (port->port_devid) {
9946 		memcpy(desc, port->port_devid->data, port->port_devid->len);
9947 		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9948 		    port->port_devid->len);
9949 	}
9950 
9951 	/*
9952 	 * This is for the Relative Target Port(type 4h) identifier
9953 	 */
9954 	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9955 	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9956 	    SVPD_ID_TYPE_RELTARG;
9957 	desc->length = 4;
9958 	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
9959 	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9960 	    sizeof(struct scsi_vpd_id_rel_trgt_port_id));
9961 
9962 	/*
9963 	 * This is for the Target Port Group(type 5h) identifier
9964 	 */
9965 	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9966 	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9967 	    SVPD_ID_TYPE_TPORTGRP;
9968 	desc->length = 4;
9969 	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port / CTL_MAX_PORTS + 1,
9970 	    &desc->identifier[2]);
9971 	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9972 	    sizeof(struct scsi_vpd_id_trgt_port_grp_id));
9973 
9974 	/*
9975 	 * This is for the Target identifier
9976 	 */
9977 	if (port->target_devid) {
9978 		memcpy(desc, port->target_devid->data, port->target_devid->len);
9979 	}
9980 
9981 	ctl_set_success(ctsio);
9982 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9983 	ctsio->be_move_done = ctl_config_move_done;
9984 	ctl_datamove((union ctl_io *)ctsio);
9985 	return (CTL_RETVAL_COMPLETE);
9986 }
9987 
9988 static int
9989 ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
9990 {
9991 	struct ctl_softc *softc = control_softc;
9992 	struct scsi_vpd_scsi_ports *sp;
9993 	struct scsi_vpd_port_designation *pd;
9994 	struct scsi_vpd_port_designation_cont *pdc;
9995 	struct ctl_lun *lun;
9996 	struct ctl_port *port;
9997 	int data_len, num_target_ports, iid_len, id_len, g, pg, p;
9998 	int num_target_port_groups;
9999 
10000 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10001 
10002 	if (softc->is_single)
10003 		num_target_port_groups = 1;
10004 	else
10005 		num_target_port_groups = NUM_TARGET_PORT_GROUPS;
10006 	num_target_ports = 0;
10007 	iid_len = 0;
10008 	id_len = 0;
10009 	mtx_lock(&softc->ctl_lock);
10010 	STAILQ_FOREACH(port, &softc->port_list, links) {
10011 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
10012 			continue;
10013 		if (lun != NULL &&
10014 		    ctl_map_lun_back(port->targ_port, lun->lun) >=
10015 		    CTL_MAX_LUNS)
10016 			continue;
10017 		num_target_ports++;
10018 		if (port->init_devid)
10019 			iid_len += port->init_devid->len;
10020 		if (port->port_devid)
10021 			id_len += port->port_devid->len;
10022 	}
10023 	mtx_unlock(&softc->ctl_lock);
10024 
10025 	data_len = sizeof(struct scsi_vpd_scsi_ports) + num_target_port_groups *
10026 	    num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
10027 	     sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
10028 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10029 	sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
10030 	ctsio->kern_sg_entries = 0;
10031 
10032 	if (data_len < alloc_len) {
10033 		ctsio->residual = alloc_len - data_len;
10034 		ctsio->kern_data_len = data_len;
10035 		ctsio->kern_total_len = data_len;
10036 	} else {
10037 		ctsio->residual = 0;
10038 		ctsio->kern_data_len = alloc_len;
10039 		ctsio->kern_total_len = alloc_len;
10040 	}
10041 	ctsio->kern_data_resid = 0;
10042 	ctsio->kern_rel_offset = 0;
10043 	ctsio->kern_sg_entries = 0;
10044 
10045 	/*
10046 	 * The control device is always connected.  The disk device, on the
10047 	 * other hand, may not be online all the time.  Need to change this
10048 	 * to figure out whether the disk device is actually online or not.
10049 	 */
10050 	if (lun != NULL)
10051 		sp->device = (SID_QUAL_LU_CONNECTED << 5) |
10052 				  lun->be_lun->lun_type;
10053 	else
10054 		sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10055 
10056 	sp->page_code = SVPD_SCSI_PORTS;
10057 	scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
10058 	    sp->page_length);
10059 	pd = &sp->design[0];
10060 
10061 	mtx_lock(&softc->ctl_lock);
10062 	pg = softc->port_offset / CTL_MAX_PORTS;
10063 	for (g = 0; g < num_target_port_groups; g++) {
10064 		STAILQ_FOREACH(port, &softc->port_list, links) {
10065 			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
10066 				continue;
10067 			if (lun != NULL &&
10068 			    ctl_map_lun_back(port->targ_port, lun->lun) >=
10069 			    CTL_MAX_LUNS)
10070 				continue;
10071 			p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
10072 			scsi_ulto2b(p, pd->relative_port_id);
10073 			if (port->init_devid && g == pg) {
10074 				iid_len = port->init_devid->len;
10075 				memcpy(pd->initiator_transportid,
10076 				    port->init_devid->data, port->init_devid->len);
10077 			} else
10078 				iid_len = 0;
10079 			scsi_ulto2b(iid_len, pd->initiator_transportid_length);
10080 			pdc = (struct scsi_vpd_port_designation_cont *)
10081 			    (&pd->initiator_transportid[iid_len]);
10082 			if (port->port_devid && g == pg) {
10083 				id_len = port->port_devid->len;
10084 				memcpy(pdc->target_port_descriptors,
10085 				    port->port_devid->data, port->port_devid->len);
10086 			} else
10087 				id_len = 0;
10088 			scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
10089 			pd = (struct scsi_vpd_port_designation *)
10090 			    ((uint8_t *)pdc->target_port_descriptors + id_len);
10091 		}
10092 	}
10093 	mtx_unlock(&softc->ctl_lock);
10094 
10095 	ctl_set_success(ctsio);
10096 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10097 	ctsio->be_move_done = ctl_config_move_done;
10098 	ctl_datamove((union ctl_io *)ctsio);
10099 	return (CTL_RETVAL_COMPLETE);
10100 }
10101 
10102 static int
10103 ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
10104 {
10105 	struct scsi_vpd_block_limits *bl_ptr;
10106 	struct ctl_lun *lun;
10107 	int bs;
10108 
10109 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10110 
10111 	ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
10112 	bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
10113 	ctsio->kern_sg_entries = 0;
10114 
10115 	if (sizeof(*bl_ptr) < alloc_len) {
10116 		ctsio->residual = alloc_len - sizeof(*bl_ptr);
10117 		ctsio->kern_data_len = sizeof(*bl_ptr);
10118 		ctsio->kern_total_len = sizeof(*bl_ptr);
10119 	} else {
10120 		ctsio->residual = 0;
10121 		ctsio->kern_data_len = alloc_len;
10122 		ctsio->kern_total_len = alloc_len;
10123 	}
10124 	ctsio->kern_data_resid = 0;
10125 	ctsio->kern_rel_offset = 0;
10126 	ctsio->kern_sg_entries = 0;
10127 
10128 	/*
10129 	 * The control device is always connected.  The disk device, on the
10130 	 * other hand, may not be online all the time.  Need to change this
10131 	 * to figure out whether the disk device is actually online or not.
10132 	 */
10133 	if (lun != NULL)
10134 		bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10135 				  lun->be_lun->lun_type;
10136 	else
10137 		bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10138 
10139 	bl_ptr->page_code = SVPD_BLOCK_LIMITS;
10140 	scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
10141 	bl_ptr->max_cmp_write_len = 0xff;
10142 	scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
10143 	if (lun != NULL) {
10144 		bs = lun->be_lun->blocksize;
10145 		scsi_ulto4b(MAXPHYS / bs, bl_ptr->opt_txfer_len);
10146 		if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10147 			scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_lba_cnt);
10148 			scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_blk_cnt);
10149 			if (lun->be_lun->pblockexp != 0) {
10150 				scsi_ulto4b((1 << lun->be_lun->pblockexp),
10151 				    bl_ptr->opt_unmap_grain);
10152 				scsi_ulto4b(0x80000000 | lun->be_lun->pblockoff,
10153 				    bl_ptr->unmap_grain_align);
10154 			}
10155 		}
10156 		scsi_ulto4b(lun->be_lun->atomicblock,
10157 		    bl_ptr->max_atomic_transfer_length);
10158 		scsi_ulto4b(0, bl_ptr->atomic_alignment);
10159 		scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
10160 	}
10161 	scsi_u64to8b(UINT64_MAX, bl_ptr->max_write_same_length);
10162 
10163 	ctl_set_success(ctsio);
10164 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10165 	ctsio->be_move_done = ctl_config_move_done;
10166 	ctl_datamove((union ctl_io *)ctsio);
10167 	return (CTL_RETVAL_COMPLETE);
10168 }
10169 
10170 static int
10171 ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
10172 {
10173 	struct scsi_vpd_block_device_characteristics *bdc_ptr;
10174 	struct ctl_lun *lun;
10175 	const char *value;
10176 	u_int i;
10177 
10178 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10179 
10180 	ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
10181 	bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
10182 	ctsio->kern_sg_entries = 0;
10183 
10184 	if (sizeof(*bdc_ptr) < alloc_len) {
10185 		ctsio->residual = alloc_len - sizeof(*bdc_ptr);
10186 		ctsio->kern_data_len = sizeof(*bdc_ptr);
10187 		ctsio->kern_total_len = sizeof(*bdc_ptr);
10188 	} else {
10189 		ctsio->residual = 0;
10190 		ctsio->kern_data_len = alloc_len;
10191 		ctsio->kern_total_len = alloc_len;
10192 	}
10193 	ctsio->kern_data_resid = 0;
10194 	ctsio->kern_rel_offset = 0;
10195 	ctsio->kern_sg_entries = 0;
10196 
10197 	/*
10198 	 * The control device is always connected.  The disk device, on the
10199 	 * other hand, may not be online all the time.  Need to change this
10200 	 * to figure out whether the disk device is actually online or not.
10201 	 */
10202 	if (lun != NULL)
10203 		bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10204 				  lun->be_lun->lun_type;
10205 	else
10206 		bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10207 	bdc_ptr->page_code = SVPD_BDC;
10208 	scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
10209 	if (lun != NULL &&
10210 	    (value = ctl_get_opt(&lun->be_lun->options, "rpm")) != NULL)
10211 		i = strtol(value, NULL, 0);
10212 	else
10213 		i = CTL_DEFAULT_ROTATION_RATE;
10214 	scsi_ulto2b(i, bdc_ptr->medium_rotation_rate);
10215 	if (lun != NULL &&
10216 	    (value = ctl_get_opt(&lun->be_lun->options, "formfactor")) != NULL)
10217 		i = strtol(value, NULL, 0);
10218 	else
10219 		i = 0;
10220 	bdc_ptr->wab_wac_ff = (i & 0x0f);
10221 	bdc_ptr->flags = SVPD_FUAB | SVPD_VBULS;
10222 
10223 	ctl_set_success(ctsio);
10224 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10225 	ctsio->be_move_done = ctl_config_move_done;
10226 	ctl_datamove((union ctl_io *)ctsio);
10227 	return (CTL_RETVAL_COMPLETE);
10228 }
10229 
10230 static int
10231 ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
10232 {
10233 	struct scsi_vpd_logical_block_prov *lbp_ptr;
10234 	struct ctl_lun *lun;
10235 
10236 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10237 
10238 	ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
10239 	lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
10240 	ctsio->kern_sg_entries = 0;
10241 
10242 	if (sizeof(*lbp_ptr) < alloc_len) {
10243 		ctsio->residual = alloc_len - sizeof(*lbp_ptr);
10244 		ctsio->kern_data_len = sizeof(*lbp_ptr);
10245 		ctsio->kern_total_len = sizeof(*lbp_ptr);
10246 	} else {
10247 		ctsio->residual = 0;
10248 		ctsio->kern_data_len = alloc_len;
10249 		ctsio->kern_total_len = alloc_len;
10250 	}
10251 	ctsio->kern_data_resid = 0;
10252 	ctsio->kern_rel_offset = 0;
10253 	ctsio->kern_sg_entries = 0;
10254 
10255 	/*
10256 	 * The control device is always connected.  The disk device, on the
10257 	 * other hand, may not be online all the time.  Need to change this
10258 	 * to figure out whether the disk device is actually online or not.
10259 	 */
10260 	if (lun != NULL)
10261 		lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10262 				  lun->be_lun->lun_type;
10263 	else
10264 		lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10265 
10266 	lbp_ptr->page_code = SVPD_LBP;
10267 	scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
10268 	lbp_ptr->threshold_exponent = CTL_LBP_EXPONENT;
10269 	if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10270 		lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
10271 		    SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
10272 		lbp_ptr->prov_type = SVPD_LBP_THIN;
10273 	}
10274 
10275 	ctl_set_success(ctsio);
10276 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10277 	ctsio->be_move_done = ctl_config_move_done;
10278 	ctl_datamove((union ctl_io *)ctsio);
10279 	return (CTL_RETVAL_COMPLETE);
10280 }
10281 
10282 static int
10283 ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
10284 {
10285 	struct scsi_inquiry *cdb;
10286 	int alloc_len, retval;
10287 
10288 	cdb = (struct scsi_inquiry *)ctsio->cdb;
10289 
10290 	retval = CTL_RETVAL_COMPLETE;
10291 
10292 	alloc_len = scsi_2btoul(cdb->length);
10293 
10294 	switch (cdb->page_code) {
10295 	case SVPD_SUPPORTED_PAGES:
10296 		retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
10297 		break;
10298 	case SVPD_UNIT_SERIAL_NUMBER:
10299 		retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
10300 		break;
10301 	case SVPD_DEVICE_ID:
10302 		retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
10303 		break;
10304 	case SVPD_EXTENDED_INQUIRY_DATA:
10305 		retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
10306 		break;
10307 	case SVPD_MODE_PAGE_POLICY:
10308 		retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
10309 		break;
10310 	case SVPD_SCSI_PORTS:
10311 		retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10312 		break;
10313 	case SVPD_SCSI_TPC:
10314 		retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
10315 		break;
10316 	case SVPD_BLOCK_LIMITS:
10317 		retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10318 		break;
10319 	case SVPD_BDC:
10320 		retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
10321 		break;
10322 	case SVPD_LBP:
10323 		retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10324 		break;
10325 	default:
10326 		ctl_set_invalid_field(ctsio,
10327 				      /*sks_valid*/ 1,
10328 				      /*command*/ 1,
10329 				      /*field*/ 2,
10330 				      /*bit_valid*/ 0,
10331 				      /*bit*/ 0);
10332 		ctl_done((union ctl_io *)ctsio);
10333 		retval = CTL_RETVAL_COMPLETE;
10334 		break;
10335 	}
10336 
10337 	return (retval);
10338 }
10339 
10340 static int
10341 ctl_inquiry_std(struct ctl_scsiio *ctsio)
10342 {
10343 	struct scsi_inquiry_data *inq_ptr;
10344 	struct scsi_inquiry *cdb;
10345 	struct ctl_softc *ctl_softc;
10346 	struct ctl_lun *lun;
10347 	char *val;
10348 	uint32_t alloc_len, data_len;
10349 	ctl_port_type port_type;
10350 
10351 	ctl_softc = control_softc;
10352 
10353 	/*
10354 	 * Figure out whether we're talking to a Fibre Channel port or not.
10355 	 * We treat the ioctl front end, and any SCSI adapters, as packetized
10356 	 * SCSI front ends.
10357 	 */
10358 	port_type = ctl_softc->ctl_ports[
10359 	    ctl_port_idx(ctsio->io_hdr.nexus.targ_port)]->port_type;
10360 	if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10361 		port_type = CTL_PORT_SCSI;
10362 
10363 	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10364 	cdb = (struct scsi_inquiry *)ctsio->cdb;
10365 	alloc_len = scsi_2btoul(cdb->length);
10366 
10367 	/*
10368 	 * We malloc the full inquiry data size here and fill it
10369 	 * in.  If the user only asks for less, we'll give him
10370 	 * that much.
10371 	 */
10372 	data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
10373 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10374 	inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10375 	ctsio->kern_sg_entries = 0;
10376 	ctsio->kern_data_resid = 0;
10377 	ctsio->kern_rel_offset = 0;
10378 
10379 	if (data_len < alloc_len) {
10380 		ctsio->residual = alloc_len - data_len;
10381 		ctsio->kern_data_len = data_len;
10382 		ctsio->kern_total_len = data_len;
10383 	} else {
10384 		ctsio->residual = 0;
10385 		ctsio->kern_data_len = alloc_len;
10386 		ctsio->kern_total_len = alloc_len;
10387 	}
10388 
10389 	/*
10390 	 * If we have a LUN configured, report it as connected.  Otherwise,
10391 	 * report that it is offline or no device is supported, depending
10392 	 * on the value of inquiry_pq_no_lun.
10393 	 *
10394 	 * According to the spec (SPC-4 r34), the peripheral qualifier
10395 	 * SID_QUAL_LU_OFFLINE (001b) is used in the following scenario:
10396 	 *
10397 	 * "A peripheral device having the specified peripheral device type
10398 	 * is not connected to this logical unit. However, the device
10399 	 * server is capable of supporting the specified peripheral device
10400 	 * type on this logical unit."
10401 	 *
10402 	 * According to the same spec, the peripheral qualifier
10403 	 * SID_QUAL_BAD_LU (011b) is used in this scenario:
10404 	 *
10405 	 * "The device server is not capable of supporting a peripheral
10406 	 * device on this logical unit. For this peripheral qualifier the
10407 	 * peripheral device type shall be set to 1Fh. All other peripheral
10408 	 * device type values are reserved for this peripheral qualifier."
10409 	 *
10410 	 * Given the text, it would seem that we probably want to report that
10411 	 * the LUN is offline here.  There is no LUN connected, but we can
10412 	 * support a LUN at the given LUN number.
10413 	 *
10414 	 * In the real world, though, it sounds like things are a little
10415 	 * different:
10416 	 *
10417 	 * - Linux, when presented with a LUN with the offline peripheral
10418 	 *   qualifier, will create an sg driver instance for it.  So when
10419 	 *   you attach it to CTL, you wind up with a ton of sg driver
10420 	 *   instances.  (One for every LUN that Linux bothered to probe.)
10421 	 *   Linux does this despite the fact that it issues a REPORT LUNs
10422 	 *   to LUN 0 to get the inventory of supported LUNs.
10423 	 *
10424 	 * - There is other anecdotal evidence (from Emulex folks) about
10425 	 *   arrays that use the offline peripheral qualifier for LUNs that
10426 	 *   are on the "passive" path in an active/passive array.
10427 	 *
10428 	 * So the solution is provide a hopefully reasonable default
10429 	 * (return bad/no LUN) and allow the user to change the behavior
10430 	 * with a tunable/sysctl variable.
10431 	 */
10432 	if (lun != NULL)
10433 		inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10434 				  lun->be_lun->lun_type;
10435 	else if (ctl_softc->inquiry_pq_no_lun == 0)
10436 		inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10437 	else
10438 		inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10439 
10440 	/* RMB in byte 2 is 0 */
10441 	inq_ptr->version = SCSI_REV_SPC4;
10442 
10443 	/*
10444 	 * According to SAM-3, even if a device only supports a single
10445 	 * level of LUN addressing, it should still set the HISUP bit:
10446 	 *
10447 	 * 4.9.1 Logical unit numbers overview
10448 	 *
10449 	 * All logical unit number formats described in this standard are
10450 	 * hierarchical in structure even when only a single level in that
10451 	 * hierarchy is used. The HISUP bit shall be set to one in the
10452 	 * standard INQUIRY data (see SPC-2) when any logical unit number
10453 	 * format described in this standard is used.  Non-hierarchical
10454 	 * formats are outside the scope of this standard.
10455 	 *
10456 	 * Therefore we set the HiSup bit here.
10457 	 *
10458 	 * The reponse format is 2, per SPC-3.
10459 	 */
10460 	inq_ptr->response_format = SID_HiSup | 2;
10461 
10462 	inq_ptr->additional_length = data_len -
10463 	    (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10464 	CTL_DEBUG_PRINT(("additional_length = %d\n",
10465 			 inq_ptr->additional_length));
10466 
10467 	inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10468 	/* 16 bit addressing */
10469 	if (port_type == CTL_PORT_SCSI)
10470 		inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10471 	/* XXX set the SID_MultiP bit here if we're actually going to
10472 	   respond on multiple ports */
10473 	inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10474 
10475 	/* 16 bit data bus, synchronous transfers */
10476 	if (port_type == CTL_PORT_SCSI)
10477 		inq_ptr->flags = SID_WBus16 | SID_Sync;
10478 	/*
10479 	 * XXX KDM do we want to support tagged queueing on the control
10480 	 * device at all?
10481 	 */
10482 	if ((lun == NULL)
10483 	 || (lun->be_lun->lun_type != T_PROCESSOR))
10484 		inq_ptr->flags |= SID_CmdQue;
10485 	/*
10486 	 * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10487 	 * We have 8 bytes for the vendor name, and 16 bytes for the device
10488 	 * name and 4 bytes for the revision.
10489 	 */
10490 	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10491 	    "vendor")) == NULL) {
10492 		strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10493 	} else {
10494 		memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10495 		strncpy(inq_ptr->vendor, val,
10496 		    min(sizeof(inq_ptr->vendor), strlen(val)));
10497 	}
10498 	if (lun == NULL) {
10499 		strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10500 		    sizeof(inq_ptr->product));
10501 	} else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10502 		switch (lun->be_lun->lun_type) {
10503 		case T_DIRECT:
10504 			strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10505 			    sizeof(inq_ptr->product));
10506 			break;
10507 		case T_PROCESSOR:
10508 			strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10509 			    sizeof(inq_ptr->product));
10510 			break;
10511 		default:
10512 			strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10513 			    sizeof(inq_ptr->product));
10514 			break;
10515 		}
10516 	} else {
10517 		memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10518 		strncpy(inq_ptr->product, val,
10519 		    min(sizeof(inq_ptr->product), strlen(val)));
10520 	}
10521 
10522 	/*
10523 	 * XXX make this a macro somewhere so it automatically gets
10524 	 * incremented when we make changes.
10525 	 */
10526 	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10527 	    "revision")) == NULL) {
10528 		strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10529 	} else {
10530 		memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10531 		strncpy(inq_ptr->revision, val,
10532 		    min(sizeof(inq_ptr->revision), strlen(val)));
10533 	}
10534 
10535 	/*
10536 	 * For parallel SCSI, we support double transition and single
10537 	 * transition clocking.  We also support QAS (Quick Arbitration
10538 	 * and Selection) and Information Unit transfers on both the
10539 	 * control and array devices.
10540 	 */
10541 	if (port_type == CTL_PORT_SCSI)
10542 		inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10543 				    SID_SPI_IUS;
10544 
10545 	/* SAM-5 (no version claimed) */
10546 	scsi_ulto2b(0x00A0, inq_ptr->version1);
10547 	/* SPC-4 (no version claimed) */
10548 	scsi_ulto2b(0x0460, inq_ptr->version2);
10549 	if (port_type == CTL_PORT_FC) {
10550 		/* FCP-2 ANSI INCITS.350:2003 */
10551 		scsi_ulto2b(0x0917, inq_ptr->version3);
10552 	} else if (port_type == CTL_PORT_SCSI) {
10553 		/* SPI-4 ANSI INCITS.362:200x */
10554 		scsi_ulto2b(0x0B56, inq_ptr->version3);
10555 	} else if (port_type == CTL_PORT_ISCSI) {
10556 		/* iSCSI (no version claimed) */
10557 		scsi_ulto2b(0x0960, inq_ptr->version3);
10558 	} else if (port_type == CTL_PORT_SAS) {
10559 		/* SAS (no version claimed) */
10560 		scsi_ulto2b(0x0BE0, inq_ptr->version3);
10561 	}
10562 
10563 	if (lun == NULL) {
10564 		/* SBC-4 (no version claimed) */
10565 		scsi_ulto2b(0x0600, inq_ptr->version4);
10566 	} else {
10567 		switch (lun->be_lun->lun_type) {
10568 		case T_DIRECT:
10569 			/* SBC-4 (no version claimed) */
10570 			scsi_ulto2b(0x0600, inq_ptr->version4);
10571 			break;
10572 		case T_PROCESSOR:
10573 		default:
10574 			break;
10575 		}
10576 	}
10577 
10578 	ctl_set_success(ctsio);
10579 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10580 	ctsio->be_move_done = ctl_config_move_done;
10581 	ctl_datamove((union ctl_io *)ctsio);
10582 	return (CTL_RETVAL_COMPLETE);
10583 }
10584 
10585 int
10586 ctl_inquiry(struct ctl_scsiio *ctsio)
10587 {
10588 	struct scsi_inquiry *cdb;
10589 	int retval;
10590 
10591 	CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10592 
10593 	cdb = (struct scsi_inquiry *)ctsio->cdb;
10594 	if (cdb->byte2 & SI_EVPD)
10595 		retval = ctl_inquiry_evpd(ctsio);
10596 	else if (cdb->page_code == 0)
10597 		retval = ctl_inquiry_std(ctsio);
10598 	else {
10599 		ctl_set_invalid_field(ctsio,
10600 				      /*sks_valid*/ 1,
10601 				      /*command*/ 1,
10602 				      /*field*/ 2,
10603 				      /*bit_valid*/ 0,
10604 				      /*bit*/ 0);
10605 		ctl_done((union ctl_io *)ctsio);
10606 		return (CTL_RETVAL_COMPLETE);
10607 	}
10608 
10609 	return (retval);
10610 }
10611 
10612 /*
10613  * For known CDB types, parse the LBA and length.
10614  */
10615 static int
10616 ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10617 {
10618 	if (io->io_hdr.io_type != CTL_IO_SCSI)
10619 		return (1);
10620 
10621 	switch (io->scsiio.cdb[0]) {
10622 	case COMPARE_AND_WRITE: {
10623 		struct scsi_compare_and_write *cdb;
10624 
10625 		cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10626 
10627 		*lba = scsi_8btou64(cdb->addr);
10628 		*len = cdb->length;
10629 		break;
10630 	}
10631 	case READ_6:
10632 	case WRITE_6: {
10633 		struct scsi_rw_6 *cdb;
10634 
10635 		cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10636 
10637 		*lba = scsi_3btoul(cdb->addr);
10638 		/* only 5 bits are valid in the most significant address byte */
10639 		*lba &= 0x1fffff;
10640 		*len = cdb->length;
10641 		break;
10642 	}
10643 	case READ_10:
10644 	case WRITE_10: {
10645 		struct scsi_rw_10 *cdb;
10646 
10647 		cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10648 
10649 		*lba = scsi_4btoul(cdb->addr);
10650 		*len = scsi_2btoul(cdb->length);
10651 		break;
10652 	}
10653 	case WRITE_VERIFY_10: {
10654 		struct scsi_write_verify_10 *cdb;
10655 
10656 		cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10657 
10658 		*lba = scsi_4btoul(cdb->addr);
10659 		*len = scsi_2btoul(cdb->length);
10660 		break;
10661 	}
10662 	case READ_12:
10663 	case WRITE_12: {
10664 		struct scsi_rw_12 *cdb;
10665 
10666 		cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10667 
10668 		*lba = scsi_4btoul(cdb->addr);
10669 		*len = scsi_4btoul(cdb->length);
10670 		break;
10671 	}
10672 	case WRITE_VERIFY_12: {
10673 		struct scsi_write_verify_12 *cdb;
10674 
10675 		cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10676 
10677 		*lba = scsi_4btoul(cdb->addr);
10678 		*len = scsi_4btoul(cdb->length);
10679 		break;
10680 	}
10681 	case READ_16:
10682 	case WRITE_16:
10683 	case WRITE_ATOMIC_16: {
10684 		struct scsi_rw_16 *cdb;
10685 
10686 		cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10687 
10688 		*lba = scsi_8btou64(cdb->addr);
10689 		*len = scsi_4btoul(cdb->length);
10690 		break;
10691 	}
10692 	case WRITE_VERIFY_16: {
10693 		struct scsi_write_verify_16 *cdb;
10694 
10695 		cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10696 
10697 		*lba = scsi_8btou64(cdb->addr);
10698 		*len = scsi_4btoul(cdb->length);
10699 		break;
10700 	}
10701 	case WRITE_SAME_10: {
10702 		struct scsi_write_same_10 *cdb;
10703 
10704 		cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10705 
10706 		*lba = scsi_4btoul(cdb->addr);
10707 		*len = scsi_2btoul(cdb->length);
10708 		break;
10709 	}
10710 	case WRITE_SAME_16: {
10711 		struct scsi_write_same_16 *cdb;
10712 
10713 		cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10714 
10715 		*lba = scsi_8btou64(cdb->addr);
10716 		*len = scsi_4btoul(cdb->length);
10717 		break;
10718 	}
10719 	case VERIFY_10: {
10720 		struct scsi_verify_10 *cdb;
10721 
10722 		cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10723 
10724 		*lba = scsi_4btoul(cdb->addr);
10725 		*len = scsi_2btoul(cdb->length);
10726 		break;
10727 	}
10728 	case VERIFY_12: {
10729 		struct scsi_verify_12 *cdb;
10730 
10731 		cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10732 
10733 		*lba = scsi_4btoul(cdb->addr);
10734 		*len = scsi_4btoul(cdb->length);
10735 		break;
10736 	}
10737 	case VERIFY_16: {
10738 		struct scsi_verify_16 *cdb;
10739 
10740 		cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10741 
10742 		*lba = scsi_8btou64(cdb->addr);
10743 		*len = scsi_4btoul(cdb->length);
10744 		break;
10745 	}
10746 	case UNMAP: {
10747 		*lba = 0;
10748 		*len = UINT64_MAX;
10749 		break;
10750 	}
10751 	case SERVICE_ACTION_IN: {	/* GET LBA STATUS */
10752 		struct scsi_get_lba_status *cdb;
10753 
10754 		cdb = (struct scsi_get_lba_status *)io->scsiio.cdb;
10755 		*lba = scsi_8btou64(cdb->addr);
10756 		*len = UINT32_MAX;
10757 		break;
10758 	}
10759 	default:
10760 		return (1);
10761 		break; /* NOTREACHED */
10762 	}
10763 
10764 	return (0);
10765 }
10766 
10767 static ctl_action
10768 ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2,
10769     bool seq)
10770 {
10771 	uint64_t endlba1, endlba2;
10772 
10773 	endlba1 = lba1 + len1 - (seq ? 0 : 1);
10774 	endlba2 = lba2 + len2 - 1;
10775 
10776 	if ((endlba1 < lba2) || (endlba2 < lba1))
10777 		return (CTL_ACTION_PASS);
10778 	else
10779 		return (CTL_ACTION_BLOCK);
10780 }
10781 
10782 static int
10783 ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
10784 {
10785 	struct ctl_ptr_len_flags *ptrlen;
10786 	struct scsi_unmap_desc *buf, *end, *range;
10787 	uint64_t lba;
10788 	uint32_t len;
10789 
10790 	/* If not UNMAP -- go other way. */
10791 	if (io->io_hdr.io_type != CTL_IO_SCSI ||
10792 	    io->scsiio.cdb[0] != UNMAP)
10793 		return (CTL_ACTION_ERROR);
10794 
10795 	/* If UNMAP without data -- block and wait for data. */
10796 	ptrlen = (struct ctl_ptr_len_flags *)
10797 	    &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10798 	if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
10799 	    ptrlen->ptr == NULL)
10800 		return (CTL_ACTION_BLOCK);
10801 
10802 	/* UNMAP with data -- check for collision. */
10803 	buf = (struct scsi_unmap_desc *)ptrlen->ptr;
10804 	end = buf + ptrlen->len / sizeof(*buf);
10805 	for (range = buf; range < end; range++) {
10806 		lba = scsi_8btou64(range->lba);
10807 		len = scsi_4btoul(range->length);
10808 		if ((lba < lba2 + len2) && (lba + len > lba2))
10809 			return (CTL_ACTION_BLOCK);
10810 	}
10811 	return (CTL_ACTION_PASS);
10812 }
10813 
10814 static ctl_action
10815 ctl_extent_check(union ctl_io *io1, union ctl_io *io2, bool seq)
10816 {
10817 	uint64_t lba1, lba2;
10818 	uint64_t len1, len2;
10819 	int retval;
10820 
10821 	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10822 		return (CTL_ACTION_ERROR);
10823 
10824 	retval = ctl_extent_check_unmap(io1, lba2, len2);
10825 	if (retval != CTL_ACTION_ERROR)
10826 		return (retval);
10827 
10828 	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10829 		return (CTL_ACTION_ERROR);
10830 
10831 	return (ctl_extent_check_lba(lba1, len1, lba2, len2, seq));
10832 }
10833 
10834 static ctl_action
10835 ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2)
10836 {
10837 	uint64_t lba1, lba2;
10838 	uint64_t len1, len2;
10839 
10840 	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10841 		return (CTL_ACTION_ERROR);
10842 	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10843 		return (CTL_ACTION_ERROR);
10844 
10845 	if (lba1 + len1 == lba2)
10846 		return (CTL_ACTION_BLOCK);
10847 	return (CTL_ACTION_PASS);
10848 }
10849 
10850 static ctl_action
10851 ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
10852     union ctl_io *ooa_io)
10853 {
10854 	const struct ctl_cmd_entry *pending_entry, *ooa_entry;
10855 	ctl_serialize_action *serialize_row;
10856 
10857 	/*
10858 	 * The initiator attempted multiple untagged commands at the same
10859 	 * time.  Can't do that.
10860 	 */
10861 	if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10862 	 && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10863 	 && ((pending_io->io_hdr.nexus.targ_port ==
10864 	      ooa_io->io_hdr.nexus.targ_port)
10865 	  && (pending_io->io_hdr.nexus.initid.id ==
10866 	      ooa_io->io_hdr.nexus.initid.id))
10867 	 && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
10868 		return (CTL_ACTION_OVERLAP);
10869 
10870 	/*
10871 	 * The initiator attempted to send multiple tagged commands with
10872 	 * the same ID.  (It's fine if different initiators have the same
10873 	 * tag ID.)
10874 	 *
10875 	 * Even if all of those conditions are true, we don't kill the I/O
10876 	 * if the command ahead of us has been aborted.  We won't end up
10877 	 * sending it to the FETD, and it's perfectly legal to resend a
10878 	 * command with the same tag number as long as the previous
10879 	 * instance of this tag number has been aborted somehow.
10880 	 */
10881 	if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10882 	 && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10883 	 && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
10884 	 && ((pending_io->io_hdr.nexus.targ_port ==
10885 	      ooa_io->io_hdr.nexus.targ_port)
10886 	  && (pending_io->io_hdr.nexus.initid.id ==
10887 	      ooa_io->io_hdr.nexus.initid.id))
10888 	 && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
10889 		return (CTL_ACTION_OVERLAP_TAG);
10890 
10891 	/*
10892 	 * If we get a head of queue tag, SAM-3 says that we should
10893 	 * immediately execute it.
10894 	 *
10895 	 * What happens if this command would normally block for some other
10896 	 * reason?  e.g. a request sense with a head of queue tag
10897 	 * immediately after a write.  Normally that would block, but this
10898 	 * will result in its getting executed immediately...
10899 	 *
10900 	 * We currently return "pass" instead of "skip", so we'll end up
10901 	 * going through the rest of the queue to check for overlapped tags.
10902 	 *
10903 	 * XXX KDM check for other types of blockage first??
10904 	 */
10905 	if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10906 		return (CTL_ACTION_PASS);
10907 
10908 	/*
10909 	 * Ordered tags have to block until all items ahead of them
10910 	 * have completed.  If we get called with an ordered tag, we always
10911 	 * block, if something else is ahead of us in the queue.
10912 	 */
10913 	if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
10914 		return (CTL_ACTION_BLOCK);
10915 
10916 	/*
10917 	 * Simple tags get blocked until all head of queue and ordered tags
10918 	 * ahead of them have completed.  I'm lumping untagged commands in
10919 	 * with simple tags here.  XXX KDM is that the right thing to do?
10920 	 */
10921 	if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10922 	  || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
10923 	 && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10924 	  || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
10925 		return (CTL_ACTION_BLOCK);
10926 
10927 	pending_entry = ctl_get_cmd_entry(&pending_io->scsiio, NULL);
10928 	ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio, NULL);
10929 
10930 	serialize_row = ctl_serialize_table[ooa_entry->seridx];
10931 
10932 	switch (serialize_row[pending_entry->seridx]) {
10933 	case CTL_SER_BLOCK:
10934 		return (CTL_ACTION_BLOCK);
10935 	case CTL_SER_EXTENT:
10936 		return (ctl_extent_check(ooa_io, pending_io,
10937 		    (lun->serseq == CTL_LUN_SERSEQ_ON)));
10938 	case CTL_SER_EXTENTOPT:
10939 		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
10940 		    & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
10941 			return (ctl_extent_check(ooa_io, pending_io,
10942 			    (lun->serseq == CTL_LUN_SERSEQ_ON)));
10943 		return (CTL_ACTION_PASS);
10944 	case CTL_SER_EXTENTSEQ:
10945 		if (lun->serseq != CTL_LUN_SERSEQ_OFF)
10946 			return (ctl_extent_check_seq(ooa_io, pending_io));
10947 		return (CTL_ACTION_PASS);
10948 	case CTL_SER_PASS:
10949 		return (CTL_ACTION_PASS);
10950 	case CTL_SER_BLOCKOPT:
10951 		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
10952 		    & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
10953 			return (CTL_ACTION_BLOCK);
10954 		return (CTL_ACTION_PASS);
10955 	case CTL_SER_SKIP:
10956 		return (CTL_ACTION_SKIP);
10957 	default:
10958 		panic("invalid serialization value %d",
10959 		      serialize_row[pending_entry->seridx]);
10960 	}
10961 
10962 	return (CTL_ACTION_ERROR);
10963 }
10964 
10965 /*
10966  * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
10967  * Assumptions:
10968  * - pending_io is generally either incoming, or on the blocked queue
10969  * - starting I/O is the I/O we want to start the check with.
10970  */
10971 static ctl_action
10972 ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
10973 	      union ctl_io *starting_io)
10974 {
10975 	union ctl_io *ooa_io;
10976 	ctl_action action;
10977 
10978 	mtx_assert(&lun->lun_lock, MA_OWNED);
10979 
10980 	/*
10981 	 * Run back along the OOA queue, starting with the current
10982 	 * blocked I/O and going through every I/O before it on the
10983 	 * queue.  If starting_io is NULL, we'll just end up returning
10984 	 * CTL_ACTION_PASS.
10985 	 */
10986 	for (ooa_io = starting_io; ooa_io != NULL;
10987 	     ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
10988 	     ooa_links)){
10989 
10990 		/*
10991 		 * This routine just checks to see whether
10992 		 * cur_blocked is blocked by ooa_io, which is ahead
10993 		 * of it in the queue.  It doesn't queue/dequeue
10994 		 * cur_blocked.
10995 		 */
10996 		action = ctl_check_for_blockage(lun, pending_io, ooa_io);
10997 		switch (action) {
10998 		case CTL_ACTION_BLOCK:
10999 		case CTL_ACTION_OVERLAP:
11000 		case CTL_ACTION_OVERLAP_TAG:
11001 		case CTL_ACTION_SKIP:
11002 		case CTL_ACTION_ERROR:
11003 			return (action);
11004 			break; /* NOTREACHED */
11005 		case CTL_ACTION_PASS:
11006 			break;
11007 		default:
11008 			panic("invalid action %d", action);
11009 			break;  /* NOTREACHED */
11010 		}
11011 	}
11012 
11013 	return (CTL_ACTION_PASS);
11014 }
11015 
11016 /*
11017  * Assumptions:
11018  * - An I/O has just completed, and has been removed from the per-LUN OOA
11019  *   queue, so some items on the blocked queue may now be unblocked.
11020  */
11021 static int
11022 ctl_check_blocked(struct ctl_lun *lun)
11023 {
11024 	union ctl_io *cur_blocked, *next_blocked;
11025 
11026 	mtx_assert(&lun->lun_lock, MA_OWNED);
11027 
11028 	/*
11029 	 * Run forward from the head of the blocked queue, checking each
11030 	 * entry against the I/Os prior to it on the OOA queue to see if
11031 	 * there is still any blockage.
11032 	 *
11033 	 * We cannot use the TAILQ_FOREACH() macro, because it can't deal
11034 	 * with our removing a variable on it while it is traversing the
11035 	 * list.
11036 	 */
11037 	for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
11038 	     cur_blocked != NULL; cur_blocked = next_blocked) {
11039 		union ctl_io *prev_ooa;
11040 		ctl_action action;
11041 
11042 		next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
11043 							  blocked_links);
11044 
11045 		prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
11046 						      ctl_ooaq, ooa_links);
11047 
11048 		/*
11049 		 * If cur_blocked happens to be the first item in the OOA
11050 		 * queue now, prev_ooa will be NULL, and the action
11051 		 * returned will just be CTL_ACTION_PASS.
11052 		 */
11053 		action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
11054 
11055 		switch (action) {
11056 		case CTL_ACTION_BLOCK:
11057 			/* Nothing to do here, still blocked */
11058 			break;
11059 		case CTL_ACTION_OVERLAP:
11060 		case CTL_ACTION_OVERLAP_TAG:
11061 			/*
11062 			 * This shouldn't happen!  In theory we've already
11063 			 * checked this command for overlap...
11064 			 */
11065 			break;
11066 		case CTL_ACTION_PASS:
11067 		case CTL_ACTION_SKIP: {
11068 			struct ctl_softc *softc;
11069 			const struct ctl_cmd_entry *entry;
11070 			int isc_retval;
11071 
11072 			/*
11073 			 * The skip case shouldn't happen, this transaction
11074 			 * should have never made it onto the blocked queue.
11075 			 */
11076 			/*
11077 			 * This I/O is no longer blocked, we can remove it
11078 			 * from the blocked queue.  Since this is a TAILQ
11079 			 * (doubly linked list), we can do O(1) removals
11080 			 * from any place on the list.
11081 			 */
11082 			TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
11083 				     blocked_links);
11084 			cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11085 
11086 			if (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC){
11087 				/*
11088 				 * Need to send IO back to original side to
11089 				 * run
11090 				 */
11091 				union ctl_ha_msg msg_info;
11092 
11093 				msg_info.hdr.original_sc =
11094 					cur_blocked->io_hdr.original_sc;
11095 				msg_info.hdr.serializing_sc = cur_blocked;
11096 				msg_info.hdr.msg_type = CTL_MSG_R2R;
11097 				if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11098 				     &msg_info, sizeof(msg_info), 0)) >
11099 				     CTL_HA_STATUS_SUCCESS) {
11100 					printf("CTL:Check Blocked error from "
11101 					       "ctl_ha_msg_send %d\n",
11102 					       isc_retval);
11103 				}
11104 				break;
11105 			}
11106 			entry = ctl_get_cmd_entry(&cur_blocked->scsiio, NULL);
11107 			softc = control_softc;
11108 
11109 			/*
11110 			 * Check this I/O for LUN state changes that may
11111 			 * have happened while this command was blocked.
11112 			 * The LUN state may have been changed by a command
11113 			 * ahead of us in the queue, so we need to re-check
11114 			 * for any states that can be caused by SCSI
11115 			 * commands.
11116 			 */
11117 			if (ctl_scsiio_lun_check(softc, lun, entry,
11118 						 &cur_blocked->scsiio) == 0) {
11119 				cur_blocked->io_hdr.flags |=
11120 				                      CTL_FLAG_IS_WAS_ON_RTR;
11121 				ctl_enqueue_rtr(cur_blocked);
11122 			} else
11123 				ctl_done(cur_blocked);
11124 			break;
11125 		}
11126 		default:
11127 			/*
11128 			 * This probably shouldn't happen -- we shouldn't
11129 			 * get CTL_ACTION_ERROR, or anything else.
11130 			 */
11131 			break;
11132 		}
11133 	}
11134 
11135 	return (CTL_RETVAL_COMPLETE);
11136 }
11137 
11138 /*
11139  * This routine (with one exception) checks LUN flags that can be set by
11140  * commands ahead of us in the OOA queue.  These flags have to be checked
11141  * when a command initially comes in, and when we pull a command off the
11142  * blocked queue and are preparing to execute it.  The reason we have to
11143  * check these flags for commands on the blocked queue is that the LUN
11144  * state may have been changed by a command ahead of us while we're on the
11145  * blocked queue.
11146  *
11147  * Ordering is somewhat important with these checks, so please pay
11148  * careful attention to the placement of any new checks.
11149  */
11150 static int
11151 ctl_scsiio_lun_check(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
11152     const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11153 {
11154 	int retval;
11155 	uint32_t residx;
11156 
11157 	retval = 0;
11158 
11159 	mtx_assert(&lun->lun_lock, MA_OWNED);
11160 
11161 	/*
11162 	 * If this shelf is a secondary shelf controller, we have to reject
11163 	 * any media access commands.
11164 	 */
11165 	if ((ctl_softc->flags & CTL_FLAG_ACTIVE_SHELF) == 0 &&
11166 	    (entry->flags & CTL_CMD_FLAG_OK_ON_SECONDARY) == 0) {
11167 		ctl_set_lun_standby(ctsio);
11168 		retval = 1;
11169 		goto bailout;
11170 	}
11171 
11172 	if (entry->pattern & CTL_LUN_PAT_WRITE) {
11173 		if (lun->flags & CTL_LUN_READONLY) {
11174 			ctl_set_sense(ctsio, /*current_error*/ 1,
11175 			    /*sense_key*/ SSD_KEY_DATA_PROTECT,
11176 			    /*asc*/ 0x27, /*ascq*/ 0x01, SSD_ELEM_NONE);
11177 			retval = 1;
11178 			goto bailout;
11179 		}
11180 		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT]
11181 		    .eca_and_aen & SCP_SWP) != 0) {
11182 			ctl_set_sense(ctsio, /*current_error*/ 1,
11183 			    /*sense_key*/ SSD_KEY_DATA_PROTECT,
11184 			    /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
11185 			retval = 1;
11186 			goto bailout;
11187 		}
11188 	}
11189 
11190 	/*
11191 	 * Check for a reservation conflict.  If this command isn't allowed
11192 	 * even on reserved LUNs, and if this initiator isn't the one who
11193 	 * reserved us, reject the command with a reservation conflict.
11194 	 */
11195 	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
11196 	if ((lun->flags & CTL_LUN_RESERVED)
11197 	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11198 		if (lun->res_idx != residx) {
11199 			ctl_set_reservation_conflict(ctsio);
11200 			retval = 1;
11201 			goto bailout;
11202 		}
11203 	}
11204 
11205 	if ((lun->flags & CTL_LUN_PR_RESERVED) == 0 ||
11206 	    (entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV)) {
11207 		/* No reservation or command is allowed. */;
11208 	} else if ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_WRESV) &&
11209 	    (lun->res_type == SPR_TYPE_WR_EX ||
11210 	     lun->res_type == SPR_TYPE_WR_EX_RO ||
11211 	     lun->res_type == SPR_TYPE_WR_EX_AR)) {
11212 		/* The command is allowed for Write Exclusive resv. */;
11213 	} else {
11214 		/*
11215 		 * if we aren't registered or it's a res holder type
11216 		 * reservation and this isn't the res holder then set a
11217 		 * conflict.
11218 		 */
11219 		if (ctl_get_prkey(lun, residx) == 0
11220 		 || (residx != lun->pr_res_idx && lun->res_type < 4)) {
11221 			ctl_set_reservation_conflict(ctsio);
11222 			retval = 1;
11223 			goto bailout;
11224 		}
11225 
11226 	}
11227 
11228 	if ((lun->flags & CTL_LUN_OFFLINE)
11229 	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_OFFLINE) == 0)) {
11230 		ctl_set_lun_not_ready(ctsio);
11231 		retval = 1;
11232 		goto bailout;
11233 	}
11234 
11235 	/*
11236 	 * If the LUN is stopped, see if this particular command is allowed
11237 	 * for a stopped lun.  Otherwise, reject it with 0x04,0x02.
11238 	 */
11239 	if ((lun->flags & CTL_LUN_STOPPED)
11240 	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_STOPPED) == 0)) {
11241 		/* "Logical unit not ready, initializing cmd. required" */
11242 		ctl_set_lun_stopped(ctsio);
11243 		retval = 1;
11244 		goto bailout;
11245 	}
11246 
11247 	if ((lun->flags & CTL_LUN_INOPERABLE)
11248 	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_INOPERABLE) == 0)) {
11249 		/* "Medium format corrupted" */
11250 		ctl_set_medium_format_corrupted(ctsio);
11251 		retval = 1;
11252 		goto bailout;
11253 	}
11254 
11255 bailout:
11256 	return (retval);
11257 
11258 }
11259 
11260 static void
11261 ctl_failover_io(union ctl_io *io, int have_lock)
11262 {
11263 	ctl_set_busy(&io->scsiio);
11264 	ctl_done(io);
11265 }
11266 
11267 static void
11268 ctl_failover(void)
11269 {
11270 	struct ctl_lun *lun;
11271 	struct ctl_softc *ctl_softc;
11272 	union ctl_io *next_io, *pending_io;
11273 	union ctl_io *io;
11274 	int lun_idx;
11275 
11276 	ctl_softc = control_softc;
11277 
11278 	mtx_lock(&ctl_softc->ctl_lock);
11279 	/*
11280 	 * Remove any cmds from the other SC from the rtr queue.  These
11281 	 * will obviously only be for LUNs for which we're the primary.
11282 	 * We can't send status or get/send data for these commands.
11283 	 * Since they haven't been executed yet, we can just remove them.
11284 	 * We'll either abort them or delete them below, depending on
11285 	 * which HA mode we're in.
11286 	 */
11287 #ifdef notyet
11288 	mtx_lock(&ctl_softc->queue_lock);
11289 	for (io = (union ctl_io *)STAILQ_FIRST(&ctl_softc->rtr_queue);
11290 	     io != NULL; io = next_io) {
11291 		next_io = (union ctl_io *)STAILQ_NEXT(&io->io_hdr, links);
11292 		if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11293 			STAILQ_REMOVE(&ctl_softc->rtr_queue, &io->io_hdr,
11294 				      ctl_io_hdr, links);
11295 	}
11296 	mtx_unlock(&ctl_softc->queue_lock);
11297 #endif
11298 
11299 	for (lun_idx=0; lun_idx < ctl_softc->num_luns; lun_idx++) {
11300 		lun = ctl_softc->ctl_luns[lun_idx];
11301 		if (lun==NULL)
11302 			continue;
11303 
11304 		/*
11305 		 * Processor LUNs are primary on both sides.
11306 		 * XXX will this always be true?
11307 		 */
11308 		if (lun->be_lun->lun_type == T_PROCESSOR)
11309 			continue;
11310 
11311 		if ((lun->flags & CTL_LUN_PRIMARY_SC)
11312 		 && (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11313 			printf("FAILOVER: primary lun %d\n", lun_idx);
11314 		        /*
11315 			 * Remove all commands from the other SC. First from the
11316 			 * blocked queue then from the ooa queue. Once we have
11317 			 * removed them. Call ctl_check_blocked to see if there
11318 			 * is anything that can run.
11319 			 */
11320 			for (io = (union ctl_io *)TAILQ_FIRST(
11321 			     &lun->blocked_queue); io != NULL; io = next_io) {
11322 
11323 		        	next_io = (union ctl_io *)TAILQ_NEXT(
11324 				    &io->io_hdr, blocked_links);
11325 
11326 				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11327 					TAILQ_REMOVE(&lun->blocked_queue,
11328 						     &io->io_hdr,blocked_links);
11329 					io->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11330 					TAILQ_REMOVE(&lun->ooa_queue,
11331 						     &io->io_hdr, ooa_links);
11332 
11333 					ctl_free_io(io);
11334 				}
11335 			}
11336 
11337 			for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11338 	     		     io != NULL; io = next_io) {
11339 
11340 		        	next_io = (union ctl_io *)TAILQ_NEXT(
11341 				    &io->io_hdr, ooa_links);
11342 
11343 				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11344 
11345 					TAILQ_REMOVE(&lun->ooa_queue,
11346 						&io->io_hdr,
11347 					     	ooa_links);
11348 
11349 					ctl_free_io(io);
11350 				}
11351 			}
11352 			ctl_check_blocked(lun);
11353 		} else if ((lun->flags & CTL_LUN_PRIMARY_SC)
11354 			&& (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
11355 
11356 			printf("FAILOVER: primary lun %d\n", lun_idx);
11357 			/*
11358 			 * Abort all commands from the other SC.  We can't
11359 			 * send status back for them now.  These should get
11360 			 * cleaned up when they are completed or come out
11361 			 * for a datamove operation.
11362 			 */
11363 			for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11364 	     		     io != NULL; io = next_io) {
11365 		        	next_io = (union ctl_io *)TAILQ_NEXT(
11366 					&io->io_hdr, ooa_links);
11367 
11368 				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11369 					io->io_hdr.flags |= CTL_FLAG_ABORT;
11370 			}
11371 		} else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11372 			&& (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
11373 
11374 			printf("FAILOVER: secondary lun %d\n", lun_idx);
11375 
11376 			lun->flags |= CTL_LUN_PRIMARY_SC;
11377 
11378 			/*
11379 			 * We send all I/O that was sent to this controller
11380 			 * and redirected to the other side back with
11381 			 * busy status, and have the initiator retry it.
11382 			 * Figuring out how much data has been transferred,
11383 			 * etc. and picking up where we left off would be
11384 			 * very tricky.
11385 			 *
11386 			 * XXX KDM need to remove I/O from the blocked
11387 			 * queue as well!
11388 			 */
11389 			for (pending_io = (union ctl_io *)TAILQ_FIRST(
11390 			     &lun->ooa_queue); pending_io != NULL;
11391 			     pending_io = next_io) {
11392 
11393 				next_io =  (union ctl_io *)TAILQ_NEXT(
11394 					&pending_io->io_hdr, ooa_links);
11395 
11396 				pending_io->io_hdr.flags &=
11397 					~CTL_FLAG_SENT_2OTHER_SC;
11398 
11399 				if (pending_io->io_hdr.flags &
11400 				    CTL_FLAG_IO_ACTIVE) {
11401 					pending_io->io_hdr.flags |=
11402 						CTL_FLAG_FAILOVER;
11403 				} else {
11404 					ctl_set_busy(&pending_io->scsiio);
11405 					ctl_done(pending_io);
11406 				}
11407 			}
11408 
11409 			ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
11410 		} else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11411 			&& (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11412 			printf("FAILOVER: secondary lun %d\n", lun_idx);
11413 			/*
11414 			 * if the first io on the OOA is not on the RtR queue
11415 			 * add it.
11416 			 */
11417 			lun->flags |= CTL_LUN_PRIMARY_SC;
11418 
11419 			pending_io = (union ctl_io *)TAILQ_FIRST(
11420 			    &lun->ooa_queue);
11421 			if (pending_io==NULL) {
11422 				printf("Nothing on OOA queue\n");
11423 				continue;
11424 			}
11425 
11426 			pending_io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11427 			if ((pending_io->io_hdr.flags &
11428 			     CTL_FLAG_IS_WAS_ON_RTR) == 0) {
11429 				pending_io->io_hdr.flags |=
11430 				    CTL_FLAG_IS_WAS_ON_RTR;
11431 				ctl_enqueue_rtr(pending_io);
11432 			}
11433 #if 0
11434 			else
11435 			{
11436 				printf("Tag 0x%04x is running\n",
11437 				      pending_io->scsiio.tag_num);
11438 			}
11439 #endif
11440 
11441 			next_io = (union ctl_io *)TAILQ_NEXT(
11442 			    &pending_io->io_hdr, ooa_links);
11443 			for (pending_io=next_io; pending_io != NULL;
11444 			     pending_io = next_io) {
11445 				pending_io->io_hdr.flags &=
11446 				    ~CTL_FLAG_SENT_2OTHER_SC;
11447 				next_io = (union ctl_io *)TAILQ_NEXT(
11448 					&pending_io->io_hdr, ooa_links);
11449 				if (pending_io->io_hdr.flags &
11450 				    CTL_FLAG_IS_WAS_ON_RTR) {
11451 #if 0
11452 				        printf("Tag 0x%04x is running\n",
11453 				      		pending_io->scsiio.tag_num);
11454 #endif
11455 					continue;
11456 				}
11457 
11458 				switch (ctl_check_ooa(lun, pending_io,
11459 			            (union ctl_io *)TAILQ_PREV(
11460 				    &pending_io->io_hdr, ctl_ooaq,
11461 				    ooa_links))) {
11462 
11463 				case CTL_ACTION_BLOCK:
11464 					TAILQ_INSERT_TAIL(&lun->blocked_queue,
11465 							  &pending_io->io_hdr,
11466 							  blocked_links);
11467 					pending_io->io_hdr.flags |=
11468 					    CTL_FLAG_BLOCKED;
11469 					break;
11470 				case CTL_ACTION_PASS:
11471 				case CTL_ACTION_SKIP:
11472 					pending_io->io_hdr.flags |=
11473 					    CTL_FLAG_IS_WAS_ON_RTR;
11474 					ctl_enqueue_rtr(pending_io);
11475 					break;
11476 				case CTL_ACTION_OVERLAP:
11477 					ctl_set_overlapped_cmd(
11478 					    (struct ctl_scsiio *)pending_io);
11479 					ctl_done(pending_io);
11480 					break;
11481 				case CTL_ACTION_OVERLAP_TAG:
11482 					ctl_set_overlapped_tag(
11483 					    (struct ctl_scsiio *)pending_io,
11484 					    pending_io->scsiio.tag_num & 0xff);
11485 					ctl_done(pending_io);
11486 					break;
11487 				case CTL_ACTION_ERROR:
11488 				default:
11489 					ctl_set_internal_failure(
11490 						(struct ctl_scsiio *)pending_io,
11491 						0,  // sks_valid
11492 						0); //retry count
11493 					ctl_done(pending_io);
11494 					break;
11495 				}
11496 			}
11497 
11498 			ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
11499 		} else {
11500 			panic("Unhandled HA mode failover, LUN flags = %#x, "
11501 			      "ha_mode = #%x", lun->flags, ctl_softc->ha_mode);
11502 		}
11503 	}
11504 	ctl_pause_rtr = 0;
11505 	mtx_unlock(&ctl_softc->ctl_lock);
11506 }
11507 
11508 static int
11509 ctl_scsiio_precheck(struct ctl_softc *ctl_softc, struct ctl_scsiio *ctsio)
11510 {
11511 	struct ctl_lun *lun;
11512 	const struct ctl_cmd_entry *entry;
11513 	uint32_t initidx, targ_lun;
11514 	int retval;
11515 
11516 	retval = 0;
11517 
11518 	lun = NULL;
11519 
11520 	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11521 	if ((targ_lun < CTL_MAX_LUNS)
11522 	 && ((lun = ctl_softc->ctl_luns[targ_lun]) != NULL)) {
11523 		/*
11524 		 * If the LUN is invalid, pretend that it doesn't exist.
11525 		 * It will go away as soon as all pending I/O has been
11526 		 * completed.
11527 		 */
11528 		mtx_lock(&lun->lun_lock);
11529 		if (lun->flags & CTL_LUN_DISABLED) {
11530 			mtx_unlock(&lun->lun_lock);
11531 			lun = NULL;
11532 			ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11533 			ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11534 		} else {
11535 			ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
11536 			ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr =
11537 				lun->be_lun;
11538 			if (lun->be_lun->lun_type == T_PROCESSOR) {
11539 				ctsio->io_hdr.flags |= CTL_FLAG_CONTROL_DEV;
11540 			}
11541 
11542 			/*
11543 			 * Every I/O goes into the OOA queue for a
11544 			 * particular LUN, and stays there until completion.
11545 			 */
11546 			TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr,
11547 			    ooa_links);
11548 		}
11549 	} else {
11550 		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11551 		ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11552 	}
11553 
11554 	/* Get command entry and return error if it is unsuppotyed. */
11555 	entry = ctl_validate_command(ctsio);
11556 	if (entry == NULL) {
11557 		if (lun)
11558 			mtx_unlock(&lun->lun_lock);
11559 		return (retval);
11560 	}
11561 
11562 	ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11563 	ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11564 
11565 	/*
11566 	 * Check to see whether we can send this command to LUNs that don't
11567 	 * exist.  This should pretty much only be the case for inquiry
11568 	 * and request sense.  Further checks, below, really require having
11569 	 * a LUN, so we can't really check the command anymore.  Just put
11570 	 * it on the rtr queue.
11571 	 */
11572 	if (lun == NULL) {
11573 		if (entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) {
11574 			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11575 			ctl_enqueue_rtr((union ctl_io *)ctsio);
11576 			return (retval);
11577 		}
11578 
11579 		ctl_set_unsupported_lun(ctsio);
11580 		ctl_done((union ctl_io *)ctsio);
11581 		CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11582 		return (retval);
11583 	} else {
11584 		/*
11585 		 * Make sure we support this particular command on this LUN.
11586 		 * e.g., we don't support writes to the control LUN.
11587 		 */
11588 		if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11589 			mtx_unlock(&lun->lun_lock);
11590 			ctl_set_invalid_opcode(ctsio);
11591 			ctl_done((union ctl_io *)ctsio);
11592 			return (retval);
11593 		}
11594 	}
11595 
11596 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11597 
11598 #ifdef CTL_WITH_CA
11599 	/*
11600 	 * If we've got a request sense, it'll clear the contingent
11601 	 * allegiance condition.  Otherwise, if we have a CA condition for
11602 	 * this initiator, clear it, because it sent down a command other
11603 	 * than request sense.
11604 	 */
11605 	if ((ctsio->cdb[0] != REQUEST_SENSE)
11606 	 && (ctl_is_set(lun->have_ca, initidx)))
11607 		ctl_clear_mask(lun->have_ca, initidx);
11608 #endif
11609 
11610 	/*
11611 	 * If the command has this flag set, it handles its own unit
11612 	 * attention reporting, we shouldn't do anything.  Otherwise we
11613 	 * check for any pending unit attentions, and send them back to the
11614 	 * initiator.  We only do this when a command initially comes in,
11615 	 * not when we pull it off the blocked queue.
11616 	 *
11617 	 * According to SAM-3, section 5.3.2, the order that things get
11618 	 * presented back to the host is basically unit attentions caused
11619 	 * by some sort of reset event, busy status, reservation conflicts
11620 	 * or task set full, and finally any other status.
11621 	 *
11622 	 * One issue here is that some of the unit attentions we report
11623 	 * don't fall into the "reset" category (e.g. "reported luns data
11624 	 * has changed").  So reporting it here, before the reservation
11625 	 * check, may be technically wrong.  I guess the only thing to do
11626 	 * would be to check for and report the reset events here, and then
11627 	 * check for the other unit attention types after we check for a
11628 	 * reservation conflict.
11629 	 *
11630 	 * XXX KDM need to fix this
11631 	 */
11632 	if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11633 		ctl_ua_type ua_type;
11634 		scsi_sense_data_type sense_format;
11635 
11636 		if (lun->flags & CTL_LUN_SENSE_DESC)
11637 			sense_format = SSD_TYPE_DESC;
11638 		else
11639 			sense_format = SSD_TYPE_FIXED;
11640 
11641 		ua_type = ctl_build_ua(lun, initidx, &ctsio->sense_data,
11642 		    sense_format);
11643 		if (ua_type != CTL_UA_NONE) {
11644 			mtx_unlock(&lun->lun_lock);
11645 			ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11646 			ctsio->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
11647 			ctsio->sense_len = SSD_FULL_SIZE;
11648 			ctl_done((union ctl_io *)ctsio);
11649 			return (retval);
11650 		}
11651 	}
11652 
11653 
11654 	if (ctl_scsiio_lun_check(ctl_softc, lun, entry, ctsio) != 0) {
11655 		mtx_unlock(&lun->lun_lock);
11656 		ctl_done((union ctl_io *)ctsio);
11657 		return (retval);
11658 	}
11659 
11660 	/*
11661 	 * XXX CHD this is where we want to send IO to other side if
11662 	 * this LUN is secondary on this SC. We will need to make a copy
11663 	 * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11664 	 * the copy we send as FROM_OTHER.
11665 	 * We also need to stuff the address of the original IO so we can
11666 	 * find it easily. Something similar will need be done on the other
11667 	 * side so when we are done we can find the copy.
11668 	 */
11669 	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11670 		union ctl_ha_msg msg_info;
11671 		int isc_retval;
11672 
11673 		ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11674 
11675 		msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11676 		msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11677 #if 0
11678 		printf("1. ctsio %p\n", ctsio);
11679 #endif
11680 		msg_info.hdr.serializing_sc = NULL;
11681 		msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11682 		msg_info.scsi.tag_num = ctsio->tag_num;
11683 		msg_info.scsi.tag_type = ctsio->tag_type;
11684 		memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11685 
11686 		ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11687 
11688 		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11689 		    (void *)&msg_info, sizeof(msg_info), 0)) >
11690 		    CTL_HA_STATUS_SUCCESS) {
11691 			printf("CTL:precheck, ctl_ha_msg_send returned %d\n",
11692 			       isc_retval);
11693 			printf("CTL:opcode is %x\n", ctsio->cdb[0]);
11694 		} else {
11695 #if 0
11696 			printf("CTL:Precheck sent msg, opcode is %x\n",opcode);
11697 #endif
11698 		}
11699 
11700 		/*
11701 		 * XXX KDM this I/O is off the incoming queue, but hasn't
11702 		 * been inserted on any other queue.  We may need to come
11703 		 * up with a holding queue while we wait for serialization
11704 		 * so that we have an idea of what we're waiting for from
11705 		 * the other side.
11706 		 */
11707 		mtx_unlock(&lun->lun_lock);
11708 		return (retval);
11709 	}
11710 
11711 	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11712 			      (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11713 			      ctl_ooaq, ooa_links))) {
11714 	case CTL_ACTION_BLOCK:
11715 		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11716 		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11717 				  blocked_links);
11718 		mtx_unlock(&lun->lun_lock);
11719 		return (retval);
11720 	case CTL_ACTION_PASS:
11721 	case CTL_ACTION_SKIP:
11722 		ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11723 		mtx_unlock(&lun->lun_lock);
11724 		ctl_enqueue_rtr((union ctl_io *)ctsio);
11725 		break;
11726 	case CTL_ACTION_OVERLAP:
11727 		mtx_unlock(&lun->lun_lock);
11728 		ctl_set_overlapped_cmd(ctsio);
11729 		ctl_done((union ctl_io *)ctsio);
11730 		break;
11731 	case CTL_ACTION_OVERLAP_TAG:
11732 		mtx_unlock(&lun->lun_lock);
11733 		ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11734 		ctl_done((union ctl_io *)ctsio);
11735 		break;
11736 	case CTL_ACTION_ERROR:
11737 	default:
11738 		mtx_unlock(&lun->lun_lock);
11739 		ctl_set_internal_failure(ctsio,
11740 					 /*sks_valid*/ 0,
11741 					 /*retry_count*/ 0);
11742 		ctl_done((union ctl_io *)ctsio);
11743 		break;
11744 	}
11745 	return (retval);
11746 }
11747 
11748 const struct ctl_cmd_entry *
11749 ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11750 {
11751 	const struct ctl_cmd_entry *entry;
11752 	int service_action;
11753 
11754 	entry = &ctl_cmd_table[ctsio->cdb[0]];
11755 	if (sa)
11756 		*sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11757 	if (entry->flags & CTL_CMD_FLAG_SA5) {
11758 		service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11759 		entry = &((const struct ctl_cmd_entry *)
11760 		    entry->execute)[service_action];
11761 	}
11762 	return (entry);
11763 }
11764 
11765 const struct ctl_cmd_entry *
11766 ctl_validate_command(struct ctl_scsiio *ctsio)
11767 {
11768 	const struct ctl_cmd_entry *entry;
11769 	int i, sa;
11770 	uint8_t diff;
11771 
11772 	entry = ctl_get_cmd_entry(ctsio, &sa);
11773 	if (entry->execute == NULL) {
11774 		if (sa)
11775 			ctl_set_invalid_field(ctsio,
11776 					      /*sks_valid*/ 1,
11777 					      /*command*/ 1,
11778 					      /*field*/ 1,
11779 					      /*bit_valid*/ 1,
11780 					      /*bit*/ 4);
11781 		else
11782 			ctl_set_invalid_opcode(ctsio);
11783 		ctl_done((union ctl_io *)ctsio);
11784 		return (NULL);
11785 	}
11786 	KASSERT(entry->length > 0,
11787 	    ("Not defined length for command 0x%02x/0x%02x",
11788 	     ctsio->cdb[0], ctsio->cdb[1]));
11789 	for (i = 1; i < entry->length; i++) {
11790 		diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11791 		if (diff == 0)
11792 			continue;
11793 		ctl_set_invalid_field(ctsio,
11794 				      /*sks_valid*/ 1,
11795 				      /*command*/ 1,
11796 				      /*field*/ i,
11797 				      /*bit_valid*/ 1,
11798 				      /*bit*/ fls(diff) - 1);
11799 		ctl_done((union ctl_io *)ctsio);
11800 		return (NULL);
11801 	}
11802 	return (entry);
11803 }
11804 
11805 static int
11806 ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11807 {
11808 
11809 	switch (lun_type) {
11810 	case T_PROCESSOR:
11811 		if (((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0) &&
11812 		    ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11813 			return (0);
11814 		break;
11815 	case T_DIRECT:
11816 		if (((entry->flags & CTL_CMD_FLAG_OK_ON_SLUN) == 0) &&
11817 		    ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11818 			return (0);
11819 		break;
11820 	default:
11821 		return (0);
11822 	}
11823 	return (1);
11824 }
11825 
11826 static int
11827 ctl_scsiio(struct ctl_scsiio *ctsio)
11828 {
11829 	int retval;
11830 	const struct ctl_cmd_entry *entry;
11831 
11832 	retval = CTL_RETVAL_COMPLETE;
11833 
11834 	CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11835 
11836 	entry = ctl_get_cmd_entry(ctsio, NULL);
11837 
11838 	/*
11839 	 * If this I/O has been aborted, just send it straight to
11840 	 * ctl_done() without executing it.
11841 	 */
11842 	if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11843 		ctl_done((union ctl_io *)ctsio);
11844 		goto bailout;
11845 	}
11846 
11847 	/*
11848 	 * All the checks should have been handled by ctl_scsiio_precheck().
11849 	 * We should be clear now to just execute the I/O.
11850 	 */
11851 	retval = entry->execute(ctsio);
11852 
11853 bailout:
11854 	return (retval);
11855 }
11856 
11857 /*
11858  * Since we only implement one target right now, a bus reset simply resets
11859  * our single target.
11860  */
11861 static int
11862 ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io)
11863 {
11864 	return(ctl_target_reset(ctl_softc, io, CTL_UA_BUS_RESET));
11865 }
11866 
11867 static int
11868 ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
11869 		 ctl_ua_type ua_type)
11870 {
11871 	struct ctl_lun *lun;
11872 	int retval;
11873 
11874 	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11875 		union ctl_ha_msg msg_info;
11876 
11877 		io->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11878 		msg_info.hdr.nexus = io->io_hdr.nexus;
11879 		if (ua_type==CTL_UA_TARG_RESET)
11880 			msg_info.task.task_action = CTL_TASK_TARGET_RESET;
11881 		else
11882 			msg_info.task.task_action = CTL_TASK_BUS_RESET;
11883 		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11884 		msg_info.hdr.original_sc = NULL;
11885 		msg_info.hdr.serializing_sc = NULL;
11886 		if (CTL_HA_STATUS_SUCCESS != ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11887 		    (void *)&msg_info, sizeof(msg_info), 0)) {
11888 		}
11889 	}
11890 	retval = 0;
11891 
11892 	mtx_lock(&ctl_softc->ctl_lock);
11893 	STAILQ_FOREACH(lun, &ctl_softc->lun_list, links)
11894 		retval += ctl_lun_reset(lun, io, ua_type);
11895 	mtx_unlock(&ctl_softc->ctl_lock);
11896 
11897 	return (retval);
11898 }
11899 
11900 /*
11901  * The LUN should always be set.  The I/O is optional, and is used to
11902  * distinguish between I/Os sent by this initiator, and by other
11903  * initiators.  We set unit attention for initiators other than this one.
11904  * SAM-3 is vague on this point.  It does say that a unit attention should
11905  * be established for other initiators when a LUN is reset (see section
11906  * 5.7.3), but it doesn't specifically say that the unit attention should
11907  * be established for this particular initiator when a LUN is reset.  Here
11908  * is the relevant text, from SAM-3 rev 8:
11909  *
11910  * 5.7.2 When a SCSI initiator port aborts its own tasks
11911  *
11912  * When a SCSI initiator port causes its own task(s) to be aborted, no
11913  * notification that the task(s) have been aborted shall be returned to
11914  * the SCSI initiator port other than the completion response for the
11915  * command or task management function action that caused the task(s) to
11916  * be aborted and notification(s) associated with related effects of the
11917  * action (e.g., a reset unit attention condition).
11918  *
11919  * XXX KDM for now, we're setting unit attention for all initiators.
11920  */
11921 static int
11922 ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
11923 {
11924 	union ctl_io *xio;
11925 #if 0
11926 	uint32_t initidx;
11927 #endif
11928 #ifdef CTL_WITH_CA
11929 	int i;
11930 #endif
11931 
11932 	mtx_lock(&lun->lun_lock);
11933 	/*
11934 	 * Run through the OOA queue and abort each I/O.
11935 	 */
11936 #if 0
11937 	TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
11938 #endif
11939 	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11940 	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11941 		xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
11942 	}
11943 
11944 	/*
11945 	 * This version sets unit attention for every
11946 	 */
11947 #if 0
11948 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
11949 	ctl_est_ua_all(lun, initidx, ua_type);
11950 #else
11951 	ctl_est_ua_all(lun, -1, ua_type);
11952 #endif
11953 
11954 	/*
11955 	 * A reset (any kind, really) clears reservations established with
11956 	 * RESERVE/RELEASE.  It does not clear reservations established
11957 	 * with PERSISTENT RESERVE OUT, but we don't support that at the
11958 	 * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
11959 	 * reservations made with the RESERVE/RELEASE commands, because
11960 	 * those commands are obsolete in SPC-3.
11961 	 */
11962 	lun->flags &= ~CTL_LUN_RESERVED;
11963 
11964 #ifdef CTL_WITH_CA
11965 	for (i = 0; i < CTL_MAX_INITIATORS; i++)
11966 		ctl_clear_mask(lun->have_ca, i);
11967 #endif
11968 	mtx_unlock(&lun->lun_lock);
11969 
11970 	return (0);
11971 }
11972 
11973 static void
11974 ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
11975     int other_sc)
11976 {
11977 	union ctl_io *xio;
11978 
11979 	mtx_assert(&lun->lun_lock, MA_OWNED);
11980 
11981 	/*
11982 	 * Run through the OOA queue and attempt to find the given I/O.
11983 	 * The target port, initiator ID, tag type and tag number have to
11984 	 * match the values that we got from the initiator.  If we have an
11985 	 * untagged command to abort, simply abort the first untagged command
11986 	 * we come to.  We only allow one untagged command at a time of course.
11987 	 */
11988 	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11989 	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11990 
11991 		if ((targ_port == UINT32_MAX ||
11992 		     targ_port == xio->io_hdr.nexus.targ_port) &&
11993 		    (init_id == UINT32_MAX ||
11994 		     init_id == xio->io_hdr.nexus.initid.id)) {
11995 			if (targ_port != xio->io_hdr.nexus.targ_port ||
11996 			    init_id != xio->io_hdr.nexus.initid.id)
11997 				xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
11998 			xio->io_hdr.flags |= CTL_FLAG_ABORT;
11999 			if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12000 				union ctl_ha_msg msg_info;
12001 
12002 				msg_info.hdr.nexus = xio->io_hdr.nexus;
12003 				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
12004 				msg_info.task.tag_num = xio->scsiio.tag_num;
12005 				msg_info.task.tag_type = xio->scsiio.tag_type;
12006 				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12007 				msg_info.hdr.original_sc = NULL;
12008 				msg_info.hdr.serializing_sc = NULL;
12009 				ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12010 				    (void *)&msg_info, sizeof(msg_info), 0);
12011 			}
12012 		}
12013 	}
12014 }
12015 
12016 static int
12017 ctl_abort_task_set(union ctl_io *io)
12018 {
12019 	struct ctl_softc *softc = control_softc;
12020 	struct ctl_lun *lun;
12021 	uint32_t targ_lun;
12022 
12023 	/*
12024 	 * Look up the LUN.
12025 	 */
12026 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12027 	mtx_lock(&softc->ctl_lock);
12028 	if ((targ_lun < CTL_MAX_LUNS) && (softc->ctl_luns[targ_lun] != NULL))
12029 		lun = softc->ctl_luns[targ_lun];
12030 	else {
12031 		mtx_unlock(&softc->ctl_lock);
12032 		return (1);
12033 	}
12034 
12035 	mtx_lock(&lun->lun_lock);
12036 	mtx_unlock(&softc->ctl_lock);
12037 	if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
12038 		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12039 		    io->io_hdr.nexus.initid.id,
12040 		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12041 	} else { /* CTL_TASK_CLEAR_TASK_SET */
12042 		ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
12043 		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12044 	}
12045 	mtx_unlock(&lun->lun_lock);
12046 	return (0);
12047 }
12048 
12049 static int
12050 ctl_i_t_nexus_reset(union ctl_io *io)
12051 {
12052 	struct ctl_softc *softc = control_softc;
12053 	struct ctl_lun *lun;
12054 	uint32_t initidx, residx;
12055 
12056 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
12057 	residx = ctl_get_resindex(&io->io_hdr.nexus);
12058 	mtx_lock(&softc->ctl_lock);
12059 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
12060 		mtx_lock(&lun->lun_lock);
12061 		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12062 		    io->io_hdr.nexus.initid.id,
12063 		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12064 #ifdef CTL_WITH_CA
12065 		ctl_clear_mask(lun->have_ca, initidx);
12066 #endif
12067 		if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
12068 			lun->flags &= ~CTL_LUN_RESERVED;
12069 		ctl_est_ua(lun, initidx, CTL_UA_I_T_NEXUS_LOSS);
12070 		mtx_unlock(&lun->lun_lock);
12071 	}
12072 	mtx_unlock(&softc->ctl_lock);
12073 	return (0);
12074 }
12075 
12076 static int
12077 ctl_abort_task(union ctl_io *io)
12078 {
12079 	union ctl_io *xio;
12080 	struct ctl_lun *lun;
12081 	struct ctl_softc *ctl_softc;
12082 #if 0
12083 	struct sbuf sb;
12084 	char printbuf[128];
12085 #endif
12086 	int found;
12087 	uint32_t targ_lun;
12088 
12089 	ctl_softc = control_softc;
12090 	found = 0;
12091 
12092 	/*
12093 	 * Look up the LUN.
12094 	 */
12095 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12096 	mtx_lock(&ctl_softc->ctl_lock);
12097 	if ((targ_lun < CTL_MAX_LUNS)
12098 	 && (ctl_softc->ctl_luns[targ_lun] != NULL))
12099 		lun = ctl_softc->ctl_luns[targ_lun];
12100 	else {
12101 		mtx_unlock(&ctl_softc->ctl_lock);
12102 		return (1);
12103 	}
12104 
12105 #if 0
12106 	printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
12107 	       lun->lun, io->taskio.tag_num, io->taskio.tag_type);
12108 #endif
12109 
12110 	mtx_lock(&lun->lun_lock);
12111 	mtx_unlock(&ctl_softc->ctl_lock);
12112 	/*
12113 	 * Run through the OOA queue and attempt to find the given I/O.
12114 	 * The target port, initiator ID, tag type and tag number have to
12115 	 * match the values that we got from the initiator.  If we have an
12116 	 * untagged command to abort, simply abort the first untagged command
12117 	 * we come to.  We only allow one untagged command at a time of course.
12118 	 */
12119 #if 0
12120 	TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
12121 #endif
12122 	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12123 	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12124 #if 0
12125 		sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
12126 
12127 		sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
12128 			    lun->lun, xio->scsiio.tag_num,
12129 			    xio->scsiio.tag_type,
12130 			    (xio->io_hdr.blocked_links.tqe_prev
12131 			    == NULL) ? "" : " BLOCKED",
12132 			    (xio->io_hdr.flags &
12133 			    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
12134 			    (xio->io_hdr.flags &
12135 			    CTL_FLAG_ABORT) ? " ABORT" : "",
12136 			    (xio->io_hdr.flags &
12137 			    CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
12138 		ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
12139 		sbuf_finish(&sb);
12140 		printf("%s\n", sbuf_data(&sb));
12141 #endif
12142 
12143 		if ((xio->io_hdr.nexus.targ_port == io->io_hdr.nexus.targ_port)
12144 		 && (xio->io_hdr.nexus.initid.id ==
12145 		     io->io_hdr.nexus.initid.id)) {
12146 			/*
12147 			 * If the abort says that the task is untagged, the
12148 			 * task in the queue must be untagged.  Otherwise,
12149 			 * we just check to see whether the tag numbers
12150 			 * match.  This is because the QLogic firmware
12151 			 * doesn't pass back the tag type in an abort
12152 			 * request.
12153 			 */
12154 #if 0
12155 			if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
12156 			  && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
12157 			 || (xio->scsiio.tag_num == io->taskio.tag_num)) {
12158 #endif
12159 			/*
12160 			 * XXX KDM we've got problems with FC, because it
12161 			 * doesn't send down a tag type with aborts.  So we
12162 			 * can only really go by the tag number...
12163 			 * This may cause problems with parallel SCSI.
12164 			 * Need to figure that out!!
12165 			 */
12166 			if (xio->scsiio.tag_num == io->taskio.tag_num) {
12167 				xio->io_hdr.flags |= CTL_FLAG_ABORT;
12168 				found = 1;
12169 				if ((io->io_hdr.flags &
12170 				     CTL_FLAG_FROM_OTHER_SC) == 0 &&
12171 				    !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12172 					union ctl_ha_msg msg_info;
12173 
12174 					io->io_hdr.flags |=
12175 					                CTL_FLAG_SENT_2OTHER_SC;
12176 					msg_info.hdr.nexus = io->io_hdr.nexus;
12177 					msg_info.task.task_action =
12178 						CTL_TASK_ABORT_TASK;
12179 					msg_info.task.tag_num =
12180 						io->taskio.tag_num;
12181 					msg_info.task.tag_type =
12182 						io->taskio.tag_type;
12183 					msg_info.hdr.msg_type =
12184 						CTL_MSG_MANAGE_TASKS;
12185 					msg_info.hdr.original_sc = NULL;
12186 					msg_info.hdr.serializing_sc = NULL;
12187 #if 0
12188 					printf("Sent Abort to other side\n");
12189 #endif
12190 					if (CTL_HA_STATUS_SUCCESS !=
12191 					        ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12192 		    				(void *)&msg_info,
12193 						sizeof(msg_info), 0)) {
12194 					}
12195 				}
12196 #if 0
12197 				printf("ctl_abort_task: found I/O to abort\n");
12198 #endif
12199 				break;
12200 			}
12201 		}
12202 	}
12203 	mtx_unlock(&lun->lun_lock);
12204 
12205 	if (found == 0) {
12206 		/*
12207 		 * This isn't really an error.  It's entirely possible for
12208 		 * the abort and command completion to cross on the wire.
12209 		 * This is more of an informative/diagnostic error.
12210 		 */
12211 #if 0
12212 		printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
12213 		       "%d:%d:%d:%d tag %d type %d\n",
12214 		       io->io_hdr.nexus.initid.id,
12215 		       io->io_hdr.nexus.targ_port,
12216 		       io->io_hdr.nexus.targ_target.id,
12217 		       io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
12218 		       io->taskio.tag_type);
12219 #endif
12220 	}
12221 	return (0);
12222 }
12223 
12224 static void
12225 ctl_run_task(union ctl_io *io)
12226 {
12227 	struct ctl_softc *ctl_softc = control_softc;
12228 	int retval = 1;
12229 	const char *task_desc;
12230 
12231 	CTL_DEBUG_PRINT(("ctl_run_task\n"));
12232 
12233 	KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12234 	    ("ctl_run_task: Unextected io_type %d\n",
12235 	     io->io_hdr.io_type));
12236 
12237 	task_desc = ctl_scsi_task_string(&io->taskio);
12238 	if (task_desc != NULL) {
12239 #ifdef NEEDTOPORT
12240 		csevent_log(CSC_CTL | CSC_SHELF_SW |
12241 			    CTL_TASK_REPORT,
12242 			    csevent_LogType_Trace,
12243 			    csevent_Severity_Information,
12244 			    csevent_AlertLevel_Green,
12245 			    csevent_FRU_Firmware,
12246 			    csevent_FRU_Unknown,
12247 			    "CTL: received task: %s",task_desc);
12248 #endif
12249 	} else {
12250 #ifdef NEEDTOPORT
12251 		csevent_log(CSC_CTL | CSC_SHELF_SW |
12252 			    CTL_TASK_REPORT,
12253 			    csevent_LogType_Trace,
12254 			    csevent_Severity_Information,
12255 			    csevent_AlertLevel_Green,
12256 			    csevent_FRU_Firmware,
12257 			    csevent_FRU_Unknown,
12258 			    "CTL: received unknown task "
12259 			    "type: %d (%#x)",
12260 			    io->taskio.task_action,
12261 			    io->taskio.task_action);
12262 #endif
12263 	}
12264 	switch (io->taskio.task_action) {
12265 	case CTL_TASK_ABORT_TASK:
12266 		retval = ctl_abort_task(io);
12267 		break;
12268 	case CTL_TASK_ABORT_TASK_SET:
12269 	case CTL_TASK_CLEAR_TASK_SET:
12270 		retval = ctl_abort_task_set(io);
12271 		break;
12272 	case CTL_TASK_CLEAR_ACA:
12273 		break;
12274 	case CTL_TASK_I_T_NEXUS_RESET:
12275 		retval = ctl_i_t_nexus_reset(io);
12276 		break;
12277 	case CTL_TASK_LUN_RESET: {
12278 		struct ctl_lun *lun;
12279 		uint32_t targ_lun;
12280 
12281 		targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12282 		mtx_lock(&ctl_softc->ctl_lock);
12283 		if ((targ_lun < CTL_MAX_LUNS)
12284 		 && (ctl_softc->ctl_luns[targ_lun] != NULL))
12285 			lun = ctl_softc->ctl_luns[targ_lun];
12286 		else {
12287 			mtx_unlock(&ctl_softc->ctl_lock);
12288 			retval = 1;
12289 			break;
12290 		}
12291 
12292 		if (!(io->io_hdr.flags &
12293 		    CTL_FLAG_FROM_OTHER_SC)) {
12294 			union ctl_ha_msg msg_info;
12295 
12296 			io->io_hdr.flags |=
12297 				CTL_FLAG_SENT_2OTHER_SC;
12298 			msg_info.hdr.msg_type =
12299 				CTL_MSG_MANAGE_TASKS;
12300 			msg_info.hdr.nexus = io->io_hdr.nexus;
12301 			msg_info.task.task_action =
12302 				CTL_TASK_LUN_RESET;
12303 			msg_info.hdr.original_sc = NULL;
12304 			msg_info.hdr.serializing_sc = NULL;
12305 			if (CTL_HA_STATUS_SUCCESS !=
12306 			    ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12307 			    (void *)&msg_info,
12308 			    sizeof(msg_info), 0)) {
12309 			}
12310 		}
12311 
12312 		retval = ctl_lun_reset(lun, io,
12313 				       CTL_UA_LUN_RESET);
12314 		mtx_unlock(&ctl_softc->ctl_lock);
12315 		break;
12316 	}
12317 	case CTL_TASK_TARGET_RESET:
12318 		retval = ctl_target_reset(ctl_softc, io, CTL_UA_TARG_RESET);
12319 		break;
12320 	case CTL_TASK_BUS_RESET:
12321 		retval = ctl_bus_reset(ctl_softc, io);
12322 		break;
12323 	case CTL_TASK_PORT_LOGIN:
12324 		break;
12325 	case CTL_TASK_PORT_LOGOUT:
12326 		break;
12327 	default:
12328 		printf("ctl_run_task: got unknown task management event %d\n",
12329 		       io->taskio.task_action);
12330 		break;
12331 	}
12332 	if (retval == 0)
12333 		io->io_hdr.status = CTL_SUCCESS;
12334 	else
12335 		io->io_hdr.status = CTL_ERROR;
12336 	ctl_done(io);
12337 }
12338 
12339 /*
12340  * For HA operation.  Handle commands that come in from the other
12341  * controller.
12342  */
12343 static void
12344 ctl_handle_isc(union ctl_io *io)
12345 {
12346 	int free_io;
12347 	struct ctl_lun *lun;
12348 	struct ctl_softc *ctl_softc;
12349 	uint32_t targ_lun;
12350 
12351 	ctl_softc = control_softc;
12352 
12353 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12354 	lun = ctl_softc->ctl_luns[targ_lun];
12355 
12356 	switch (io->io_hdr.msg_type) {
12357 	case CTL_MSG_SERIALIZE:
12358 		free_io = ctl_serialize_other_sc_cmd(&io->scsiio);
12359 		break;
12360 	case CTL_MSG_R2R: {
12361 		const struct ctl_cmd_entry *entry;
12362 
12363 		/*
12364 		 * This is only used in SER_ONLY mode.
12365 		 */
12366 		free_io = 0;
12367 		entry = ctl_get_cmd_entry(&io->scsiio, NULL);
12368 		mtx_lock(&lun->lun_lock);
12369 		if (ctl_scsiio_lun_check(ctl_softc, lun,
12370 		    entry, (struct ctl_scsiio *)io) != 0) {
12371 			mtx_unlock(&lun->lun_lock);
12372 			ctl_done(io);
12373 			break;
12374 		}
12375 		io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12376 		mtx_unlock(&lun->lun_lock);
12377 		ctl_enqueue_rtr(io);
12378 		break;
12379 	}
12380 	case CTL_MSG_FINISH_IO:
12381 		if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
12382 			free_io = 0;
12383 			ctl_done(io);
12384 		} else {
12385 			free_io = 1;
12386 			mtx_lock(&lun->lun_lock);
12387 			TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr,
12388 				     ooa_links);
12389 			ctl_check_blocked(lun);
12390 			mtx_unlock(&lun->lun_lock);
12391 		}
12392 		break;
12393 	case CTL_MSG_PERS_ACTION:
12394 		ctl_hndl_per_res_out_on_other_sc(
12395 			(union ctl_ha_msg *)&io->presio.pr_msg);
12396 		free_io = 1;
12397 		break;
12398 	case CTL_MSG_BAD_JUJU:
12399 		free_io = 0;
12400 		ctl_done(io);
12401 		break;
12402 	case CTL_MSG_DATAMOVE:
12403 		/* Only used in XFER mode */
12404 		free_io = 0;
12405 		ctl_datamove_remote(io);
12406 		break;
12407 	case CTL_MSG_DATAMOVE_DONE:
12408 		/* Only used in XFER mode */
12409 		free_io = 0;
12410 		io->scsiio.be_move_done(io);
12411 		break;
12412 	default:
12413 		free_io = 1;
12414 		printf("%s: Invalid message type %d\n",
12415 		       __func__, io->io_hdr.msg_type);
12416 		break;
12417 	}
12418 	if (free_io)
12419 		ctl_free_io(io);
12420 
12421 }
12422 
12423 
12424 /*
12425  * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12426  * there is no match.
12427  */
12428 static ctl_lun_error_pattern
12429 ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12430 {
12431 	const struct ctl_cmd_entry *entry;
12432 	ctl_lun_error_pattern filtered_pattern, pattern;
12433 
12434 	pattern = desc->error_pattern;
12435 
12436 	/*
12437 	 * XXX KDM we need more data passed into this function to match a
12438 	 * custom pattern, and we actually need to implement custom pattern
12439 	 * matching.
12440 	 */
12441 	if (pattern & CTL_LUN_PAT_CMD)
12442 		return (CTL_LUN_PAT_CMD);
12443 
12444 	if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12445 		return (CTL_LUN_PAT_ANY);
12446 
12447 	entry = ctl_get_cmd_entry(ctsio, NULL);
12448 
12449 	filtered_pattern = entry->pattern & pattern;
12450 
12451 	/*
12452 	 * If the user requested specific flags in the pattern (e.g.
12453 	 * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12454 	 * flags.
12455 	 *
12456 	 * If the user did not specify any flags, it doesn't matter whether
12457 	 * or not the command supports the flags.
12458 	 */
12459 	if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12460 	     (pattern & ~CTL_LUN_PAT_MASK))
12461 		return (CTL_LUN_PAT_NONE);
12462 
12463 	/*
12464 	 * If the user asked for a range check, see if the requested LBA
12465 	 * range overlaps with this command's LBA range.
12466 	 */
12467 	if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12468 		uint64_t lba1;
12469 		uint64_t len1;
12470 		ctl_action action;
12471 		int retval;
12472 
12473 		retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12474 		if (retval != 0)
12475 			return (CTL_LUN_PAT_NONE);
12476 
12477 		action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12478 					      desc->lba_range.len, FALSE);
12479 		/*
12480 		 * A "pass" means that the LBA ranges don't overlap, so
12481 		 * this doesn't match the user's range criteria.
12482 		 */
12483 		if (action == CTL_ACTION_PASS)
12484 			return (CTL_LUN_PAT_NONE);
12485 	}
12486 
12487 	return (filtered_pattern);
12488 }
12489 
12490 static void
12491 ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12492 {
12493 	struct ctl_error_desc *desc, *desc2;
12494 
12495 	mtx_assert(&lun->lun_lock, MA_OWNED);
12496 
12497 	STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12498 		ctl_lun_error_pattern pattern;
12499 		/*
12500 		 * Check to see whether this particular command matches
12501 		 * the pattern in the descriptor.
12502 		 */
12503 		pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12504 		if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12505 			continue;
12506 
12507 		switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12508 		case CTL_LUN_INJ_ABORTED:
12509 			ctl_set_aborted(&io->scsiio);
12510 			break;
12511 		case CTL_LUN_INJ_MEDIUM_ERR:
12512 			ctl_set_medium_error(&io->scsiio);
12513 			break;
12514 		case CTL_LUN_INJ_UA:
12515 			/* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12516 			 * OCCURRED */
12517 			ctl_set_ua(&io->scsiio, 0x29, 0x00);
12518 			break;
12519 		case CTL_LUN_INJ_CUSTOM:
12520 			/*
12521 			 * We're assuming the user knows what he is doing.
12522 			 * Just copy the sense information without doing
12523 			 * checks.
12524 			 */
12525 			bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12526 			      ctl_min(sizeof(desc->custom_sense),
12527 				      sizeof(io->scsiio.sense_data)));
12528 			io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12529 			io->scsiio.sense_len = SSD_FULL_SIZE;
12530 			io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12531 			break;
12532 		case CTL_LUN_INJ_NONE:
12533 		default:
12534 			/*
12535 			 * If this is an error injection type we don't know
12536 			 * about, clear the continuous flag (if it is set)
12537 			 * so it will get deleted below.
12538 			 */
12539 			desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12540 			break;
12541 		}
12542 		/*
12543 		 * By default, each error injection action is a one-shot
12544 		 */
12545 		if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12546 			continue;
12547 
12548 		STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12549 
12550 		free(desc, M_CTL);
12551 	}
12552 }
12553 
12554 #ifdef CTL_IO_DELAY
12555 static void
12556 ctl_datamove_timer_wakeup(void *arg)
12557 {
12558 	union ctl_io *io;
12559 
12560 	io = (union ctl_io *)arg;
12561 
12562 	ctl_datamove(io);
12563 }
12564 #endif /* CTL_IO_DELAY */
12565 
12566 void
12567 ctl_datamove(union ctl_io *io)
12568 {
12569 	void (*fe_datamove)(union ctl_io *io);
12570 
12571 	mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12572 
12573 	CTL_DEBUG_PRINT(("ctl_datamove\n"));
12574 
12575 #ifdef CTL_TIME_IO
12576 	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12577 		char str[256];
12578 		char path_str[64];
12579 		struct sbuf sb;
12580 
12581 		ctl_scsi_path_string(io, path_str, sizeof(path_str));
12582 		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12583 
12584 		sbuf_cat(&sb, path_str);
12585 		switch (io->io_hdr.io_type) {
12586 		case CTL_IO_SCSI:
12587 			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12588 			sbuf_printf(&sb, "\n");
12589 			sbuf_cat(&sb, path_str);
12590 			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12591 				    io->scsiio.tag_num, io->scsiio.tag_type);
12592 			break;
12593 		case CTL_IO_TASK:
12594 			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12595 				    "Tag Type: %d\n", io->taskio.task_action,
12596 				    io->taskio.tag_num, io->taskio.tag_type);
12597 			break;
12598 		default:
12599 			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12600 			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12601 			break;
12602 		}
12603 		sbuf_cat(&sb, path_str);
12604 		sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12605 			    (intmax_t)time_uptime - io->io_hdr.start_time);
12606 		sbuf_finish(&sb);
12607 		printf("%s", sbuf_data(&sb));
12608 	}
12609 #endif /* CTL_TIME_IO */
12610 
12611 #ifdef CTL_IO_DELAY
12612 	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12613 		struct ctl_lun *lun;
12614 
12615 		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12616 
12617 		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12618 	} else {
12619 		struct ctl_lun *lun;
12620 
12621 		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12622 		if ((lun != NULL)
12623 		 && (lun->delay_info.datamove_delay > 0)) {
12624 			struct callout *callout;
12625 
12626 			callout = (struct callout *)&io->io_hdr.timer_bytes;
12627 			callout_init(callout, /*mpsafe*/ 1);
12628 			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12629 			callout_reset(callout,
12630 				      lun->delay_info.datamove_delay * hz,
12631 				      ctl_datamove_timer_wakeup, io);
12632 			if (lun->delay_info.datamove_type ==
12633 			    CTL_DELAY_TYPE_ONESHOT)
12634 				lun->delay_info.datamove_delay = 0;
12635 			return;
12636 		}
12637 	}
12638 #endif
12639 
12640 	/*
12641 	 * This command has been aborted.  Set the port status, so we fail
12642 	 * the data move.
12643 	 */
12644 	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12645 		printf("ctl_datamove: tag 0x%04x on (%ju:%d:%ju:%d) aborted\n",
12646 		       io->scsiio.tag_num,(uintmax_t)io->io_hdr.nexus.initid.id,
12647 		       io->io_hdr.nexus.targ_port,
12648 		       (uintmax_t)io->io_hdr.nexus.targ_target.id,
12649 		       io->io_hdr.nexus.targ_lun);
12650 		io->io_hdr.port_status = 31337;
12651 		/*
12652 		 * Note that the backend, in this case, will get the
12653 		 * callback in its context.  In other cases it may get
12654 		 * called in the frontend's interrupt thread context.
12655 		 */
12656 		io->scsiio.be_move_done(io);
12657 		return;
12658 	}
12659 
12660 	/* Don't confuse frontend with zero length data move. */
12661 	if (io->scsiio.kern_data_len == 0) {
12662 		io->scsiio.be_move_done(io);
12663 		return;
12664 	}
12665 
12666 	/*
12667 	 * If we're in XFER mode and this I/O is from the other shelf
12668 	 * controller, we need to send the DMA to the other side to
12669 	 * actually transfer the data to/from the host.  In serialize only
12670 	 * mode the transfer happens below CTL and ctl_datamove() is only
12671 	 * called on the machine that originally received the I/O.
12672 	 */
12673 	if ((control_softc->ha_mode == CTL_HA_MODE_XFER)
12674 	 && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12675 		union ctl_ha_msg msg;
12676 		uint32_t sg_entries_sent;
12677 		int do_sg_copy;
12678 		int i;
12679 
12680 		memset(&msg, 0, sizeof(msg));
12681 		msg.hdr.msg_type = CTL_MSG_DATAMOVE;
12682 		msg.hdr.original_sc = io->io_hdr.original_sc;
12683 		msg.hdr.serializing_sc = io;
12684 		msg.hdr.nexus = io->io_hdr.nexus;
12685 		msg.dt.flags = io->io_hdr.flags;
12686 		/*
12687 		 * We convert everything into a S/G list here.  We can't
12688 		 * pass by reference, only by value between controllers.
12689 		 * So we can't pass a pointer to the S/G list, only as many
12690 		 * S/G entries as we can fit in here.  If it's possible for
12691 		 * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
12692 		 * then we need to break this up into multiple transfers.
12693 		 */
12694 		if (io->scsiio.kern_sg_entries == 0) {
12695 			msg.dt.kern_sg_entries = 1;
12696 			/*
12697 			 * If this is in cached memory, flush the cache
12698 			 * before we send the DMA request to the other
12699 			 * controller.  We want to do this in either the
12700 			 * read or the write case.  The read case is
12701 			 * straightforward.  In the write case, we want to
12702 			 * make sure nothing is in the local cache that
12703 			 * could overwrite the DMAed data.
12704 			 */
12705 			if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12706 				/*
12707 				 * XXX KDM use bus_dmamap_sync() here.
12708 				 */
12709 			}
12710 
12711 			/*
12712 			 * Convert to a physical address if this is a
12713 			 * virtual address.
12714 			 */
12715 			if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
12716 				msg.dt.sg_list[0].addr =
12717 					io->scsiio.kern_data_ptr;
12718 			} else {
12719 				/*
12720 				 * XXX KDM use busdma here!
12721 				 */
12722 #if 0
12723 				msg.dt.sg_list[0].addr = (void *)
12724 					vtophys(io->scsiio.kern_data_ptr);
12725 #endif
12726 			}
12727 
12728 			msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
12729 			do_sg_copy = 0;
12730 		} else {
12731 			struct ctl_sg_entry *sgl;
12732 
12733 			do_sg_copy = 1;
12734 			msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
12735 			sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
12736 			if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12737 				/*
12738 				 * XXX KDM use bus_dmamap_sync() here.
12739 				 */
12740 			}
12741 		}
12742 
12743 		msg.dt.kern_data_len = io->scsiio.kern_data_len;
12744 		msg.dt.kern_total_len = io->scsiio.kern_total_len;
12745 		msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
12746 		msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
12747 		msg.dt.sg_sequence = 0;
12748 
12749 		/*
12750 		 * Loop until we've sent all of the S/G entries.  On the
12751 		 * other end, we'll recompose these S/G entries into one
12752 		 * contiguous list before passing it to the
12753 		 */
12754 		for (sg_entries_sent = 0; sg_entries_sent <
12755 		     msg.dt.kern_sg_entries; msg.dt.sg_sequence++) {
12756 			msg.dt.cur_sg_entries = ctl_min((sizeof(msg.dt.sg_list)/
12757 				sizeof(msg.dt.sg_list[0])),
12758 				msg.dt.kern_sg_entries - sg_entries_sent);
12759 
12760 			if (do_sg_copy != 0) {
12761 				struct ctl_sg_entry *sgl;
12762 				int j;
12763 
12764 				sgl = (struct ctl_sg_entry *)
12765 					io->scsiio.kern_data_ptr;
12766 				/*
12767 				 * If this is in cached memory, flush the cache
12768 				 * before we send the DMA request to the other
12769 				 * controller.  We want to do this in either
12770 				 * the * read or the write case.  The read
12771 				 * case is straightforward.  In the write
12772 				 * case, we want to make sure nothing is
12773 				 * in the local cache that could overwrite
12774 				 * the DMAed data.
12775 				 */
12776 
12777 				for (i = sg_entries_sent, j = 0;
12778 				     i < msg.dt.cur_sg_entries; i++, j++) {
12779 					if ((io->io_hdr.flags &
12780 					     CTL_FLAG_NO_DATASYNC) == 0) {
12781 						/*
12782 						 * XXX KDM use bus_dmamap_sync()
12783 						 */
12784 					}
12785 					if ((io->io_hdr.flags &
12786 					     CTL_FLAG_BUS_ADDR) == 0) {
12787 						/*
12788 						 * XXX KDM use busdma.
12789 						 */
12790 #if 0
12791 						msg.dt.sg_list[j].addr =(void *)
12792 						       vtophys(sgl[i].addr);
12793 #endif
12794 					} else {
12795 						msg.dt.sg_list[j].addr =
12796 							sgl[i].addr;
12797 					}
12798 					msg.dt.sg_list[j].len = sgl[i].len;
12799 				}
12800 			}
12801 
12802 			sg_entries_sent += msg.dt.cur_sg_entries;
12803 			if (sg_entries_sent >= msg.dt.kern_sg_entries)
12804 				msg.dt.sg_last = 1;
12805 			else
12806 				msg.dt.sg_last = 0;
12807 
12808 			/*
12809 			 * XXX KDM drop and reacquire the lock here?
12810 			 */
12811 			if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12812 			    sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
12813 				/*
12814 				 * XXX do something here.
12815 				 */
12816 			}
12817 
12818 			msg.dt.sent_sg_entries = sg_entries_sent;
12819 		}
12820 		io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12821 		if (io->io_hdr.flags & CTL_FLAG_FAILOVER)
12822 			ctl_failover_io(io, /*have_lock*/ 0);
12823 
12824 	} else {
12825 
12826 		/*
12827 		 * Lookup the fe_datamove() function for this particular
12828 		 * front end.
12829 		 */
12830 		fe_datamove =
12831 		    control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12832 
12833 		fe_datamove(io);
12834 	}
12835 }
12836 
12837 static void
12838 ctl_send_datamove_done(union ctl_io *io, int have_lock)
12839 {
12840 	union ctl_ha_msg msg;
12841 	int isc_status;
12842 
12843 	memset(&msg, 0, sizeof(msg));
12844 
12845 	msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12846 	msg.hdr.original_sc = io;
12847 	msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12848 	msg.hdr.nexus = io->io_hdr.nexus;
12849 	msg.hdr.status = io->io_hdr.status;
12850 	msg.scsi.tag_num = io->scsiio.tag_num;
12851 	msg.scsi.tag_type = io->scsiio.tag_type;
12852 	msg.scsi.scsi_status = io->scsiio.scsi_status;
12853 	memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12854 	       sizeof(io->scsiio.sense_data));
12855 	msg.scsi.sense_len = io->scsiio.sense_len;
12856 	msg.scsi.sense_residual = io->scsiio.sense_residual;
12857 	msg.scsi.fetd_status = io->io_hdr.port_status;
12858 	msg.scsi.residual = io->scsiio.residual;
12859 	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12860 
12861 	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12862 		ctl_failover_io(io, /*have_lock*/ have_lock);
12863 		return;
12864 	}
12865 
12866 	isc_status = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0);
12867 	if (isc_status > CTL_HA_STATUS_SUCCESS) {
12868 		/* XXX do something if this fails */
12869 	}
12870 
12871 }
12872 
12873 /*
12874  * The DMA to the remote side is done, now we need to tell the other side
12875  * we're done so it can continue with its data movement.
12876  */
12877 static void
12878 ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12879 {
12880 	union ctl_io *io;
12881 
12882 	io = rq->context;
12883 
12884 	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12885 		printf("%s: ISC DMA write failed with error %d", __func__,
12886 		       rq->ret);
12887 		ctl_set_internal_failure(&io->scsiio,
12888 					 /*sks_valid*/ 1,
12889 					 /*retry_count*/ rq->ret);
12890 	}
12891 
12892 	ctl_dt_req_free(rq);
12893 
12894 	/*
12895 	 * In this case, we had to malloc the memory locally.  Free it.
12896 	 */
12897 	if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
12898 		int i;
12899 		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12900 			free(io->io_hdr.local_sglist[i].addr, M_CTL);
12901 	}
12902 	/*
12903 	 * The data is in local and remote memory, so now we need to send
12904 	 * status (good or back) back to the other side.
12905 	 */
12906 	ctl_send_datamove_done(io, /*have_lock*/ 0);
12907 }
12908 
12909 /*
12910  * We've moved the data from the host/controller into local memory.  Now we
12911  * need to push it over to the remote controller's memory.
12912  */
12913 static int
12914 ctl_datamove_remote_dm_write_cb(union ctl_io *io)
12915 {
12916 	int retval;
12917 
12918 	retval = 0;
12919 
12920 	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
12921 					  ctl_datamove_remote_write_cb);
12922 
12923 	return (retval);
12924 }
12925 
12926 static void
12927 ctl_datamove_remote_write(union ctl_io *io)
12928 {
12929 	int retval;
12930 	void (*fe_datamove)(union ctl_io *io);
12931 
12932 	/*
12933 	 * - Get the data from the host/HBA into local memory.
12934 	 * - DMA memory from the local controller to the remote controller.
12935 	 * - Send status back to the remote controller.
12936 	 */
12937 
12938 	retval = ctl_datamove_remote_sgl_setup(io);
12939 	if (retval != 0)
12940 		return;
12941 
12942 	/* Switch the pointer over so the FETD knows what to do */
12943 	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12944 
12945 	/*
12946 	 * Use a custom move done callback, since we need to send completion
12947 	 * back to the other controller, not to the backend on this side.
12948 	 */
12949 	io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
12950 
12951 	fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12952 
12953 	fe_datamove(io);
12954 
12955 	return;
12956 
12957 }
12958 
12959 static int
12960 ctl_datamove_remote_dm_read_cb(union ctl_io *io)
12961 {
12962 #if 0
12963 	char str[256];
12964 	char path_str[64];
12965 	struct sbuf sb;
12966 #endif
12967 
12968 	/*
12969 	 * In this case, we had to malloc the memory locally.  Free it.
12970 	 */
12971 	if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
12972 		int i;
12973 		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12974 			free(io->io_hdr.local_sglist[i].addr, M_CTL);
12975 	}
12976 
12977 #if 0
12978 	scsi_path_string(io, path_str, sizeof(path_str));
12979 	sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12980 	sbuf_cat(&sb, path_str);
12981 	scsi_command_string(&io->scsiio, NULL, &sb);
12982 	sbuf_printf(&sb, "\n");
12983 	sbuf_cat(&sb, path_str);
12984 	sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12985 		    io->scsiio.tag_num, io->scsiio.tag_type);
12986 	sbuf_cat(&sb, path_str);
12987 	sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
12988 		    io->io_hdr.flags, io->io_hdr.status);
12989 	sbuf_finish(&sb);
12990 	printk("%s", sbuf_data(&sb));
12991 #endif
12992 
12993 
12994 	/*
12995 	 * The read is done, now we need to send status (good or bad) back
12996 	 * to the other side.
12997 	 */
12998 	ctl_send_datamove_done(io, /*have_lock*/ 0);
12999 
13000 	return (0);
13001 }
13002 
13003 static void
13004 ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
13005 {
13006 	union ctl_io *io;
13007 	void (*fe_datamove)(union ctl_io *io);
13008 
13009 	io = rq->context;
13010 
13011 	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
13012 		printf("%s: ISC DMA read failed with error %d", __func__,
13013 		       rq->ret);
13014 		ctl_set_internal_failure(&io->scsiio,
13015 					 /*sks_valid*/ 1,
13016 					 /*retry_count*/ rq->ret);
13017 	}
13018 
13019 	ctl_dt_req_free(rq);
13020 
13021 	/* Switch the pointer over so the FETD knows what to do */
13022 	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
13023 
13024 	/*
13025 	 * Use a custom move done callback, since we need to send completion
13026 	 * back to the other controller, not to the backend on this side.
13027 	 */
13028 	io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
13029 
13030 	/* XXX KDM add checks like the ones in ctl_datamove? */
13031 
13032 	fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
13033 
13034 	fe_datamove(io);
13035 }
13036 
13037 static int
13038 ctl_datamove_remote_sgl_setup(union ctl_io *io)
13039 {
13040 	struct ctl_sg_entry *local_sglist, *remote_sglist;
13041 	struct ctl_sg_entry *local_dma_sglist, *remote_dma_sglist;
13042 	struct ctl_softc *softc;
13043 	int retval;
13044 	int i;
13045 
13046 	retval = 0;
13047 	softc = control_softc;
13048 
13049 	local_sglist = io->io_hdr.local_sglist;
13050 	local_dma_sglist = io->io_hdr.local_dma_sglist;
13051 	remote_sglist = io->io_hdr.remote_sglist;
13052 	remote_dma_sglist = io->io_hdr.remote_dma_sglist;
13053 
13054 	if (io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) {
13055 		for (i = 0; i < io->scsiio.kern_sg_entries; i++) {
13056 			local_sglist[i].len = remote_sglist[i].len;
13057 
13058 			/*
13059 			 * XXX Detect the situation where the RS-level I/O
13060 			 * redirector on the other side has already read the
13061 			 * data off of the AOR RS on this side, and
13062 			 * transferred it to remote (mirror) memory on the
13063 			 * other side.  Since we already have the data in
13064 			 * memory here, we just need to use it.
13065 			 *
13066 			 * XXX KDM this can probably be removed once we
13067 			 * get the cache device code in and take the
13068 			 * current AOR implementation out.
13069 			 */
13070 #ifdef NEEDTOPORT
13071 			if ((remote_sglist[i].addr >=
13072 			     (void *)vtophys(softc->mirr->addr))
13073 			 && (remote_sglist[i].addr <
13074 			     ((void *)vtophys(softc->mirr->addr) +
13075 			     CacheMirrorOffset))) {
13076 				local_sglist[i].addr = remote_sglist[i].addr -
13077 					CacheMirrorOffset;
13078 				if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13079 				     CTL_FLAG_DATA_IN)
13080 					io->io_hdr.flags |= CTL_FLAG_REDIR_DONE;
13081 			} else {
13082 				local_sglist[i].addr = remote_sglist[i].addr +
13083 					CacheMirrorOffset;
13084 			}
13085 #endif
13086 #if 0
13087 			printf("%s: local %p, remote %p, len %d\n",
13088 			       __func__, local_sglist[i].addr,
13089 			       remote_sglist[i].addr, local_sglist[i].len);
13090 #endif
13091 		}
13092 	} else {
13093 		uint32_t len_to_go;
13094 
13095 		/*
13096 		 * In this case, we don't have automatically allocated
13097 		 * memory for this I/O on this controller.  This typically
13098 		 * happens with internal CTL I/O -- e.g. inquiry, mode
13099 		 * sense, etc.  Anything coming from RAIDCore will have
13100 		 * a mirror area available.
13101 		 */
13102 		len_to_go = io->scsiio.kern_data_len;
13103 
13104 		/*
13105 		 * Clear the no datasync flag, we have to use malloced
13106 		 * buffers.
13107 		 */
13108 		io->io_hdr.flags &= ~CTL_FLAG_NO_DATASYNC;
13109 
13110 		/*
13111 		 * The difficult thing here is that the size of the various
13112 		 * S/G segments may be different than the size from the
13113 		 * remote controller.  That'll make it harder when DMAing
13114 		 * the data back to the other side.
13115 		 */
13116 		for (i = 0; (i < sizeof(io->io_hdr.remote_sglist) /
13117 		     sizeof(io->io_hdr.remote_sglist[0])) &&
13118 		     (len_to_go > 0); i++) {
13119 			local_sglist[i].len = ctl_min(len_to_go, 131072);
13120 			CTL_SIZE_8B(local_dma_sglist[i].len,
13121 				    local_sglist[i].len);
13122 			local_sglist[i].addr =
13123 				malloc(local_dma_sglist[i].len, M_CTL,M_WAITOK);
13124 
13125 			local_dma_sglist[i].addr = local_sglist[i].addr;
13126 
13127 			if (local_sglist[i].addr == NULL) {
13128 				int j;
13129 
13130 				printf("malloc failed for %zd bytes!",
13131 				       local_dma_sglist[i].len);
13132 				for (j = 0; j < i; j++) {
13133 					free(local_sglist[j].addr, M_CTL);
13134 				}
13135 				ctl_set_internal_failure(&io->scsiio,
13136 							 /*sks_valid*/ 1,
13137 							 /*retry_count*/ 4857);
13138 				retval = 1;
13139 				goto bailout_error;
13140 
13141 			}
13142 			/* XXX KDM do we need a sync here? */
13143 
13144 			len_to_go -= local_sglist[i].len;
13145 		}
13146 		/*
13147 		 * Reset the number of S/G entries accordingly.  The
13148 		 * original number of S/G entries is available in
13149 		 * rem_sg_entries.
13150 		 */
13151 		io->scsiio.kern_sg_entries = i;
13152 
13153 #if 0
13154 		printf("%s: kern_sg_entries = %d\n", __func__,
13155 		       io->scsiio.kern_sg_entries);
13156 		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13157 			printf("%s: sg[%d] = %p, %d (DMA: %d)\n", __func__, i,
13158 			       local_sglist[i].addr, local_sglist[i].len,
13159 			       local_dma_sglist[i].len);
13160 #endif
13161 	}
13162 
13163 
13164 	return (retval);
13165 
13166 bailout_error:
13167 
13168 	ctl_send_datamove_done(io, /*have_lock*/ 0);
13169 
13170 	return (retval);
13171 }
13172 
13173 static int
13174 ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
13175 			 ctl_ha_dt_cb callback)
13176 {
13177 	struct ctl_ha_dt_req *rq;
13178 	struct ctl_sg_entry *remote_sglist, *local_sglist;
13179 	struct ctl_sg_entry *remote_dma_sglist, *local_dma_sglist;
13180 	uint32_t local_used, remote_used, total_used;
13181 	int retval;
13182 	int i, j;
13183 
13184 	retval = 0;
13185 
13186 	rq = ctl_dt_req_alloc();
13187 
13188 	/*
13189 	 * If we failed to allocate the request, and if the DMA didn't fail
13190 	 * anyway, set busy status.  This is just a resource allocation
13191 	 * failure.
13192 	 */
13193 	if ((rq == NULL)
13194 	 && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE))
13195 		ctl_set_busy(&io->scsiio);
13196 
13197 	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE) {
13198 
13199 		if (rq != NULL)
13200 			ctl_dt_req_free(rq);
13201 
13202 		/*
13203 		 * The data move failed.  We need to return status back
13204 		 * to the other controller.  No point in trying to DMA
13205 		 * data to the remote controller.
13206 		 */
13207 
13208 		ctl_send_datamove_done(io, /*have_lock*/ 0);
13209 
13210 		retval = 1;
13211 
13212 		goto bailout;
13213 	}
13214 
13215 	local_sglist = io->io_hdr.local_sglist;
13216 	local_dma_sglist = io->io_hdr.local_dma_sglist;
13217 	remote_sglist = io->io_hdr.remote_sglist;
13218 	remote_dma_sglist = io->io_hdr.remote_dma_sglist;
13219 	local_used = 0;
13220 	remote_used = 0;
13221 	total_used = 0;
13222 
13223 	if (io->io_hdr.flags & CTL_FLAG_REDIR_DONE) {
13224 		rq->ret = CTL_HA_STATUS_SUCCESS;
13225 		rq->context = io;
13226 		callback(rq);
13227 		goto bailout;
13228 	}
13229 
13230 	/*
13231 	 * Pull/push the data over the wire from/to the other controller.
13232 	 * This takes into account the possibility that the local and
13233 	 * remote sglists may not be identical in terms of the size of
13234 	 * the elements and the number of elements.
13235 	 *
13236 	 * One fundamental assumption here is that the length allocated for
13237 	 * both the local and remote sglists is identical.  Otherwise, we've
13238 	 * essentially got a coding error of some sort.
13239 	 */
13240 	for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
13241 		int isc_ret;
13242 		uint32_t cur_len, dma_length;
13243 		uint8_t *tmp_ptr;
13244 
13245 		rq->id = CTL_HA_DATA_CTL;
13246 		rq->command = command;
13247 		rq->context = io;
13248 
13249 		/*
13250 		 * Both pointers should be aligned.  But it is possible
13251 		 * that the allocation length is not.  They should both
13252 		 * also have enough slack left over at the end, though,
13253 		 * to round up to the next 8 byte boundary.
13254 		 */
13255 		cur_len = ctl_min(local_sglist[i].len - local_used,
13256 				  remote_sglist[j].len - remote_used);
13257 
13258 		/*
13259 		 * In this case, we have a size issue and need to decrease
13260 		 * the size, except in the case where we actually have less
13261 		 * than 8 bytes left.  In that case, we need to increase
13262 		 * the DMA length to get the last bit.
13263 		 */
13264 		if ((cur_len & 0x7) != 0) {
13265 			if (cur_len > 0x7) {
13266 				cur_len = cur_len - (cur_len & 0x7);
13267 				dma_length = cur_len;
13268 			} else {
13269 				CTL_SIZE_8B(dma_length, cur_len);
13270 			}
13271 
13272 		} else
13273 			dma_length = cur_len;
13274 
13275 		/*
13276 		 * If we had to allocate memory for this I/O, instead of using
13277 		 * the non-cached mirror memory, we'll need to flush the cache
13278 		 * before trying to DMA to the other controller.
13279 		 *
13280 		 * We could end up doing this multiple times for the same
13281 		 * segment if we have a larger local segment than remote
13282 		 * segment.  That shouldn't be an issue.
13283 		 */
13284 		if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
13285 			/*
13286 			 * XXX KDM use bus_dmamap_sync() here.
13287 			 */
13288 		}
13289 
13290 		rq->size = dma_length;
13291 
13292 		tmp_ptr = (uint8_t *)local_sglist[i].addr;
13293 		tmp_ptr += local_used;
13294 
13295 		/* Use physical addresses when talking to ISC hardware */
13296 		if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
13297 			/* XXX KDM use busdma */
13298 #if 0
13299 			rq->local = vtophys(tmp_ptr);
13300 #endif
13301 		} else
13302 			rq->local = tmp_ptr;
13303 
13304 		tmp_ptr = (uint8_t *)remote_sglist[j].addr;
13305 		tmp_ptr += remote_used;
13306 		rq->remote = tmp_ptr;
13307 
13308 		rq->callback = NULL;
13309 
13310 		local_used += cur_len;
13311 		if (local_used >= local_sglist[i].len) {
13312 			i++;
13313 			local_used = 0;
13314 		}
13315 
13316 		remote_used += cur_len;
13317 		if (remote_used >= remote_sglist[j].len) {
13318 			j++;
13319 			remote_used = 0;
13320 		}
13321 		total_used += cur_len;
13322 
13323 		if (total_used >= io->scsiio.kern_data_len)
13324 			rq->callback = callback;
13325 
13326 		if ((rq->size & 0x7) != 0) {
13327 			printf("%s: warning: size %d is not on 8b boundary\n",
13328 			       __func__, rq->size);
13329 		}
13330 		if (((uintptr_t)rq->local & 0x7) != 0) {
13331 			printf("%s: warning: local %p not on 8b boundary\n",
13332 			       __func__, rq->local);
13333 		}
13334 		if (((uintptr_t)rq->remote & 0x7) != 0) {
13335 			printf("%s: warning: remote %p not on 8b boundary\n",
13336 			       __func__, rq->local);
13337 		}
13338 #if 0
13339 		printf("%s: %s: local %#x remote %#x size %d\n", __func__,
13340 		       (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
13341 		       rq->local, rq->remote, rq->size);
13342 #endif
13343 
13344 		isc_ret = ctl_dt_single(rq);
13345 		if (isc_ret == CTL_HA_STATUS_WAIT)
13346 			continue;
13347 
13348 		if (isc_ret == CTL_HA_STATUS_DISCONNECT) {
13349 			rq->ret = CTL_HA_STATUS_SUCCESS;
13350 		} else {
13351 			rq->ret = isc_ret;
13352 		}
13353 		callback(rq);
13354 		goto bailout;
13355 	}
13356 
13357 bailout:
13358 	return (retval);
13359 
13360 }
13361 
13362 static void
13363 ctl_datamove_remote_read(union ctl_io *io)
13364 {
13365 	int retval;
13366 	int i;
13367 
13368 	/*
13369 	 * This will send an error to the other controller in the case of a
13370 	 * failure.
13371 	 */
13372 	retval = ctl_datamove_remote_sgl_setup(io);
13373 	if (retval != 0)
13374 		return;
13375 
13376 	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
13377 					  ctl_datamove_remote_read_cb);
13378 	if ((retval != 0)
13379 	 && ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0)) {
13380 		/*
13381 		 * Make sure we free memory if there was an error..  The
13382 		 * ctl_datamove_remote_xfer() function will send the
13383 		 * datamove done message, or call the callback with an
13384 		 * error if there is a problem.
13385 		 */
13386 		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13387 			free(io->io_hdr.local_sglist[i].addr, M_CTL);
13388 	}
13389 
13390 	return;
13391 }
13392 
13393 /*
13394  * Process a datamove request from the other controller.  This is used for
13395  * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
13396  * first.  Once that is complete, the data gets DMAed into the remote
13397  * controller's memory.  For reads, we DMA from the remote controller's
13398  * memory into our memory first, and then move it out to the FETD.
13399  */
13400 static void
13401 ctl_datamove_remote(union ctl_io *io)
13402 {
13403 	struct ctl_softc *softc;
13404 
13405 	softc = control_softc;
13406 
13407 	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
13408 
13409 	/*
13410 	 * Note that we look for an aborted I/O here, but don't do some of
13411 	 * the other checks that ctl_datamove() normally does.
13412 	 * We don't need to run the datamove delay code, since that should
13413 	 * have been done if need be on the other controller.
13414 	 */
13415 	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
13416 		printf("%s: tag 0x%04x on (%d:%d:%d:%d) aborted\n", __func__,
13417 		       io->scsiio.tag_num, io->io_hdr.nexus.initid.id,
13418 		       io->io_hdr.nexus.targ_port,
13419 		       io->io_hdr.nexus.targ_target.id,
13420 		       io->io_hdr.nexus.targ_lun);
13421 		io->io_hdr.port_status = 31338;
13422 		ctl_send_datamove_done(io, /*have_lock*/ 0);
13423 		return;
13424 	}
13425 
13426 	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT) {
13427 		ctl_datamove_remote_write(io);
13428 	} else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN){
13429 		ctl_datamove_remote_read(io);
13430 	} else {
13431 		union ctl_ha_msg msg;
13432 		struct scsi_sense_data *sense;
13433 		uint8_t sks[3];
13434 		int retry_count;
13435 
13436 		memset(&msg, 0, sizeof(msg));
13437 
13438 		msg.hdr.msg_type = CTL_MSG_BAD_JUJU;
13439 		msg.hdr.status = CTL_SCSI_ERROR;
13440 		msg.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
13441 
13442 		retry_count = 4243;
13443 
13444 		sense = &msg.scsi.sense_data;
13445 		sks[0] = SSD_SCS_VALID;
13446 		sks[1] = (retry_count >> 8) & 0xff;
13447 		sks[2] = retry_count & 0xff;
13448 
13449 		/* "Internal target failure" */
13450 		scsi_set_sense_data(sense,
13451 				    /*sense_format*/ SSD_TYPE_NONE,
13452 				    /*current_error*/ 1,
13453 				    /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
13454 				    /*asc*/ 0x44,
13455 				    /*ascq*/ 0x00,
13456 				    /*type*/ SSD_ELEM_SKS,
13457 				    /*size*/ sizeof(sks),
13458 				    /*data*/ sks,
13459 				    SSD_ELEM_NONE);
13460 
13461 		io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
13462 		if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13463 			ctl_failover_io(io, /*have_lock*/ 1);
13464 			return;
13465 		}
13466 
13467 		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0) >
13468 		    CTL_HA_STATUS_SUCCESS) {
13469 			/* XXX KDM what to do if this fails? */
13470 		}
13471 		return;
13472 	}
13473 
13474 }
13475 
13476 static int
13477 ctl_process_done(union ctl_io *io)
13478 {
13479 	struct ctl_lun *lun;
13480 	struct ctl_softc *ctl_softc = control_softc;
13481 	void (*fe_done)(union ctl_io *io);
13482 	uint32_t targ_port = ctl_port_idx(io->io_hdr.nexus.targ_port);
13483 
13484 	CTL_DEBUG_PRINT(("ctl_process_done\n"));
13485 
13486 	fe_done =
13487 	    control_softc->ctl_ports[targ_port]->fe_done;
13488 
13489 #ifdef CTL_TIME_IO
13490 	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
13491 		char str[256];
13492 		char path_str[64];
13493 		struct sbuf sb;
13494 
13495 		ctl_scsi_path_string(io, path_str, sizeof(path_str));
13496 		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13497 
13498 		sbuf_cat(&sb, path_str);
13499 		switch (io->io_hdr.io_type) {
13500 		case CTL_IO_SCSI:
13501 			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
13502 			sbuf_printf(&sb, "\n");
13503 			sbuf_cat(&sb, path_str);
13504 			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13505 				    io->scsiio.tag_num, io->scsiio.tag_type);
13506 			break;
13507 		case CTL_IO_TASK:
13508 			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
13509 				    "Tag Type: %d\n", io->taskio.task_action,
13510 				    io->taskio.tag_num, io->taskio.tag_type);
13511 			break;
13512 		default:
13513 			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13514 			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13515 			break;
13516 		}
13517 		sbuf_cat(&sb, path_str);
13518 		sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
13519 			    (intmax_t)time_uptime - io->io_hdr.start_time);
13520 		sbuf_finish(&sb);
13521 		printf("%s", sbuf_data(&sb));
13522 	}
13523 #endif /* CTL_TIME_IO */
13524 
13525 	switch (io->io_hdr.io_type) {
13526 	case CTL_IO_SCSI:
13527 		break;
13528 	case CTL_IO_TASK:
13529 		if (bootverbose || (ctl_debug & CTL_DEBUG_INFO))
13530 			ctl_io_error_print(io, NULL);
13531 		if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
13532 			ctl_free_io(io);
13533 		else
13534 			fe_done(io);
13535 		return (CTL_RETVAL_COMPLETE);
13536 	default:
13537 		panic("ctl_process_done: invalid io type %d\n",
13538 		      io->io_hdr.io_type);
13539 		break; /* NOTREACHED */
13540 	}
13541 
13542 	lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13543 	if (lun == NULL) {
13544 		CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13545 				 io->io_hdr.nexus.targ_mapped_lun));
13546 		goto bailout;
13547 	}
13548 
13549 	mtx_lock(&lun->lun_lock);
13550 
13551 	/*
13552 	 * Check to see if we have any errors to inject here.  We only
13553 	 * inject errors for commands that don't already have errors set.
13554 	 */
13555 	if ((STAILQ_FIRST(&lun->error_list) != NULL) &&
13556 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS) &&
13557 	    ((io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0))
13558 		ctl_inject_error(lun, io);
13559 
13560 	/*
13561 	 * XXX KDM how do we treat commands that aren't completed
13562 	 * successfully?
13563 	 *
13564 	 * XXX KDM should we also track I/O latency?
13565 	 */
13566 	if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13567 	    io->io_hdr.io_type == CTL_IO_SCSI) {
13568 #ifdef CTL_TIME_IO
13569 		struct bintime cur_bt;
13570 #endif
13571 		int type;
13572 
13573 		if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13574 		    CTL_FLAG_DATA_IN)
13575 			type = CTL_STATS_READ;
13576 		else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13577 		    CTL_FLAG_DATA_OUT)
13578 			type = CTL_STATS_WRITE;
13579 		else
13580 			type = CTL_STATS_NO_IO;
13581 
13582 		lun->stats.ports[targ_port].bytes[type] +=
13583 		    io->scsiio.kern_total_len;
13584 		lun->stats.ports[targ_port].operations[type]++;
13585 #ifdef CTL_TIME_IO
13586 		bintime_add(&lun->stats.ports[targ_port].dma_time[type],
13587 		   &io->io_hdr.dma_bt);
13588 		lun->stats.ports[targ_port].num_dmas[type] +=
13589 		    io->io_hdr.num_dmas;
13590 		getbintime(&cur_bt);
13591 		bintime_sub(&cur_bt, &io->io_hdr.start_bt);
13592 		bintime_add(&lun->stats.ports[targ_port].time[type], &cur_bt);
13593 #endif
13594 	}
13595 
13596 	/*
13597 	 * Remove this from the OOA queue.
13598 	 */
13599 	TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13600 
13601 	/*
13602 	 * Run through the blocked queue on this LUN and see if anything
13603 	 * has become unblocked, now that this transaction is done.
13604 	 */
13605 	ctl_check_blocked(lun);
13606 
13607 	/*
13608 	 * If the LUN has been invalidated, free it if there is nothing
13609 	 * left on its OOA queue.
13610 	 */
13611 	if ((lun->flags & CTL_LUN_INVALID)
13612 	 && TAILQ_EMPTY(&lun->ooa_queue)) {
13613 		mtx_unlock(&lun->lun_lock);
13614 		mtx_lock(&ctl_softc->ctl_lock);
13615 		ctl_free_lun(lun);
13616 		mtx_unlock(&ctl_softc->ctl_lock);
13617 	} else
13618 		mtx_unlock(&lun->lun_lock);
13619 
13620 bailout:
13621 
13622 	/*
13623 	 * If this command has been aborted, make sure we set the status
13624 	 * properly.  The FETD is responsible for freeing the I/O and doing
13625 	 * whatever it needs to do to clean up its state.
13626 	 */
13627 	if (io->io_hdr.flags & CTL_FLAG_ABORT)
13628 		ctl_set_task_aborted(&io->scsiio);
13629 
13630 	/*
13631 	 * If enabled, print command error status.
13632 	 * We don't print UAs unless debugging was enabled explicitly.
13633 	 */
13634 	do {
13635 		if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)
13636 			break;
13637 		if (!bootverbose && (ctl_debug & CTL_DEBUG_INFO) == 0)
13638 			break;
13639 		if ((ctl_debug & CTL_DEBUG_INFO) == 0 &&
13640 		    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SCSI_ERROR) &&
13641 		     (io->scsiio.scsi_status == SCSI_STATUS_CHECK_COND)) {
13642 			int error_code, sense_key, asc, ascq;
13643 
13644 			scsi_extract_sense_len(&io->scsiio.sense_data,
13645 			    io->scsiio.sense_len, &error_code, &sense_key,
13646 			    &asc, &ascq, /*show_errors*/ 0);
13647 			if (sense_key == SSD_KEY_UNIT_ATTENTION)
13648 				break;
13649 		}
13650 
13651 		ctl_io_error_print(io, NULL);
13652 	} while (0);
13653 
13654 	/*
13655 	 * Tell the FETD or the other shelf controller we're done with this
13656 	 * command.  Note that only SCSI commands get to this point.  Task
13657 	 * management commands are completed above.
13658 	 *
13659 	 * We only send status to the other controller if we're in XFER
13660 	 * mode.  In SER_ONLY mode, the I/O is done on the controller that
13661 	 * received the I/O (from CTL's perspective), and so the status is
13662 	 * generated there.
13663 	 *
13664 	 * XXX KDM if we hold the lock here, we could cause a deadlock
13665 	 * if the frontend comes back in in this context to queue
13666 	 * something.
13667 	 */
13668 	if ((ctl_softc->ha_mode == CTL_HA_MODE_XFER)
13669 	 && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
13670 		union ctl_ha_msg msg;
13671 
13672 		memset(&msg, 0, sizeof(msg));
13673 		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13674 		msg.hdr.original_sc = io->io_hdr.original_sc;
13675 		msg.hdr.nexus = io->io_hdr.nexus;
13676 		msg.hdr.status = io->io_hdr.status;
13677 		msg.scsi.scsi_status = io->scsiio.scsi_status;
13678 		msg.scsi.tag_num = io->scsiio.tag_num;
13679 		msg.scsi.tag_type = io->scsiio.tag_type;
13680 		msg.scsi.sense_len = io->scsiio.sense_len;
13681 		msg.scsi.sense_residual = io->scsiio.sense_residual;
13682 		msg.scsi.residual = io->scsiio.residual;
13683 		memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
13684 		       sizeof(io->scsiio.sense_data));
13685 		/*
13686 		 * We copy this whether or not this is an I/O-related
13687 		 * command.  Otherwise, we'd have to go and check to see
13688 		 * whether it's a read/write command, and it really isn't
13689 		 * worth it.
13690 		 */
13691 		memcpy(&msg.scsi.lbalen,
13692 		       &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
13693 		       sizeof(msg.scsi.lbalen));
13694 
13695 		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13696 				sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
13697 			/* XXX do something here */
13698 		}
13699 
13700 		ctl_free_io(io);
13701 	} else
13702 		fe_done(io);
13703 
13704 	return (CTL_RETVAL_COMPLETE);
13705 }
13706 
13707 #ifdef CTL_WITH_CA
13708 /*
13709  * Front end should call this if it doesn't do autosense.  When the request
13710  * sense comes back in from the initiator, we'll dequeue this and send it.
13711  */
13712 int
13713 ctl_queue_sense(union ctl_io *io)
13714 {
13715 	struct ctl_lun *lun;
13716 	struct ctl_softc *ctl_softc;
13717 	uint32_t initidx, targ_lun;
13718 
13719 	ctl_softc = control_softc;
13720 
13721 	CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13722 
13723 	/*
13724 	 * LUN lookup will likely move to the ctl_work_thread() once we
13725 	 * have our new queueing infrastructure (that doesn't put things on
13726 	 * a per-LUN queue initially).  That is so that we can handle
13727 	 * things like an INQUIRY to a LUN that we don't have enabled.  We
13728 	 * can't deal with that right now.
13729 	 */
13730 	mtx_lock(&ctl_softc->ctl_lock);
13731 
13732 	/*
13733 	 * If we don't have a LUN for this, just toss the sense
13734 	 * information.
13735 	 */
13736 	targ_lun = io->io_hdr.nexus.targ_lun;
13737 	targ_lun = ctl_map_lun(io->io_hdr.nexus.targ_port, targ_lun);
13738 	if ((targ_lun < CTL_MAX_LUNS)
13739 	 && (ctl_softc->ctl_luns[targ_lun] != NULL))
13740 		lun = ctl_softc->ctl_luns[targ_lun];
13741 	else
13742 		goto bailout;
13743 
13744 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
13745 
13746 	mtx_lock(&lun->lun_lock);
13747 	/*
13748 	 * Already have CA set for this LUN...toss the sense information.
13749 	 */
13750 	if (ctl_is_set(lun->have_ca, initidx)) {
13751 		mtx_unlock(&lun->lun_lock);
13752 		goto bailout;
13753 	}
13754 
13755 	memcpy(&lun->pending_sense[initidx], &io->scsiio.sense_data,
13756 	       ctl_min(sizeof(lun->pending_sense[initidx]),
13757 	       sizeof(io->scsiio.sense_data)));
13758 	ctl_set_mask(lun->have_ca, initidx);
13759 	mtx_unlock(&lun->lun_lock);
13760 
13761 bailout:
13762 	mtx_unlock(&ctl_softc->ctl_lock);
13763 
13764 	ctl_free_io(io);
13765 
13766 	return (CTL_RETVAL_COMPLETE);
13767 }
13768 #endif
13769 
13770 /*
13771  * Primary command inlet from frontend ports.  All SCSI and task I/O
13772  * requests must go through this function.
13773  */
13774 int
13775 ctl_queue(union ctl_io *io)
13776 {
13777 	struct ctl_softc *ctl_softc;
13778 
13779 	CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13780 
13781 	ctl_softc = control_softc;
13782 
13783 #ifdef CTL_TIME_IO
13784 	io->io_hdr.start_time = time_uptime;
13785 	getbintime(&io->io_hdr.start_bt);
13786 #endif /* CTL_TIME_IO */
13787 
13788 	/* Map FE-specific LUN ID into global one. */
13789 	io->io_hdr.nexus.targ_mapped_lun =
13790 	    ctl_map_lun(io->io_hdr.nexus.targ_port, io->io_hdr.nexus.targ_lun);
13791 
13792 	switch (io->io_hdr.io_type) {
13793 	case CTL_IO_SCSI:
13794 	case CTL_IO_TASK:
13795 		if (ctl_debug & CTL_DEBUG_CDB)
13796 			ctl_io_print(io);
13797 		ctl_enqueue_incoming(io);
13798 		break;
13799 	default:
13800 		printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13801 		return (EINVAL);
13802 	}
13803 
13804 	return (CTL_RETVAL_COMPLETE);
13805 }
13806 
13807 #ifdef CTL_IO_DELAY
13808 static void
13809 ctl_done_timer_wakeup(void *arg)
13810 {
13811 	union ctl_io *io;
13812 
13813 	io = (union ctl_io *)arg;
13814 	ctl_done(io);
13815 }
13816 #endif /* CTL_IO_DELAY */
13817 
13818 void
13819 ctl_done(union ctl_io *io)
13820 {
13821 	struct ctl_softc *ctl_softc;
13822 
13823 	ctl_softc = control_softc;
13824 
13825 	/*
13826 	 * Enable this to catch duplicate completion issues.
13827 	 */
13828 #if 0
13829 	if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13830 		printf("%s: type %d msg %d cdb %x iptl: "
13831 		       "%d:%d:%d:%d tag 0x%04x "
13832 		       "flag %#x status %x\n",
13833 			__func__,
13834 			io->io_hdr.io_type,
13835 			io->io_hdr.msg_type,
13836 			io->scsiio.cdb[0],
13837 			io->io_hdr.nexus.initid.id,
13838 			io->io_hdr.nexus.targ_port,
13839 			io->io_hdr.nexus.targ_target.id,
13840 			io->io_hdr.nexus.targ_lun,
13841 			(io->io_hdr.io_type ==
13842 			CTL_IO_TASK) ?
13843 			io->taskio.tag_num :
13844 			io->scsiio.tag_num,
13845 		        io->io_hdr.flags,
13846 			io->io_hdr.status);
13847 	} else
13848 		io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13849 #endif
13850 
13851 	/*
13852 	 * This is an internal copy of an I/O, and should not go through
13853 	 * the normal done processing logic.
13854 	 */
13855 	if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13856 		return;
13857 
13858 	/*
13859 	 * We need to send a msg to the serializing shelf to finish the IO
13860 	 * as well.  We don't send a finish message to the other shelf if
13861 	 * this is a task management command.  Task management commands
13862 	 * aren't serialized in the OOA queue, but rather just executed on
13863 	 * both shelf controllers for commands that originated on that
13864 	 * controller.
13865 	 */
13866 	if ((io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)
13867 	 && (io->io_hdr.io_type != CTL_IO_TASK)) {
13868 		union ctl_ha_msg msg_io;
13869 
13870 		msg_io.hdr.msg_type = CTL_MSG_FINISH_IO;
13871 		msg_io.hdr.serializing_sc = io->io_hdr.serializing_sc;
13872 		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_io,
13873 		    sizeof(msg_io), 0 ) != CTL_HA_STATUS_SUCCESS) {
13874 		}
13875 		/* continue on to finish IO */
13876 	}
13877 #ifdef CTL_IO_DELAY
13878 	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13879 		struct ctl_lun *lun;
13880 
13881 		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13882 
13883 		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13884 	} else {
13885 		struct ctl_lun *lun;
13886 
13887 		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13888 
13889 		if ((lun != NULL)
13890 		 && (lun->delay_info.done_delay > 0)) {
13891 			struct callout *callout;
13892 
13893 			callout = (struct callout *)&io->io_hdr.timer_bytes;
13894 			callout_init(callout, /*mpsafe*/ 1);
13895 			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
13896 			callout_reset(callout,
13897 				      lun->delay_info.done_delay * hz,
13898 				      ctl_done_timer_wakeup, io);
13899 			if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
13900 				lun->delay_info.done_delay = 0;
13901 			return;
13902 		}
13903 	}
13904 #endif /* CTL_IO_DELAY */
13905 
13906 	ctl_enqueue_done(io);
13907 }
13908 
13909 int
13910 ctl_isc(struct ctl_scsiio *ctsio)
13911 {
13912 	struct ctl_lun *lun;
13913 	int retval;
13914 
13915 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13916 
13917 	CTL_DEBUG_PRINT(("ctl_isc: command: %02x\n", ctsio->cdb[0]));
13918 
13919 	CTL_DEBUG_PRINT(("ctl_isc: calling data_submit()\n"));
13920 
13921 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
13922 
13923 	return (retval);
13924 }
13925 
13926 
13927 static void
13928 ctl_work_thread(void *arg)
13929 {
13930 	struct ctl_thread *thr = (struct ctl_thread *)arg;
13931 	struct ctl_softc *softc = thr->ctl_softc;
13932 	union ctl_io *io;
13933 	int retval;
13934 
13935 	CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
13936 
13937 	for (;;) {
13938 		retval = 0;
13939 
13940 		/*
13941 		 * We handle the queues in this order:
13942 		 * - ISC
13943 		 * - done queue (to free up resources, unblock other commands)
13944 		 * - RtR queue
13945 		 * - incoming queue
13946 		 *
13947 		 * If those queues are empty, we break out of the loop and
13948 		 * go to sleep.
13949 		 */
13950 		mtx_lock(&thr->queue_lock);
13951 		io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
13952 		if (io != NULL) {
13953 			STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
13954 			mtx_unlock(&thr->queue_lock);
13955 			ctl_handle_isc(io);
13956 			continue;
13957 		}
13958 		io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
13959 		if (io != NULL) {
13960 			STAILQ_REMOVE_HEAD(&thr->done_queue, links);
13961 			/* clear any blocked commands, call fe_done */
13962 			mtx_unlock(&thr->queue_lock);
13963 			retval = ctl_process_done(io);
13964 			continue;
13965 		}
13966 		io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
13967 		if (io != NULL) {
13968 			STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
13969 			mtx_unlock(&thr->queue_lock);
13970 			if (io->io_hdr.io_type == CTL_IO_TASK)
13971 				ctl_run_task(io);
13972 			else
13973 				ctl_scsiio_precheck(softc, &io->scsiio);
13974 			continue;
13975 		}
13976 		if (!ctl_pause_rtr) {
13977 			io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
13978 			if (io != NULL) {
13979 				STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
13980 				mtx_unlock(&thr->queue_lock);
13981 				retval = ctl_scsiio(&io->scsiio);
13982 				if (retval != CTL_RETVAL_COMPLETE)
13983 					CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
13984 				continue;
13985 			}
13986 		}
13987 
13988 		/* Sleep until we have something to do. */
13989 		mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
13990 	}
13991 }
13992 
13993 static void
13994 ctl_lun_thread(void *arg)
13995 {
13996 	struct ctl_softc *softc = (struct ctl_softc *)arg;
13997 	struct ctl_be_lun *be_lun;
13998 	int retval;
13999 
14000 	CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
14001 
14002 	for (;;) {
14003 		retval = 0;
14004 		mtx_lock(&softc->ctl_lock);
14005 		be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
14006 		if (be_lun != NULL) {
14007 			STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
14008 			mtx_unlock(&softc->ctl_lock);
14009 			ctl_create_lun(be_lun);
14010 			continue;
14011 		}
14012 
14013 		/* Sleep until we have something to do. */
14014 		mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
14015 		    PDROP | PRIBIO, "-", 0);
14016 	}
14017 }
14018 
14019 static void
14020 ctl_thresh_thread(void *arg)
14021 {
14022 	struct ctl_softc *softc = (struct ctl_softc *)arg;
14023 	struct ctl_lun *lun;
14024 	struct ctl_be_lun *be_lun;
14025 	struct scsi_da_rw_recovery_page *rwpage;
14026 	struct ctl_logical_block_provisioning_page *page;
14027 	const char *attr;
14028 	uint64_t thres, val;
14029 	int i, e;
14030 
14031 	CTL_DEBUG_PRINT(("ctl_thresh_thread starting\n"));
14032 
14033 	for (;;) {
14034 		mtx_lock(&softc->ctl_lock);
14035 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
14036 			be_lun = lun->be_lun;
14037 			if ((lun->flags & CTL_LUN_DISABLED) ||
14038 			    (lun->flags & CTL_LUN_OFFLINE) ||
14039 			    lun->backend->lun_attr == NULL)
14040 				continue;
14041 			rwpage = &lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT];
14042 			if ((rwpage->byte8 & SMS_RWER_LBPERE) == 0)
14043 				continue;
14044 			e = 0;
14045 			page = &lun->mode_pages.lbp_page[CTL_PAGE_CURRENT];
14046 			for (i = 0; i < CTL_NUM_LBP_THRESH; i++) {
14047 				if ((page->descr[i].flags & SLBPPD_ENABLED) == 0)
14048 					continue;
14049 				thres = scsi_4btoul(page->descr[i].count);
14050 				thres <<= CTL_LBP_EXPONENT;
14051 				switch (page->descr[i].resource) {
14052 				case 0x01:
14053 					attr = "blocksavail";
14054 					break;
14055 				case 0x02:
14056 					attr = "blocksused";
14057 					break;
14058 				case 0xf1:
14059 					attr = "poolblocksavail";
14060 					break;
14061 				case 0xf2:
14062 					attr = "poolblocksused";
14063 					break;
14064 				default:
14065 					continue;
14066 				}
14067 				mtx_unlock(&softc->ctl_lock); // XXX
14068 				val = lun->backend->lun_attr(
14069 				    lun->be_lun->be_lun, attr);
14070 				mtx_lock(&softc->ctl_lock);
14071 				if (val == UINT64_MAX)
14072 					continue;
14073 				if ((page->descr[i].flags & SLBPPD_ARMING_MASK)
14074 				    == SLBPPD_ARMING_INC)
14075 					e |= (val >= thres);
14076 				else
14077 					e |= (val <= thres);
14078 			}
14079 			mtx_lock(&lun->lun_lock);
14080 			if (e) {
14081 				if (lun->lasttpt == 0 ||
14082 				    time_uptime - lun->lasttpt >= CTL_LBP_UA_PERIOD) {
14083 					lun->lasttpt = time_uptime;
14084 					ctl_est_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
14085 				}
14086 			} else {
14087 				lun->lasttpt = 0;
14088 				ctl_clr_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
14089 			}
14090 			mtx_unlock(&lun->lun_lock);
14091 		}
14092 		mtx_unlock(&softc->ctl_lock);
14093 		pause("-", CTL_LBP_PERIOD * hz);
14094 	}
14095 }
14096 
14097 static void
14098 ctl_enqueue_incoming(union ctl_io *io)
14099 {
14100 	struct ctl_softc *softc = control_softc;
14101 	struct ctl_thread *thr;
14102 	u_int idx;
14103 
14104 	idx = (io->io_hdr.nexus.targ_port * 127 +
14105 	       io->io_hdr.nexus.initid.id) % worker_threads;
14106 	thr = &softc->threads[idx];
14107 	mtx_lock(&thr->queue_lock);
14108 	STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
14109 	mtx_unlock(&thr->queue_lock);
14110 	wakeup(thr);
14111 }
14112 
14113 static void
14114 ctl_enqueue_rtr(union ctl_io *io)
14115 {
14116 	struct ctl_softc *softc = control_softc;
14117 	struct ctl_thread *thr;
14118 
14119 	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14120 	mtx_lock(&thr->queue_lock);
14121 	STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
14122 	mtx_unlock(&thr->queue_lock);
14123 	wakeup(thr);
14124 }
14125 
14126 static void
14127 ctl_enqueue_done(union ctl_io *io)
14128 {
14129 	struct ctl_softc *softc = control_softc;
14130 	struct ctl_thread *thr;
14131 
14132 	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14133 	mtx_lock(&thr->queue_lock);
14134 	STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
14135 	mtx_unlock(&thr->queue_lock);
14136 	wakeup(thr);
14137 }
14138 
14139 static void
14140 ctl_enqueue_isc(union ctl_io *io)
14141 {
14142 	struct ctl_softc *softc = control_softc;
14143 	struct ctl_thread *thr;
14144 
14145 	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14146 	mtx_lock(&thr->queue_lock);
14147 	STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
14148 	mtx_unlock(&thr->queue_lock);
14149 	wakeup(thr);
14150 }
14151 
14152 /* Initialization and failover */
14153 
14154 void
14155 ctl_init_isc_msg(void)
14156 {
14157 	printf("CTL: Still calling this thing\n");
14158 }
14159 
14160 /*
14161  * Init component
14162  * 	Initializes component into configuration defined by bootMode
14163  *	(see hasc-sv.c)
14164  *  	returns hasc_Status:
14165  * 		OK
14166  *		ERROR - fatal error
14167  */
14168 static ctl_ha_comp_status
14169 ctl_isc_init(struct ctl_ha_component *c)
14170 {
14171 	ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14172 
14173 	c->status = ret;
14174 	return ret;
14175 }
14176 
14177 /* Start component
14178  * 	Starts component in state requested. If component starts successfully,
14179  *	it must set its own state to the requestrd state
14180  *	When requested state is HASC_STATE_HA, the component may refine it
14181  * 	by adding _SLAVE or _MASTER flags.
14182  *	Currently allowed state transitions are:
14183  *	UNKNOWN->HA		- initial startup
14184  *	UNKNOWN->SINGLE - initial startup when no parter detected
14185  *	HA->SINGLE		- failover
14186  * returns ctl_ha_comp_status:
14187  * 		OK	- component successfully started in requested state
14188  *		FAILED  - could not start the requested state, failover may
14189  * 			  be possible
14190  *		ERROR	- fatal error detected, no future startup possible
14191  */
14192 static ctl_ha_comp_status
14193 ctl_isc_start(struct ctl_ha_component *c, ctl_ha_state state)
14194 {
14195 	ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14196 
14197 	printf("%s: go\n", __func__);
14198 
14199 	// UNKNOWN->HA or UNKNOWN->SINGLE (bootstrap)
14200 	if (c->state == CTL_HA_STATE_UNKNOWN ) {
14201 		control_softc->is_single = 0;
14202 		if (ctl_ha_msg_create(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
14203 		    != CTL_HA_STATUS_SUCCESS) {
14204 			printf("ctl_isc_start: ctl_ha_msg_create failed.\n");
14205 			ret = CTL_HA_COMP_STATUS_ERROR;
14206 		}
14207 	} else if (CTL_HA_STATE_IS_HA(c->state)
14208 		&& CTL_HA_STATE_IS_SINGLE(state)){
14209 		// HA->SINGLE transition
14210 	        ctl_failover();
14211 		control_softc->is_single = 1;
14212 	} else {
14213 		printf("ctl_isc_start:Invalid state transition %X->%X\n",
14214 		       c->state, state);
14215 		ret = CTL_HA_COMP_STATUS_ERROR;
14216 	}
14217 	if (CTL_HA_STATE_IS_SINGLE(state))
14218 		control_softc->is_single = 1;
14219 
14220 	c->state = state;
14221 	c->status = ret;
14222 	return ret;
14223 }
14224 
14225 /*
14226  * Quiesce component
14227  * The component must clear any error conditions (set status to OK) and
14228  * prepare itself to another Start call
14229  * returns ctl_ha_comp_status:
14230  * 	OK
14231  *	ERROR
14232  */
14233 static ctl_ha_comp_status
14234 ctl_isc_quiesce(struct ctl_ha_component *c)
14235 {
14236 	int ret = CTL_HA_COMP_STATUS_OK;
14237 
14238 	ctl_pause_rtr = 1;
14239 	c->status = ret;
14240 	return ret;
14241 }
14242 
14243 struct ctl_ha_component ctl_ha_component_ctlisc =
14244 {
14245 	.name = "CTL ISC",
14246 	.state = CTL_HA_STATE_UNKNOWN,
14247 	.init = ctl_isc_init,
14248 	.start = ctl_isc_start,
14249 	.quiesce = ctl_isc_quiesce
14250 };
14251 
14252 /*
14253  *  vim: ts=8
14254  */
14255