xref: /freebsd/sys/cam/ctl/ctl.c (revision db3cb3640f547c063293e9fdc4db69e9dc120951)
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 const 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 const 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 const 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 const 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 const 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 const 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 const 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 const 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 const 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 const 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 const 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 const 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 const 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 const 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 const 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 const 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(struct ctl_softc *softc, int port_num, uint32_t lun);
402 static uint32_t ctl_map_lun_back(struct ctl_softc *softc, 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_lun *lun,
445 				const struct ctl_cmd_entry *entry,
446 				struct ctl_scsiio *ctsio);
447 //static int ctl_check_rtr(union ctl_io *pending_io, struct ctl_softc *softc);
448 static void ctl_failover(void);
449 static int ctl_scsiio_precheck(struct ctl_softc *ctl_softc,
450 			       struct ctl_scsiio *ctsio);
451 static int ctl_scsiio(struct ctl_scsiio *ctsio);
452 
453 static int ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
454 static int ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
455 			    ctl_ua_type ua_type);
456 static int ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io,
457 			 ctl_ua_type ua_type);
458 static int ctl_abort_task(union ctl_io *io);
459 static int ctl_abort_task_set(union ctl_io *io);
460 static int ctl_i_t_nexus_reset(union ctl_io *io);
461 static void ctl_run_task(union ctl_io *io);
462 #ifdef CTL_IO_DELAY
463 static void ctl_datamove_timer_wakeup(void *arg);
464 static void ctl_done_timer_wakeup(void *arg);
465 #endif /* CTL_IO_DELAY */
466 
467 static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
468 static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
469 static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
470 static void ctl_datamove_remote_write(union ctl_io *io);
471 static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
472 static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
473 static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
474 static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
475 				    ctl_ha_dt_cb callback);
476 static void ctl_datamove_remote_read(union ctl_io *io);
477 static void ctl_datamove_remote(union ctl_io *io);
478 static int ctl_process_done(union ctl_io *io);
479 static void ctl_lun_thread(void *arg);
480 static void ctl_thresh_thread(void *arg);
481 static void ctl_work_thread(void *arg);
482 static void ctl_enqueue_incoming(union ctl_io *io);
483 static void ctl_enqueue_rtr(union ctl_io *io);
484 static void ctl_enqueue_done(union ctl_io *io);
485 static void ctl_enqueue_isc(union ctl_io *io);
486 static const struct ctl_cmd_entry *
487     ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa);
488 static const struct ctl_cmd_entry *
489     ctl_validate_command(struct ctl_scsiio *ctsio);
490 static int ctl_cmd_applicable(uint8_t lun_type,
491     const struct ctl_cmd_entry *entry);
492 
493 /*
494  * Load the serialization table.  This isn't very pretty, but is probably
495  * the easiest way to do it.
496  */
497 #include "ctl_ser_table.c"
498 
499 /*
500  * We only need to define open, close and ioctl routines for this driver.
501  */
502 static struct cdevsw ctl_cdevsw = {
503 	.d_version =	D_VERSION,
504 	.d_flags =	0,
505 	.d_open =	ctl_open,
506 	.d_close =	ctl_close,
507 	.d_ioctl =	ctl_ioctl,
508 	.d_name =	"ctl",
509 };
510 
511 
512 MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
513 MALLOC_DEFINE(M_CTLIO, "ctlio", "Memory used for CTL requests");
514 
515 static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
516 
517 static moduledata_t ctl_moduledata = {
518 	"ctl",
519 	ctl_module_event_handler,
520 	NULL
521 };
522 
523 DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
524 MODULE_VERSION(ctl, 1);
525 
526 static struct ctl_frontend ioctl_frontend =
527 {
528 	.name = "ioctl",
529 };
530 
531 static void
532 ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
533 			    union ctl_ha_msg *msg_info)
534 {
535 	struct ctl_scsiio *ctsio;
536 
537 	if (msg_info->hdr.original_sc == NULL) {
538 		printf("%s: original_sc == NULL!\n", __func__);
539 		/* XXX KDM now what? */
540 		return;
541 	}
542 
543 	ctsio = &msg_info->hdr.original_sc->scsiio;
544 	ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
545 	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
546 	ctsio->io_hdr.status = msg_info->hdr.status;
547 	ctsio->scsi_status = msg_info->scsi.scsi_status;
548 	ctsio->sense_len = msg_info->scsi.sense_len;
549 	ctsio->sense_residual = msg_info->scsi.sense_residual;
550 	ctsio->residual = msg_info->scsi.residual;
551 	memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
552 	       sizeof(ctsio->sense_data));
553 	memcpy(&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
554 	       &msg_info->scsi.lbalen, sizeof(msg_info->scsi.lbalen));
555 	ctl_enqueue_isc((union ctl_io *)ctsio);
556 }
557 
558 static void
559 ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
560 				union ctl_ha_msg *msg_info)
561 {
562 	struct ctl_scsiio *ctsio;
563 
564 	if (msg_info->hdr.serializing_sc == NULL) {
565 		printf("%s: serializing_sc == NULL!\n", __func__);
566 		/* XXX KDM now what? */
567 		return;
568 	}
569 
570 	ctsio = &msg_info->hdr.serializing_sc->scsiio;
571 #if 0
572 	/*
573 	 * Attempt to catch the situation where an I/O has
574 	 * been freed, and we're using it again.
575 	 */
576 	if (ctsio->io_hdr.io_type == 0xff) {
577 		union ctl_io *tmp_io;
578 		tmp_io = (union ctl_io *)ctsio;
579 		printf("%s: %p use after free!\n", __func__,
580 		       ctsio);
581 		printf("%s: type %d msg %d cdb %x iptl: "
582 		       "%d:%d:%d:%d tag 0x%04x "
583 		       "flag %#x status %x\n",
584 			__func__,
585 			tmp_io->io_hdr.io_type,
586 			tmp_io->io_hdr.msg_type,
587 			tmp_io->scsiio.cdb[0],
588 			tmp_io->io_hdr.nexus.initid.id,
589 			tmp_io->io_hdr.nexus.targ_port,
590 			tmp_io->io_hdr.nexus.targ_target.id,
591 			tmp_io->io_hdr.nexus.targ_lun,
592 			(tmp_io->io_hdr.io_type ==
593 			CTL_IO_TASK) ?
594 			tmp_io->taskio.tag_num :
595 			tmp_io->scsiio.tag_num,
596 		        tmp_io->io_hdr.flags,
597 			tmp_io->io_hdr.status);
598 	}
599 #endif
600 	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
601 	ctl_enqueue_isc((union ctl_io *)ctsio);
602 }
603 
604 /*
605  * ISC (Inter Shelf Communication) event handler.  Events from the HA
606  * subsystem come in here.
607  */
608 static void
609 ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
610 {
611 	struct ctl_softc *softc;
612 	union ctl_io *io;
613 	struct ctl_prio *presio;
614 	ctl_ha_status isc_status;
615 
616 	softc = control_softc;
617 	io = NULL;
618 
619 
620 #if 0
621 	printf("CTL: Isc Msg event %d\n", event);
622 #endif
623 	if (event == CTL_HA_EVT_MSG_RECV) {
624 		union ctl_ha_msg msg_info;
625 
626 		isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
627 					     sizeof(msg_info), /*wait*/ 0);
628 #if 0
629 		printf("CTL: msg_type %d\n", msg_info.msg_type);
630 #endif
631 		if (isc_status != 0) {
632 			printf("Error receiving message, status = %d\n",
633 			       isc_status);
634 			return;
635 		}
636 
637 		switch (msg_info.hdr.msg_type) {
638 		case CTL_MSG_SERIALIZE:
639 #if 0
640 			printf("Serialize\n");
641 #endif
642 			io = ctl_alloc_io_nowait(softc->othersc_pool);
643 			if (io == NULL) {
644 				printf("ctl_isc_event_handler: can't allocate "
645 				       "ctl_io!\n");
646 				/* Bad Juju */
647 				/* Need to set busy and send msg back */
648 				msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
649 				msg_info.hdr.status = CTL_SCSI_ERROR;
650 				msg_info.scsi.scsi_status = SCSI_STATUS_BUSY;
651 				msg_info.scsi.sense_len = 0;
652 			        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
653 				    sizeof(msg_info), 0) > CTL_HA_STATUS_SUCCESS){
654 				}
655 				goto bailout;
656 			}
657 			ctl_zero_io(io);
658 			// populate ctsio from msg_info
659 			io->io_hdr.io_type = CTL_IO_SCSI;
660 			io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
661 			io->io_hdr.original_sc = msg_info.hdr.original_sc;
662 #if 0
663 			printf("pOrig %x\n", (int)msg_info.original_sc);
664 #endif
665 			io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
666 					    CTL_FLAG_IO_ACTIVE;
667 			/*
668 			 * If we're in serialization-only mode, we don't
669 			 * want to go through full done processing.  Thus
670 			 * the COPY flag.
671 			 *
672 			 * XXX KDM add another flag that is more specific.
673 			 */
674 			if (softc->ha_mode == CTL_HA_MODE_SER_ONLY)
675 				io->io_hdr.flags |= CTL_FLAG_INT_COPY;
676 			io->io_hdr.nexus = msg_info.hdr.nexus;
677 #if 0
678 			printf("targ %d, port %d, iid %d, lun %d\n",
679 			       io->io_hdr.nexus.targ_target.id,
680 			       io->io_hdr.nexus.targ_port,
681 			       io->io_hdr.nexus.initid.id,
682 			       io->io_hdr.nexus.targ_lun);
683 #endif
684 			io->scsiio.tag_num = msg_info.scsi.tag_num;
685 			io->scsiio.tag_type = msg_info.scsi.tag_type;
686 			memcpy(io->scsiio.cdb, msg_info.scsi.cdb,
687 			       CTL_MAX_CDBLEN);
688 			if (softc->ha_mode == CTL_HA_MODE_XFER) {
689 				const struct ctl_cmd_entry *entry;
690 
691 				entry = ctl_get_cmd_entry(&io->scsiio, NULL);
692 				io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
693 				io->io_hdr.flags |=
694 					entry->flags & CTL_FLAG_DATA_MASK;
695 			}
696 			ctl_enqueue_isc(io);
697 			break;
698 
699 		/* Performed on the Originating SC, XFER mode only */
700 		case CTL_MSG_DATAMOVE: {
701 			struct ctl_sg_entry *sgl;
702 			int i, j;
703 
704 			io = msg_info.hdr.original_sc;
705 			if (io == NULL) {
706 				printf("%s: original_sc == NULL!\n", __func__);
707 				/* XXX KDM do something here */
708 				break;
709 			}
710 			io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
711 			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
712 			/*
713 			 * Keep track of this, we need to send it back over
714 			 * when the datamove is complete.
715 			 */
716 			io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
717 
718 			if (msg_info.dt.sg_sequence == 0) {
719 				/*
720 				 * XXX KDM we use the preallocated S/G list
721 				 * here, but we'll need to change this to
722 				 * dynamic allocation if we need larger S/G
723 				 * lists.
724 				 */
725 				if (msg_info.dt.kern_sg_entries >
726 				    sizeof(io->io_hdr.remote_sglist) /
727 				    sizeof(io->io_hdr.remote_sglist[0])) {
728 					printf("%s: number of S/G entries "
729 					    "needed %u > allocated num %zd\n",
730 					    __func__,
731 					    msg_info.dt.kern_sg_entries,
732 					    sizeof(io->io_hdr.remote_sglist)/
733 					    sizeof(io->io_hdr.remote_sglist[0]));
734 
735 					/*
736 					 * XXX KDM send a message back to
737 					 * the other side to shut down the
738 					 * DMA.  The error will come back
739 					 * through via the normal channel.
740 					 */
741 					break;
742 				}
743 				sgl = io->io_hdr.remote_sglist;
744 				memset(sgl, 0,
745 				       sizeof(io->io_hdr.remote_sglist));
746 
747 				io->scsiio.kern_data_ptr = (uint8_t *)sgl;
748 
749 				io->scsiio.kern_sg_entries =
750 					msg_info.dt.kern_sg_entries;
751 				io->scsiio.rem_sg_entries =
752 					msg_info.dt.kern_sg_entries;
753 				io->scsiio.kern_data_len =
754 					msg_info.dt.kern_data_len;
755 				io->scsiio.kern_total_len =
756 					msg_info.dt.kern_total_len;
757 				io->scsiio.kern_data_resid =
758 					msg_info.dt.kern_data_resid;
759 				io->scsiio.kern_rel_offset =
760 					msg_info.dt.kern_rel_offset;
761 				/*
762 				 * Clear out per-DMA flags.
763 				 */
764 				io->io_hdr.flags &= ~CTL_FLAG_RDMA_MASK;
765 				/*
766 				 * Add per-DMA flags that are set for this
767 				 * particular DMA request.
768 				 */
769 				io->io_hdr.flags |= msg_info.dt.flags &
770 						    CTL_FLAG_RDMA_MASK;
771 			} else
772 				sgl = (struct ctl_sg_entry *)
773 					io->scsiio.kern_data_ptr;
774 
775 			for (i = msg_info.dt.sent_sg_entries, j = 0;
776 			     i < (msg_info.dt.sent_sg_entries +
777 			     msg_info.dt.cur_sg_entries); i++, j++) {
778 				sgl[i].addr = msg_info.dt.sg_list[j].addr;
779 				sgl[i].len = msg_info.dt.sg_list[j].len;
780 
781 #if 0
782 				printf("%s: L: %p,%d -> %p,%d j=%d, i=%d\n",
783 				       __func__,
784 				       msg_info.dt.sg_list[j].addr,
785 				       msg_info.dt.sg_list[j].len,
786 				       sgl[i].addr, sgl[i].len, j, i);
787 #endif
788 			}
789 #if 0
790 			memcpy(&sgl[msg_info.dt.sent_sg_entries],
791 			       msg_info.dt.sg_list,
792 			       sizeof(*sgl) * msg_info.dt.cur_sg_entries);
793 #endif
794 
795 			/*
796 			 * If this is the last piece of the I/O, we've got
797 			 * the full S/G list.  Queue processing in the thread.
798 			 * Otherwise wait for the next piece.
799 			 */
800 			if (msg_info.dt.sg_last != 0)
801 				ctl_enqueue_isc(io);
802 			break;
803 		}
804 		/* Performed on the Serializing (primary) SC, XFER mode only */
805 		case CTL_MSG_DATAMOVE_DONE: {
806 			if (msg_info.hdr.serializing_sc == NULL) {
807 				printf("%s: serializing_sc == NULL!\n",
808 				       __func__);
809 				/* XXX KDM now what? */
810 				break;
811 			}
812 			/*
813 			 * We grab the sense information here in case
814 			 * there was a failure, so we can return status
815 			 * back to the initiator.
816 			 */
817 			io = msg_info.hdr.serializing_sc;
818 			io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
819 			io->io_hdr.status = msg_info.hdr.status;
820 			io->scsiio.scsi_status = msg_info.scsi.scsi_status;
821 			io->scsiio.sense_len = msg_info.scsi.sense_len;
822 			io->scsiio.sense_residual =msg_info.scsi.sense_residual;
823 			io->io_hdr.port_status = msg_info.scsi.fetd_status;
824 			io->scsiio.residual = msg_info.scsi.residual;
825 			memcpy(&io->scsiio.sense_data,&msg_info.scsi.sense_data,
826 			       sizeof(io->scsiio.sense_data));
827 			ctl_enqueue_isc(io);
828 			break;
829 		}
830 
831 		/* Preformed on Originating SC, SER_ONLY mode */
832 		case CTL_MSG_R2R:
833 			io = msg_info.hdr.original_sc;
834 			if (io == NULL) {
835 				printf("%s: Major Bummer\n", __func__);
836 				return;
837 			} else {
838 #if 0
839 				printf("pOrig %x\n",(int) ctsio);
840 #endif
841 			}
842 			io->io_hdr.msg_type = CTL_MSG_R2R;
843 			io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
844 			ctl_enqueue_isc(io);
845 			break;
846 
847 		/*
848 		 * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
849 		 * mode.
850 		 * Performed on the Originating (i.e. secondary) SC in XFER
851 		 * mode
852 		 */
853 		case CTL_MSG_FINISH_IO:
854 			if (softc->ha_mode == CTL_HA_MODE_XFER)
855 				ctl_isc_handler_finish_xfer(softc,
856 							    &msg_info);
857 			else
858 				ctl_isc_handler_finish_ser_only(softc,
859 								&msg_info);
860 			break;
861 
862 		/* Preformed on Originating SC */
863 		case CTL_MSG_BAD_JUJU:
864 			io = msg_info.hdr.original_sc;
865 			if (io == NULL) {
866 				printf("%s: Bad JUJU!, original_sc is NULL!\n",
867 				       __func__);
868 				break;
869 			}
870 			ctl_copy_sense_data(&msg_info, io);
871 			/*
872 			 * IO should have already been cleaned up on other
873 			 * SC so clear this flag so we won't send a message
874 			 * back to finish the IO there.
875 			 */
876 			io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
877 			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
878 
879 			/* io = msg_info.hdr.serializing_sc; */
880 			io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
881 			ctl_enqueue_isc(io);
882 			break;
883 
884 		/* Handle resets sent from the other side */
885 		case CTL_MSG_MANAGE_TASKS: {
886 			struct ctl_taskio *taskio;
887 			taskio = (struct ctl_taskio *)ctl_alloc_io_nowait(
888 			    softc->othersc_pool);
889 			if (taskio == NULL) {
890 				printf("ctl_isc_event_handler: can't allocate "
891 				       "ctl_io!\n");
892 				/* Bad Juju */
893 				/* should I just call the proper reset func
894 				   here??? */
895 				goto bailout;
896 			}
897 			ctl_zero_io((union ctl_io *)taskio);
898 			taskio->io_hdr.io_type = CTL_IO_TASK;
899 			taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
900 			taskio->io_hdr.nexus = msg_info.hdr.nexus;
901 			taskio->task_action = msg_info.task.task_action;
902 			taskio->tag_num = msg_info.task.tag_num;
903 			taskio->tag_type = msg_info.task.tag_type;
904 #ifdef CTL_TIME_IO
905 			taskio->io_hdr.start_time = time_uptime;
906 			getbintime(&taskio->io_hdr.start_bt);
907 #if 0
908 			cs_prof_gettime(&taskio->io_hdr.start_ticks);
909 #endif
910 #endif /* CTL_TIME_IO */
911 			ctl_run_task((union ctl_io *)taskio);
912 			break;
913 		}
914 		/* Persistent Reserve action which needs attention */
915 		case CTL_MSG_PERS_ACTION:
916 			presio = (struct ctl_prio *)ctl_alloc_io_nowait(
917 			    softc->othersc_pool);
918 			if (presio == NULL) {
919 				printf("ctl_isc_event_handler: can't allocate "
920 				       "ctl_io!\n");
921 				/* Bad Juju */
922 				/* Need to set busy and send msg back */
923 				goto bailout;
924 			}
925 			ctl_zero_io((union ctl_io *)presio);
926 			presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
927 			presio->pr_msg = msg_info.pr;
928 			ctl_enqueue_isc((union ctl_io *)presio);
929 			break;
930 		case CTL_MSG_SYNC_FE:
931 			rcv_sync_msg = 1;
932 			break;
933 		default:
934 		        printf("How did I get here?\n");
935 		}
936 	} else if (event == CTL_HA_EVT_MSG_SENT) {
937 		if (param != CTL_HA_STATUS_SUCCESS) {
938 			printf("Bad status from ctl_ha_msg_send status %d\n",
939 			       param);
940 		}
941 		return;
942 	} else if (event == CTL_HA_EVT_DISCONNECT) {
943 		printf("CTL: Got a disconnect from Isc\n");
944 		return;
945 	} else {
946 		printf("ctl_isc_event_handler: Unknown event %d\n", event);
947 		return;
948 	}
949 
950 bailout:
951 	return;
952 }
953 
954 static void
955 ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
956 {
957 	struct scsi_sense_data *sense;
958 
959 	sense = &dest->scsiio.sense_data;
960 	bcopy(&src->scsi.sense_data, sense, sizeof(*sense));
961 	dest->scsiio.scsi_status = src->scsi.scsi_status;
962 	dest->scsiio.sense_len = src->scsi.sense_len;
963 	dest->io_hdr.status = src->hdr.status;
964 }
965 
966 static void
967 ctl_est_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
968 {
969 	ctl_ua_type *pu;
970 
971 	mtx_assert(&lun->lun_lock, MA_OWNED);
972 	pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
973 	if (pu == NULL)
974 		return;
975 	pu[initidx % CTL_MAX_INIT_PER_PORT] |= ua;
976 }
977 
978 static void
979 ctl_est_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
980 {
981 	int i, j;
982 
983 	mtx_assert(&lun->lun_lock, MA_OWNED);
984 	for (i = 0; i < CTL_MAX_PORTS; i++) {
985 		if (lun->pending_ua[i] == NULL)
986 			continue;
987 		for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
988 			if (i * CTL_MAX_INIT_PER_PORT + j == except)
989 				continue;
990 			lun->pending_ua[i][j] |= ua;
991 		}
992 	}
993 }
994 
995 static void
996 ctl_clr_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
997 {
998 	ctl_ua_type *pu;
999 
1000 	mtx_assert(&lun->lun_lock, MA_OWNED);
1001 	pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1002 	if (pu == NULL)
1003 		return;
1004 	pu[initidx % CTL_MAX_INIT_PER_PORT] &= ~ua;
1005 }
1006 
1007 static void
1008 ctl_clr_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1009 {
1010 	int i, j;
1011 
1012 	mtx_assert(&lun->lun_lock, MA_OWNED);
1013 	for (i = 0; i < CTL_MAX_PORTS; i++) {
1014 		if (lun->pending_ua[i] == NULL)
1015 			continue;
1016 		for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
1017 			if (i * CTL_MAX_INIT_PER_PORT + j == except)
1018 				continue;
1019 			lun->pending_ua[i][j] &= ~ua;
1020 		}
1021 	}
1022 }
1023 
1024 static int
1025 ctl_ha_state_sysctl(SYSCTL_HANDLER_ARGS)
1026 {
1027 	struct ctl_softc *softc = (struct ctl_softc *)arg1;
1028 	struct ctl_lun *lun;
1029 	int error, value;
1030 
1031 	if (softc->flags & CTL_FLAG_ACTIVE_SHELF)
1032 		value = 0;
1033 	else
1034 		value = 1;
1035 
1036 	error = sysctl_handle_int(oidp, &value, 0, req);
1037 	if ((error != 0) || (req->newptr == NULL))
1038 		return (error);
1039 
1040 	mtx_lock(&softc->ctl_lock);
1041 	if (value == 0)
1042 		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1043 	else
1044 		softc->flags &= ~CTL_FLAG_ACTIVE_SHELF;
1045 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
1046 		mtx_lock(&lun->lun_lock);
1047 		ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
1048 		mtx_unlock(&lun->lun_lock);
1049 	}
1050 	mtx_unlock(&softc->ctl_lock);
1051 	return (0);
1052 }
1053 
1054 static int
1055 ctl_init(void)
1056 {
1057 	struct ctl_softc *softc;
1058 	void *other_pool;
1059 	struct ctl_port *port;
1060 	int i, error, retval;
1061 	//int isc_retval;
1062 
1063 	retval = 0;
1064 	ctl_pause_rtr = 0;
1065         rcv_sync_msg = 0;
1066 
1067 	control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
1068 			       M_WAITOK | M_ZERO);
1069 	softc = control_softc;
1070 
1071 	softc->dev = make_dev(&ctl_cdevsw, 0, UID_ROOT, GID_OPERATOR, 0600,
1072 			      "cam/ctl");
1073 
1074 	softc->dev->si_drv1 = softc;
1075 
1076 	/*
1077 	 * By default, return a "bad LUN" peripheral qualifier for unknown
1078 	 * LUNs.  The user can override this default using the tunable or
1079 	 * sysctl.  See the comment in ctl_inquiry_std() for more details.
1080 	 */
1081 	softc->inquiry_pq_no_lun = 1;
1082 	TUNABLE_INT_FETCH("kern.cam.ctl.inquiry_pq_no_lun",
1083 			  &softc->inquiry_pq_no_lun);
1084 	sysctl_ctx_init(&softc->sysctl_ctx);
1085 	softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
1086 		SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
1087 		CTLFLAG_RD, 0, "CAM Target Layer");
1088 
1089 	if (softc->sysctl_tree == NULL) {
1090 		printf("%s: unable to allocate sysctl tree\n", __func__);
1091 		destroy_dev(softc->dev);
1092 		free(control_softc, M_DEVBUF);
1093 		control_softc = NULL;
1094 		return (ENOMEM);
1095 	}
1096 
1097 	SYSCTL_ADD_INT(&softc->sysctl_ctx,
1098 		       SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
1099 		       "inquiry_pq_no_lun", CTLFLAG_RW,
1100 		       &softc->inquiry_pq_no_lun, 0,
1101 		       "Report no lun possible for invalid LUNs");
1102 
1103 	mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
1104 	softc->io_zone = uma_zcreate("CTL IO", sizeof(union ctl_io),
1105 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1106 	softc->open_count = 0;
1107 
1108 	/*
1109 	 * Default to actually sending a SYNCHRONIZE CACHE command down to
1110 	 * the drive.
1111 	 */
1112 	softc->flags = CTL_FLAG_REAL_SYNC;
1113 
1114 	/*
1115 	 * In Copan's HA scheme, the "master" and "slave" roles are
1116 	 * figured out through the slot the controller is in.  Although it
1117 	 * is an active/active system, someone has to be in charge.
1118 	 */
1119 	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1120 	    OID_AUTO, "ha_id", CTLFLAG_RDTUN, &softc->ha_id, 0,
1121 	    "HA head ID (0 - no HA)");
1122 	if (softc->ha_id == 0) {
1123 		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1124 		softc->is_single = 1;
1125 		softc->port_offset = 0;
1126 	} else
1127 		softc->port_offset = (softc->ha_id - 1) * CTL_MAX_PORTS;
1128 	softc->persis_offset = softc->port_offset * CTL_MAX_INIT_PER_PORT;
1129 
1130 	/*
1131 	 * XXX KDM need to figure out where we want to get our target ID
1132 	 * and WWID.  Is it different on each port?
1133 	 */
1134 	softc->target.id = 0;
1135 	softc->target.wwid[0] = 0x12345678;
1136 	softc->target.wwid[1] = 0x87654321;
1137 	STAILQ_INIT(&softc->lun_list);
1138 	STAILQ_INIT(&softc->pending_lun_queue);
1139 	STAILQ_INIT(&softc->fe_list);
1140 	STAILQ_INIT(&softc->port_list);
1141 	STAILQ_INIT(&softc->be_list);
1142 	ctl_tpc_init(softc);
1143 
1144 	if (ctl_pool_create(softc, "othersc", CTL_POOL_ENTRIES_OTHER_SC,
1145 	                    &other_pool) != 0)
1146 	{
1147 		printf("ctl: can't allocate %d entry other SC pool, "
1148 		       "exiting\n", CTL_POOL_ENTRIES_OTHER_SC);
1149 		return (ENOMEM);
1150 	}
1151 	softc->othersc_pool = other_pool;
1152 
1153 	if (worker_threads <= 0)
1154 		worker_threads = max(1, mp_ncpus / 4);
1155 	if (worker_threads > CTL_MAX_THREADS)
1156 		worker_threads = CTL_MAX_THREADS;
1157 
1158 	for (i = 0; i < worker_threads; i++) {
1159 		struct ctl_thread *thr = &softc->threads[i];
1160 
1161 		mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1162 		thr->ctl_softc = softc;
1163 		STAILQ_INIT(&thr->incoming_queue);
1164 		STAILQ_INIT(&thr->rtr_queue);
1165 		STAILQ_INIT(&thr->done_queue);
1166 		STAILQ_INIT(&thr->isc_queue);
1167 
1168 		error = kproc_kthread_add(ctl_work_thread, thr,
1169 		    &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1170 		if (error != 0) {
1171 			printf("error creating CTL work thread!\n");
1172 			ctl_pool_free(other_pool);
1173 			return (error);
1174 		}
1175 	}
1176 	error = kproc_kthread_add(ctl_lun_thread, softc,
1177 	    &softc->ctl_proc, NULL, 0, 0, "ctl", "lun");
1178 	if (error != 0) {
1179 		printf("error creating CTL lun thread!\n");
1180 		ctl_pool_free(other_pool);
1181 		return (error);
1182 	}
1183 	error = kproc_kthread_add(ctl_thresh_thread, softc,
1184 	    &softc->ctl_proc, NULL, 0, 0, "ctl", "thresh");
1185 	if (error != 0) {
1186 		printf("error creating CTL threshold thread!\n");
1187 		ctl_pool_free(other_pool);
1188 		return (error);
1189 	}
1190 	if (bootverbose)
1191 		printf("ctl: CAM Target Layer loaded\n");
1192 
1193 	/*
1194 	 * Initialize the ioctl front end.
1195 	 */
1196 	ctl_frontend_register(&ioctl_frontend);
1197 	port = &softc->ioctl_info.port;
1198 	port->frontend = &ioctl_frontend;
1199 	sprintf(softc->ioctl_info.port_name, "ioctl");
1200 	port->port_type = CTL_PORT_IOCTL;
1201 	port->num_requested_ctl_io = 100;
1202 	port->port_name = softc->ioctl_info.port_name;
1203 	port->port_online = ctl_ioctl_online;
1204 	port->port_offline = ctl_ioctl_offline;
1205 	port->onoff_arg = &softc->ioctl_info;
1206 	port->lun_enable = ctl_ioctl_lun_enable;
1207 	port->lun_disable = ctl_ioctl_lun_disable;
1208 	port->targ_lun_arg = &softc->ioctl_info;
1209 	port->fe_datamove = ctl_ioctl_datamove;
1210 	port->fe_done = ctl_ioctl_done;
1211 	port->max_targets = 15;
1212 	port->max_target_id = 15;
1213 
1214 	if (ctl_port_register(&softc->ioctl_info.port) != 0) {
1215 		printf("ctl: ioctl front end registration failed, will "
1216 		       "continue anyway\n");
1217 	}
1218 
1219 	SYSCTL_ADD_PROC(&softc->sysctl_ctx,SYSCTL_CHILDREN(softc->sysctl_tree),
1220 	    OID_AUTO, "ha_state", CTLTYPE_INT | CTLFLAG_RWTUN,
1221 	    softc, 0, ctl_ha_state_sysctl, "I", "HA state for this head");
1222 
1223 #ifdef CTL_IO_DELAY
1224 	if (sizeof(struct callout) > CTL_TIMER_BYTES) {
1225 		printf("sizeof(struct callout) %zd > CTL_TIMER_BYTES %zd\n",
1226 		       sizeof(struct callout), CTL_TIMER_BYTES);
1227 		return (EINVAL);
1228 	}
1229 #endif /* CTL_IO_DELAY */
1230 
1231 	return (0);
1232 }
1233 
1234 void
1235 ctl_shutdown(void)
1236 {
1237 	struct ctl_softc *softc;
1238 	struct ctl_lun *lun, *next_lun;
1239 
1240 	softc = (struct ctl_softc *)control_softc;
1241 
1242 	if (ctl_port_deregister(&softc->ioctl_info.port) != 0)
1243 		printf("ctl: ioctl front end deregistration failed\n");
1244 
1245 	mtx_lock(&softc->ctl_lock);
1246 
1247 	/*
1248 	 * Free up each LUN.
1249 	 */
1250 	for (lun = STAILQ_FIRST(&softc->lun_list); lun != NULL; lun = next_lun){
1251 		next_lun = STAILQ_NEXT(lun, links);
1252 		ctl_free_lun(lun);
1253 	}
1254 
1255 	mtx_unlock(&softc->ctl_lock);
1256 
1257 	ctl_frontend_deregister(&ioctl_frontend);
1258 
1259 #if 0
1260 	ctl_shutdown_thread(softc->work_thread);
1261 	mtx_destroy(&softc->queue_lock);
1262 #endif
1263 
1264 	ctl_tpc_shutdown(softc);
1265 	uma_zdestroy(softc->io_zone);
1266 	mtx_destroy(&softc->ctl_lock);
1267 
1268 	destroy_dev(softc->dev);
1269 
1270 	sysctl_ctx_free(&softc->sysctl_ctx);
1271 
1272 	free(control_softc, M_DEVBUF);
1273 	control_softc = NULL;
1274 
1275 	if (bootverbose)
1276 		printf("ctl: CAM Target Layer unloaded\n");
1277 }
1278 
1279 static int
1280 ctl_module_event_handler(module_t mod, int what, void *arg)
1281 {
1282 
1283 	switch (what) {
1284 	case MOD_LOAD:
1285 		return (ctl_init());
1286 	case MOD_UNLOAD:
1287 		return (EBUSY);
1288 	default:
1289 		return (EOPNOTSUPP);
1290 	}
1291 }
1292 
1293 /*
1294  * XXX KDM should we do some access checks here?  Bump a reference count to
1295  * prevent a CTL module from being unloaded while someone has it open?
1296  */
1297 static int
1298 ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
1299 {
1300 	return (0);
1301 }
1302 
1303 static int
1304 ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
1305 {
1306 	return (0);
1307 }
1308 
1309 int
1310 ctl_port_enable(ctl_port_type port_type)
1311 {
1312 	struct ctl_softc *softc = control_softc;
1313 	struct ctl_port *port;
1314 
1315 	if (softc->is_single == 0) {
1316 		union ctl_ha_msg msg_info;
1317 		int isc_retval;
1318 
1319 #if 0
1320 		printf("%s: HA mode, synchronizing frontend enable\n",
1321 		        __func__);
1322 #endif
1323 		msg_info.hdr.msg_type = CTL_MSG_SYNC_FE;
1324 	        if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1325 		        sizeof(msg_info), 1 )) > CTL_HA_STATUS_SUCCESS) {
1326 			printf("Sync msg send error retval %d\n", isc_retval);
1327 		}
1328 		if (!rcv_sync_msg) {
1329 			isc_retval=ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
1330 			        sizeof(msg_info), 1);
1331 		}
1332 #if 0
1333         	printf("CTL:Frontend Enable\n");
1334 	} else {
1335 		printf("%s: single mode, skipping frontend synchronization\n",
1336 		        __func__);
1337 #endif
1338 	}
1339 
1340 	STAILQ_FOREACH(port, &softc->port_list, links) {
1341 		if (port_type & port->port_type)
1342 		{
1343 #if 0
1344 			printf("port %d\n", port->targ_port);
1345 #endif
1346 			ctl_port_online(port);
1347 		}
1348 	}
1349 
1350 	return (0);
1351 }
1352 
1353 int
1354 ctl_port_disable(ctl_port_type port_type)
1355 {
1356 	struct ctl_softc *softc;
1357 	struct ctl_port *port;
1358 
1359 	softc = control_softc;
1360 
1361 	STAILQ_FOREACH(port, &softc->port_list, links) {
1362 		if (port_type & port->port_type)
1363 			ctl_port_offline(port);
1364 	}
1365 
1366 	return (0);
1367 }
1368 
1369 /*
1370  * Returns 0 for success, 1 for failure.
1371  * Currently the only failure mode is if there aren't enough entries
1372  * allocated.  So, in case of a failure, look at num_entries_dropped,
1373  * reallocate and try again.
1374  */
1375 int
1376 ctl_port_list(struct ctl_port_entry *entries, int num_entries_alloced,
1377 	      int *num_entries_filled, int *num_entries_dropped,
1378 	      ctl_port_type port_type, int no_virtual)
1379 {
1380 	struct ctl_softc *softc;
1381 	struct ctl_port *port;
1382 	int entries_dropped, entries_filled;
1383 	int retval;
1384 	int i;
1385 
1386 	softc = control_softc;
1387 
1388 	retval = 0;
1389 	entries_filled = 0;
1390 	entries_dropped = 0;
1391 
1392 	i = 0;
1393 	mtx_lock(&softc->ctl_lock);
1394 	STAILQ_FOREACH(port, &softc->port_list, links) {
1395 		struct ctl_port_entry *entry;
1396 
1397 		if ((port->port_type & port_type) == 0)
1398 			continue;
1399 
1400 		if ((no_virtual != 0)
1401 		 && (port->virtual_port != 0))
1402 			continue;
1403 
1404 		if (entries_filled >= num_entries_alloced) {
1405 			entries_dropped++;
1406 			continue;
1407 		}
1408 		entry = &entries[i];
1409 
1410 		entry->port_type = port->port_type;
1411 		strlcpy(entry->port_name, port->port_name,
1412 			sizeof(entry->port_name));
1413 		entry->physical_port = port->physical_port;
1414 		entry->virtual_port = port->virtual_port;
1415 		entry->wwnn = port->wwnn;
1416 		entry->wwpn = port->wwpn;
1417 
1418 		i++;
1419 		entries_filled++;
1420 	}
1421 
1422 	mtx_unlock(&softc->ctl_lock);
1423 
1424 	if (entries_dropped > 0)
1425 		retval = 1;
1426 
1427 	*num_entries_dropped = entries_dropped;
1428 	*num_entries_filled = entries_filled;
1429 
1430 	return (retval);
1431 }
1432 
1433 static void
1434 ctl_ioctl_online(void *arg)
1435 {
1436 	struct ctl_ioctl_info *ioctl_info;
1437 
1438 	ioctl_info = (struct ctl_ioctl_info *)arg;
1439 
1440 	ioctl_info->flags |= CTL_IOCTL_FLAG_ENABLED;
1441 }
1442 
1443 static void
1444 ctl_ioctl_offline(void *arg)
1445 {
1446 	struct ctl_ioctl_info *ioctl_info;
1447 
1448 	ioctl_info = (struct ctl_ioctl_info *)arg;
1449 
1450 	ioctl_info->flags &= ~CTL_IOCTL_FLAG_ENABLED;
1451 }
1452 
1453 /*
1454  * Remove an initiator by port number and initiator ID.
1455  * Returns 0 for success, -1 for failure.
1456  */
1457 int
1458 ctl_remove_initiator(struct ctl_port *port, int iid)
1459 {
1460 	struct ctl_softc *softc = control_softc;
1461 
1462 	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1463 
1464 	if (iid > CTL_MAX_INIT_PER_PORT) {
1465 		printf("%s: initiator ID %u > maximun %u!\n",
1466 		       __func__, iid, CTL_MAX_INIT_PER_PORT);
1467 		return (-1);
1468 	}
1469 
1470 	mtx_lock(&softc->ctl_lock);
1471 	port->wwpn_iid[iid].in_use--;
1472 	port->wwpn_iid[iid].last_use = time_uptime;
1473 	mtx_unlock(&softc->ctl_lock);
1474 
1475 	return (0);
1476 }
1477 
1478 /*
1479  * Add an initiator to the initiator map.
1480  * Returns iid for success, < 0 for failure.
1481  */
1482 int
1483 ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
1484 {
1485 	struct ctl_softc *softc = control_softc;
1486 	time_t best_time;
1487 	int i, best;
1488 
1489 	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1490 
1491 	if (iid >= CTL_MAX_INIT_PER_PORT) {
1492 		printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
1493 		       __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
1494 		free(name, M_CTL);
1495 		return (-1);
1496 	}
1497 
1498 	mtx_lock(&softc->ctl_lock);
1499 
1500 	if (iid < 0 && (wwpn != 0 || name != NULL)) {
1501 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1502 			if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
1503 				iid = i;
1504 				break;
1505 			}
1506 			if (name != NULL && port->wwpn_iid[i].name != NULL &&
1507 			    strcmp(name, port->wwpn_iid[i].name) == 0) {
1508 				iid = i;
1509 				break;
1510 			}
1511 		}
1512 	}
1513 
1514 	if (iid < 0) {
1515 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1516 			if (port->wwpn_iid[i].in_use == 0 &&
1517 			    port->wwpn_iid[i].wwpn == 0 &&
1518 			    port->wwpn_iid[i].name == NULL) {
1519 				iid = i;
1520 				break;
1521 			}
1522 		}
1523 	}
1524 
1525 	if (iid < 0) {
1526 		best = -1;
1527 		best_time = INT32_MAX;
1528 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1529 			if (port->wwpn_iid[i].in_use == 0) {
1530 				if (port->wwpn_iid[i].last_use < best_time) {
1531 					best = i;
1532 					best_time = port->wwpn_iid[i].last_use;
1533 				}
1534 			}
1535 		}
1536 		iid = best;
1537 	}
1538 
1539 	if (iid < 0) {
1540 		mtx_unlock(&softc->ctl_lock);
1541 		free(name, M_CTL);
1542 		return (-2);
1543 	}
1544 
1545 	if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
1546 		/*
1547 		 * This is not an error yet.
1548 		 */
1549 		if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
1550 #if 0
1551 			printf("%s: port %d iid %u WWPN %#jx arrived"
1552 			    " again\n", __func__, port->targ_port,
1553 			    iid, (uintmax_t)wwpn);
1554 #endif
1555 			goto take;
1556 		}
1557 		if (name != NULL && port->wwpn_iid[iid].name != NULL &&
1558 		    strcmp(name, port->wwpn_iid[iid].name) == 0) {
1559 #if 0
1560 			printf("%s: port %d iid %u name '%s' arrived"
1561 			    " again\n", __func__, port->targ_port,
1562 			    iid, name);
1563 #endif
1564 			goto take;
1565 		}
1566 
1567 		/*
1568 		 * This is an error, but what do we do about it?  The
1569 		 * driver is telling us we have a new WWPN for this
1570 		 * initiator ID, so we pretty much need to use it.
1571 		 */
1572 		printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
1573 		    " but WWPN %#jx '%s' is still at that address\n",
1574 		    __func__, port->targ_port, iid, wwpn, name,
1575 		    (uintmax_t)port->wwpn_iid[iid].wwpn,
1576 		    port->wwpn_iid[iid].name);
1577 
1578 		/*
1579 		 * XXX KDM clear have_ca and ua_pending on each LUN for
1580 		 * this initiator.
1581 		 */
1582 	}
1583 take:
1584 	free(port->wwpn_iid[iid].name, M_CTL);
1585 	port->wwpn_iid[iid].name = name;
1586 	port->wwpn_iid[iid].wwpn = wwpn;
1587 	port->wwpn_iid[iid].in_use++;
1588 	mtx_unlock(&softc->ctl_lock);
1589 
1590 	return (iid);
1591 }
1592 
1593 static int
1594 ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
1595 {
1596 	int len;
1597 
1598 	switch (port->port_type) {
1599 	case CTL_PORT_FC:
1600 	{
1601 		struct scsi_transportid_fcp *id =
1602 		    (struct scsi_transportid_fcp *)buf;
1603 		if (port->wwpn_iid[iid].wwpn == 0)
1604 			return (0);
1605 		memset(id, 0, sizeof(*id));
1606 		id->format_protocol = SCSI_PROTO_FC;
1607 		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
1608 		return (sizeof(*id));
1609 	}
1610 	case CTL_PORT_ISCSI:
1611 	{
1612 		struct scsi_transportid_iscsi_port *id =
1613 		    (struct scsi_transportid_iscsi_port *)buf;
1614 		if (port->wwpn_iid[iid].name == NULL)
1615 			return (0);
1616 		memset(id, 0, 256);
1617 		id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
1618 		    SCSI_PROTO_ISCSI;
1619 		len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
1620 		len = roundup2(min(len, 252), 4);
1621 		scsi_ulto2b(len, id->additional_length);
1622 		return (sizeof(*id) + len);
1623 	}
1624 	case CTL_PORT_SAS:
1625 	{
1626 		struct scsi_transportid_sas *id =
1627 		    (struct scsi_transportid_sas *)buf;
1628 		if (port->wwpn_iid[iid].wwpn == 0)
1629 			return (0);
1630 		memset(id, 0, sizeof(*id));
1631 		id->format_protocol = SCSI_PROTO_SAS;
1632 		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
1633 		return (sizeof(*id));
1634 	}
1635 	default:
1636 	{
1637 		struct scsi_transportid_spi *id =
1638 		    (struct scsi_transportid_spi *)buf;
1639 		memset(id, 0, sizeof(*id));
1640 		id->format_protocol = SCSI_PROTO_SPI;
1641 		scsi_ulto2b(iid, id->scsi_addr);
1642 		scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
1643 		return (sizeof(*id));
1644 	}
1645 	}
1646 }
1647 
1648 static int
1649 ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id)
1650 {
1651 	return (0);
1652 }
1653 
1654 static int
1655 ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id)
1656 {
1657 	return (0);
1658 }
1659 
1660 /*
1661  * Data movement routine for the CTL ioctl frontend port.
1662  */
1663 static int
1664 ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio)
1665 {
1666 	struct ctl_sg_entry *ext_sglist, *kern_sglist;
1667 	struct ctl_sg_entry ext_entry, kern_entry;
1668 	int ext_sglen, ext_sg_entries, kern_sg_entries;
1669 	int ext_sg_start, ext_offset;
1670 	int len_to_copy, len_copied;
1671 	int kern_watermark, ext_watermark;
1672 	int ext_sglist_malloced;
1673 	int i, j;
1674 
1675 	ext_sglist_malloced = 0;
1676 	ext_sg_start = 0;
1677 	ext_offset = 0;
1678 
1679 	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove\n"));
1680 
1681 	/*
1682 	 * If this flag is set, fake the data transfer.
1683 	 */
1684 	if (ctsio->io_hdr.flags & CTL_FLAG_NO_DATAMOVE) {
1685 		ctsio->ext_data_filled = ctsio->ext_data_len;
1686 		goto bailout;
1687 	}
1688 
1689 	/*
1690 	 * To simplify things here, if we have a single buffer, stick it in
1691 	 * a S/G entry and just make it a single entry S/G list.
1692 	 */
1693 	if (ctsio->io_hdr.flags & CTL_FLAG_EDPTR_SGLIST) {
1694 		int len_seen;
1695 
1696 		ext_sglen = ctsio->ext_sg_entries * sizeof(*ext_sglist);
1697 
1698 		ext_sglist = (struct ctl_sg_entry *)malloc(ext_sglen, M_CTL,
1699 							   M_WAITOK);
1700 		ext_sglist_malloced = 1;
1701 		if (copyin(ctsio->ext_data_ptr, ext_sglist,
1702 				   ext_sglen) != 0) {
1703 			ctl_set_internal_failure(ctsio,
1704 						 /*sks_valid*/ 0,
1705 						 /*retry_count*/ 0);
1706 			goto bailout;
1707 		}
1708 		ext_sg_entries = ctsio->ext_sg_entries;
1709 		len_seen = 0;
1710 		for (i = 0; i < ext_sg_entries; i++) {
1711 			if ((len_seen + ext_sglist[i].len) >=
1712 			     ctsio->ext_data_filled) {
1713 				ext_sg_start = i;
1714 				ext_offset = ctsio->ext_data_filled - len_seen;
1715 				break;
1716 			}
1717 			len_seen += ext_sglist[i].len;
1718 		}
1719 	} else {
1720 		ext_sglist = &ext_entry;
1721 		ext_sglist->addr = ctsio->ext_data_ptr;
1722 		ext_sglist->len = ctsio->ext_data_len;
1723 		ext_sg_entries = 1;
1724 		ext_sg_start = 0;
1725 		ext_offset = ctsio->ext_data_filled;
1726 	}
1727 
1728 	if (ctsio->kern_sg_entries > 0) {
1729 		kern_sglist = (struct ctl_sg_entry *)ctsio->kern_data_ptr;
1730 		kern_sg_entries = ctsio->kern_sg_entries;
1731 	} else {
1732 		kern_sglist = &kern_entry;
1733 		kern_sglist->addr = ctsio->kern_data_ptr;
1734 		kern_sglist->len = ctsio->kern_data_len;
1735 		kern_sg_entries = 1;
1736 	}
1737 
1738 
1739 	kern_watermark = 0;
1740 	ext_watermark = ext_offset;
1741 	len_copied = 0;
1742 	for (i = ext_sg_start, j = 0;
1743 	     i < ext_sg_entries && j < kern_sg_entries;) {
1744 		uint8_t *ext_ptr, *kern_ptr;
1745 
1746 		len_to_copy = MIN(ext_sglist[i].len - ext_watermark,
1747 				  kern_sglist[j].len - kern_watermark);
1748 
1749 		ext_ptr = (uint8_t *)ext_sglist[i].addr;
1750 		ext_ptr = ext_ptr + ext_watermark;
1751 		if (ctsio->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
1752 			/*
1753 			 * XXX KDM fix this!
1754 			 */
1755 			panic("need to implement bus address support");
1756 #if 0
1757 			kern_ptr = bus_to_virt(kern_sglist[j].addr);
1758 #endif
1759 		} else
1760 			kern_ptr = (uint8_t *)kern_sglist[j].addr;
1761 		kern_ptr = kern_ptr + kern_watermark;
1762 
1763 		kern_watermark += len_to_copy;
1764 		ext_watermark += len_to_copy;
1765 
1766 		if ((ctsio->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
1767 		     CTL_FLAG_DATA_IN) {
1768 			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1769 					 "bytes to user\n", len_to_copy));
1770 			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1771 					 "to %p\n", kern_ptr, ext_ptr));
1772 			if (copyout(kern_ptr, ext_ptr, len_to_copy) != 0) {
1773 				ctl_set_internal_failure(ctsio,
1774 							 /*sks_valid*/ 0,
1775 							 /*retry_count*/ 0);
1776 				goto bailout;
1777 			}
1778 		} else {
1779 			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1780 					 "bytes from user\n", len_to_copy));
1781 			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1782 					 "to %p\n", ext_ptr, kern_ptr));
1783 			if (copyin(ext_ptr, kern_ptr, len_to_copy)!= 0){
1784 				ctl_set_internal_failure(ctsio,
1785 							 /*sks_valid*/ 0,
1786 							 /*retry_count*/0);
1787 				goto bailout;
1788 			}
1789 		}
1790 
1791 		len_copied += len_to_copy;
1792 
1793 		if (ext_sglist[i].len == ext_watermark) {
1794 			i++;
1795 			ext_watermark = 0;
1796 		}
1797 
1798 		if (kern_sglist[j].len == kern_watermark) {
1799 			j++;
1800 			kern_watermark = 0;
1801 		}
1802 	}
1803 
1804 	ctsio->ext_data_filled += len_copied;
1805 
1806 	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_sg_entries: %d, "
1807 			 "kern_sg_entries: %d\n", ext_sg_entries,
1808 			 kern_sg_entries));
1809 	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_data_len = %d, "
1810 			 "kern_data_len = %d\n", ctsio->ext_data_len,
1811 			 ctsio->kern_data_len));
1812 
1813 
1814 	/* XXX KDM set residual?? */
1815 bailout:
1816 
1817 	if (ext_sglist_malloced != 0)
1818 		free(ext_sglist, M_CTL);
1819 
1820 	return (CTL_RETVAL_COMPLETE);
1821 }
1822 
1823 /*
1824  * Serialize a command that went down the "wrong" side, and so was sent to
1825  * this controller for execution.  The logic is a little different than the
1826  * standard case in ctl_scsiio_precheck().  Errors in this case need to get
1827  * sent back to the other side, but in the success case, we execute the
1828  * command on this side (XFER mode) or tell the other side to execute it
1829  * (SER_ONLY mode).
1830  */
1831 static int
1832 ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
1833 {
1834 	struct ctl_softc *softc;
1835 	union ctl_ha_msg msg_info;
1836 	struct ctl_lun *lun;
1837 	int retval = 0;
1838 	uint32_t targ_lun;
1839 
1840 	softc = control_softc;
1841 
1842 	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
1843 	lun = softc->ctl_luns[targ_lun];
1844 	if (lun==NULL)
1845 	{
1846 		/*
1847 		 * Why isn't LUN defined? The other side wouldn't
1848 		 * send a cmd if the LUN is undefined.
1849 		 */
1850 		printf("%s: Bad JUJU!, LUN is NULL!\n", __func__);
1851 
1852 		/* "Logical unit not supported" */
1853 		ctl_set_sense_data(&msg_info.scsi.sense_data,
1854 				   lun,
1855 				   /*sense_format*/SSD_TYPE_NONE,
1856 				   /*current_error*/ 1,
1857 				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1858 				   /*asc*/ 0x25,
1859 				   /*ascq*/ 0x00,
1860 				   SSD_ELEM_NONE);
1861 
1862 		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1863 		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1864 		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1865 		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1866 		msg_info.hdr.serializing_sc = NULL;
1867 		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1868 	        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1869 				sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1870 		}
1871 		return(1);
1872 
1873 	}
1874 
1875 	mtx_lock(&lun->lun_lock);
1876     	TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1877 
1878 	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
1879 		(union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
1880 		 ooa_links))) {
1881 	case CTL_ACTION_BLOCK:
1882 		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
1883 		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
1884 				  blocked_links);
1885 		break;
1886 	case CTL_ACTION_PASS:
1887 	case CTL_ACTION_SKIP:
1888 		if (softc->ha_mode == CTL_HA_MODE_XFER) {
1889 			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
1890 			ctl_enqueue_rtr((union ctl_io *)ctsio);
1891 		} else {
1892 
1893 			/* send msg back to other side */
1894 			msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1895 			msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
1896 			msg_info.hdr.msg_type = CTL_MSG_R2R;
1897 #if 0
1898 			printf("2. pOrig %x\n", (int)msg_info.hdr.original_sc);
1899 #endif
1900 		        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1901 			    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1902 			}
1903 		}
1904 		break;
1905 	case CTL_ACTION_OVERLAP:
1906 		/* OVERLAPPED COMMANDS ATTEMPTED */
1907 		ctl_set_sense_data(&msg_info.scsi.sense_data,
1908 				   lun,
1909 				   /*sense_format*/SSD_TYPE_NONE,
1910 				   /*current_error*/ 1,
1911 				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1912 				   /*asc*/ 0x4E,
1913 				   /*ascq*/ 0x00,
1914 				   SSD_ELEM_NONE);
1915 
1916 		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1917 		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1918 		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1919 		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1920 		msg_info.hdr.serializing_sc = NULL;
1921 		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1922 #if 0
1923 		printf("BAD JUJU:Major Bummer Overlap\n");
1924 #endif
1925 		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1926 		retval = 1;
1927 		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1928 		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1929 		}
1930 		break;
1931 	case CTL_ACTION_OVERLAP_TAG:
1932 		/* TAGGED OVERLAPPED COMMANDS (NN = QUEUE TAG) */
1933 		ctl_set_sense_data(&msg_info.scsi.sense_data,
1934 				   lun,
1935 				   /*sense_format*/SSD_TYPE_NONE,
1936 				   /*current_error*/ 1,
1937 				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1938 				   /*asc*/ 0x4D,
1939 				   /*ascq*/ ctsio->tag_num & 0xff,
1940 				   SSD_ELEM_NONE);
1941 
1942 		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1943 		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1944 		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1945 		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1946 		msg_info.hdr.serializing_sc = NULL;
1947 		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1948 #if 0
1949 		printf("BAD JUJU:Major Bummer Overlap Tag\n");
1950 #endif
1951 		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1952 		retval = 1;
1953 		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1954 		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1955 		}
1956 		break;
1957 	case CTL_ACTION_ERROR:
1958 	default:
1959 		/* "Internal target failure" */
1960 		ctl_set_sense_data(&msg_info.scsi.sense_data,
1961 				   lun,
1962 				   /*sense_format*/SSD_TYPE_NONE,
1963 				   /*current_error*/ 1,
1964 				   /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
1965 				   /*asc*/ 0x44,
1966 				   /*ascq*/ 0x00,
1967 				   SSD_ELEM_NONE);
1968 
1969 		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1970 		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1971 		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1972 		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1973 		msg_info.hdr.serializing_sc = NULL;
1974 		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1975 #if 0
1976 		printf("BAD JUJU:Major Bummer HW Error\n");
1977 #endif
1978 		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1979 		retval = 1;
1980 		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1981 		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1982 		}
1983 		break;
1984 	}
1985 	mtx_unlock(&lun->lun_lock);
1986 	return (retval);
1987 }
1988 
1989 static int
1990 ctl_ioctl_submit_wait(union ctl_io *io)
1991 {
1992 	struct ctl_fe_ioctl_params params;
1993 	ctl_fe_ioctl_state last_state;
1994 	int done, retval;
1995 
1996 	retval = 0;
1997 
1998 	bzero(&params, sizeof(params));
1999 
2000 	mtx_init(&params.ioctl_mtx, "ctliocmtx", NULL, MTX_DEF);
2001 	cv_init(&params.sem, "ctlioccv");
2002 	params.state = CTL_IOCTL_INPROG;
2003 	last_state = params.state;
2004 
2005 	io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr = &params;
2006 
2007 	CTL_DEBUG_PRINT(("ctl_ioctl_submit_wait\n"));
2008 
2009 	/* This shouldn't happen */
2010 	if ((retval = ctl_queue(io)) != CTL_RETVAL_COMPLETE)
2011 		return (retval);
2012 
2013 	done = 0;
2014 
2015 	do {
2016 		mtx_lock(&params.ioctl_mtx);
2017 		/*
2018 		 * Check the state here, and don't sleep if the state has
2019 		 * already changed (i.e. wakeup has already occured, but we
2020 		 * weren't waiting yet).
2021 		 */
2022 		if (params.state == last_state) {
2023 			/* XXX KDM cv_wait_sig instead? */
2024 			cv_wait(&params.sem, &params.ioctl_mtx);
2025 		}
2026 		last_state = params.state;
2027 
2028 		switch (params.state) {
2029 		case CTL_IOCTL_INPROG:
2030 			/* Why did we wake up? */
2031 			/* XXX KDM error here? */
2032 			mtx_unlock(&params.ioctl_mtx);
2033 			break;
2034 		case CTL_IOCTL_DATAMOVE:
2035 			CTL_DEBUG_PRINT(("got CTL_IOCTL_DATAMOVE\n"));
2036 
2037 			/*
2038 			 * change last_state back to INPROG to avoid
2039 			 * deadlock on subsequent data moves.
2040 			 */
2041 			params.state = last_state = CTL_IOCTL_INPROG;
2042 
2043 			mtx_unlock(&params.ioctl_mtx);
2044 			ctl_ioctl_do_datamove(&io->scsiio);
2045 			/*
2046 			 * Note that in some cases, most notably writes,
2047 			 * this will queue the I/O and call us back later.
2048 			 * In other cases, generally reads, this routine
2049 			 * will immediately call back and wake us up,
2050 			 * probably using our own context.
2051 			 */
2052 			io->scsiio.be_move_done(io);
2053 			break;
2054 		case CTL_IOCTL_DONE:
2055 			mtx_unlock(&params.ioctl_mtx);
2056 			CTL_DEBUG_PRINT(("got CTL_IOCTL_DONE\n"));
2057 			done = 1;
2058 			break;
2059 		default:
2060 			mtx_unlock(&params.ioctl_mtx);
2061 			/* XXX KDM error here? */
2062 			break;
2063 		}
2064 	} while (done == 0);
2065 
2066 	mtx_destroy(&params.ioctl_mtx);
2067 	cv_destroy(&params.sem);
2068 
2069 	return (CTL_RETVAL_COMPLETE);
2070 }
2071 
2072 static void
2073 ctl_ioctl_datamove(union ctl_io *io)
2074 {
2075 	struct ctl_fe_ioctl_params *params;
2076 
2077 	params = (struct ctl_fe_ioctl_params *)
2078 		io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2079 
2080 	mtx_lock(&params->ioctl_mtx);
2081 	params->state = CTL_IOCTL_DATAMOVE;
2082 	cv_broadcast(&params->sem);
2083 	mtx_unlock(&params->ioctl_mtx);
2084 }
2085 
2086 static void
2087 ctl_ioctl_done(union ctl_io *io)
2088 {
2089 	struct ctl_fe_ioctl_params *params;
2090 
2091 	params = (struct ctl_fe_ioctl_params *)
2092 		io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2093 
2094 	mtx_lock(&params->ioctl_mtx);
2095 	params->state = CTL_IOCTL_DONE;
2096 	cv_broadcast(&params->sem);
2097 	mtx_unlock(&params->ioctl_mtx);
2098 }
2099 
2100 static void
2101 ctl_ioctl_hard_startstop_callback(void *arg, struct cfi_metatask *metatask)
2102 {
2103 	struct ctl_fe_ioctl_startstop_info *sd_info;
2104 
2105 	sd_info = (struct ctl_fe_ioctl_startstop_info *)arg;
2106 
2107 	sd_info->hs_info.status = metatask->status;
2108 	sd_info->hs_info.total_luns = metatask->taskinfo.startstop.total_luns;
2109 	sd_info->hs_info.luns_complete =
2110 		metatask->taskinfo.startstop.luns_complete;
2111 	sd_info->hs_info.luns_failed = metatask->taskinfo.startstop.luns_failed;
2112 
2113 	cv_broadcast(&sd_info->sem);
2114 }
2115 
2116 static void
2117 ctl_ioctl_bbrread_callback(void *arg, struct cfi_metatask *metatask)
2118 {
2119 	struct ctl_fe_ioctl_bbrread_info *fe_bbr_info;
2120 
2121 	fe_bbr_info = (struct ctl_fe_ioctl_bbrread_info *)arg;
2122 
2123 	mtx_lock(fe_bbr_info->lock);
2124 	fe_bbr_info->bbr_info->status = metatask->status;
2125 	fe_bbr_info->bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2126 	fe_bbr_info->wakeup_done = 1;
2127 	mtx_unlock(fe_bbr_info->lock);
2128 
2129 	cv_broadcast(&fe_bbr_info->sem);
2130 }
2131 
2132 /*
2133  * Returns 0 for success, errno for failure.
2134  */
2135 static int
2136 ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2137 		   struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2138 {
2139 	union ctl_io *io;
2140 	int retval;
2141 
2142 	retval = 0;
2143 
2144 	mtx_lock(&lun->lun_lock);
2145 	for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
2146 	     (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2147 	     ooa_links)) {
2148 		struct ctl_ooa_entry *entry;
2149 
2150 		/*
2151 		 * If we've got more than we can fit, just count the
2152 		 * remaining entries.
2153 		 */
2154 		if (*cur_fill_num >= ooa_hdr->alloc_num)
2155 			continue;
2156 
2157 		entry = &kern_entries[*cur_fill_num];
2158 
2159 		entry->tag_num = io->scsiio.tag_num;
2160 		entry->lun_num = lun->lun;
2161 #ifdef CTL_TIME_IO
2162 		entry->start_bt = io->io_hdr.start_bt;
2163 #endif
2164 		bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2165 		entry->cdb_len = io->scsiio.cdb_len;
2166 		if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
2167 			entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2168 
2169 		if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2170 			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2171 
2172 		if (io->io_hdr.flags & CTL_FLAG_ABORT)
2173 			entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2174 
2175 		if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2176 			entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2177 
2178 		if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2179 			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2180 	}
2181 	mtx_unlock(&lun->lun_lock);
2182 
2183 	return (retval);
2184 }
2185 
2186 static void *
2187 ctl_copyin_alloc(void *user_addr, int len, char *error_str,
2188 		 size_t error_str_len)
2189 {
2190 	void *kptr;
2191 
2192 	kptr = malloc(len, M_CTL, M_WAITOK | M_ZERO);
2193 
2194 	if (copyin(user_addr, kptr, len) != 0) {
2195 		snprintf(error_str, error_str_len, "Error copying %d bytes "
2196 			 "from user address %p to kernel address %p", len,
2197 			 user_addr, kptr);
2198 		free(kptr, M_CTL);
2199 		return (NULL);
2200 	}
2201 
2202 	return (kptr);
2203 }
2204 
2205 static void
2206 ctl_free_args(int num_args, struct ctl_be_arg *args)
2207 {
2208 	int i;
2209 
2210 	if (args == NULL)
2211 		return;
2212 
2213 	for (i = 0; i < num_args; i++) {
2214 		free(args[i].kname, M_CTL);
2215 		free(args[i].kvalue, M_CTL);
2216 	}
2217 
2218 	free(args, M_CTL);
2219 }
2220 
2221 static struct ctl_be_arg *
2222 ctl_copyin_args(int num_args, struct ctl_be_arg *uargs,
2223 		char *error_str, size_t error_str_len)
2224 {
2225 	struct ctl_be_arg *args;
2226 	int i;
2227 
2228 	args = ctl_copyin_alloc(uargs, num_args * sizeof(*args),
2229 				error_str, error_str_len);
2230 
2231 	if (args == NULL)
2232 		goto bailout;
2233 
2234 	for (i = 0; i < num_args; i++) {
2235 		args[i].kname = NULL;
2236 		args[i].kvalue = NULL;
2237 	}
2238 
2239 	for (i = 0; i < num_args; i++) {
2240 		uint8_t *tmpptr;
2241 
2242 		args[i].kname = ctl_copyin_alloc(args[i].name,
2243 			args[i].namelen, error_str, error_str_len);
2244 		if (args[i].kname == NULL)
2245 			goto bailout;
2246 
2247 		if (args[i].kname[args[i].namelen - 1] != '\0') {
2248 			snprintf(error_str, error_str_len, "Argument %d "
2249 				 "name is not NUL-terminated", i);
2250 			goto bailout;
2251 		}
2252 
2253 		if (args[i].flags & CTL_BEARG_RD) {
2254 			tmpptr = ctl_copyin_alloc(args[i].value,
2255 				args[i].vallen, error_str, error_str_len);
2256 			if (tmpptr == NULL)
2257 				goto bailout;
2258 			if ((args[i].flags & CTL_BEARG_ASCII)
2259 			 && (tmpptr[args[i].vallen - 1] != '\0')) {
2260 				snprintf(error_str, error_str_len, "Argument "
2261 				    "%d value is not NUL-terminated", i);
2262 				goto bailout;
2263 			}
2264 			args[i].kvalue = tmpptr;
2265 		} else {
2266 			args[i].kvalue = malloc(args[i].vallen,
2267 			    M_CTL, M_WAITOK | M_ZERO);
2268 		}
2269 	}
2270 
2271 	return (args);
2272 bailout:
2273 
2274 	ctl_free_args(num_args, args);
2275 
2276 	return (NULL);
2277 }
2278 
2279 static void
2280 ctl_copyout_args(int num_args, struct ctl_be_arg *args)
2281 {
2282 	int i;
2283 
2284 	for (i = 0; i < num_args; i++) {
2285 		if (args[i].flags & CTL_BEARG_WR)
2286 			copyout(args[i].kvalue, args[i].value, args[i].vallen);
2287 	}
2288 }
2289 
2290 /*
2291  * Escape characters that are illegal or not recommended in XML.
2292  */
2293 int
2294 ctl_sbuf_printf_esc(struct sbuf *sb, char *str, int size)
2295 {
2296 	char *end = str + size;
2297 	int retval;
2298 
2299 	retval = 0;
2300 
2301 	for (; *str && str < end; str++) {
2302 		switch (*str) {
2303 		case '&':
2304 			retval = sbuf_printf(sb, "&amp;");
2305 			break;
2306 		case '>':
2307 			retval = sbuf_printf(sb, "&gt;");
2308 			break;
2309 		case '<':
2310 			retval = sbuf_printf(sb, "&lt;");
2311 			break;
2312 		default:
2313 			retval = sbuf_putc(sb, *str);
2314 			break;
2315 		}
2316 
2317 		if (retval != 0)
2318 			break;
2319 
2320 	}
2321 
2322 	return (retval);
2323 }
2324 
2325 static void
2326 ctl_id_sbuf(struct ctl_devid *id, struct sbuf *sb)
2327 {
2328 	struct scsi_vpd_id_descriptor *desc;
2329 	int i;
2330 
2331 	if (id == NULL || id->len < 4)
2332 		return;
2333 	desc = (struct scsi_vpd_id_descriptor *)id->data;
2334 	switch (desc->id_type & SVPD_ID_TYPE_MASK) {
2335 	case SVPD_ID_TYPE_T10:
2336 		sbuf_printf(sb, "t10.");
2337 		break;
2338 	case SVPD_ID_TYPE_EUI64:
2339 		sbuf_printf(sb, "eui.");
2340 		break;
2341 	case SVPD_ID_TYPE_NAA:
2342 		sbuf_printf(sb, "naa.");
2343 		break;
2344 	case SVPD_ID_TYPE_SCSI_NAME:
2345 		break;
2346 	}
2347 	switch (desc->proto_codeset & SVPD_ID_CODESET_MASK) {
2348 	case SVPD_ID_CODESET_BINARY:
2349 		for (i = 0; i < desc->length; i++)
2350 			sbuf_printf(sb, "%02x", desc->identifier[i]);
2351 		break;
2352 	case SVPD_ID_CODESET_ASCII:
2353 		sbuf_printf(sb, "%.*s", (int)desc->length,
2354 		    (char *)desc->identifier);
2355 		break;
2356 	case SVPD_ID_CODESET_UTF8:
2357 		sbuf_printf(sb, "%s", (char *)desc->identifier);
2358 		break;
2359 	}
2360 }
2361 
2362 static int
2363 ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2364 	  struct thread *td)
2365 {
2366 	struct ctl_softc *softc;
2367 	int retval;
2368 
2369 	softc = control_softc;
2370 
2371 	retval = 0;
2372 
2373 	switch (cmd) {
2374 	case CTL_IO: {
2375 		union ctl_io *io;
2376 		void *pool_tmp;
2377 
2378 		/*
2379 		 * If we haven't been "enabled", don't allow any SCSI I/O
2380 		 * to this FETD.
2381 		 */
2382 		if ((softc->ioctl_info.flags & CTL_IOCTL_FLAG_ENABLED) == 0) {
2383 			retval = EPERM;
2384 			break;
2385 		}
2386 
2387 		io = ctl_alloc_io(softc->ioctl_info.port.ctl_pool_ref);
2388 
2389 		/*
2390 		 * Need to save the pool reference so it doesn't get
2391 		 * spammed by the user's ctl_io.
2392 		 */
2393 		pool_tmp = io->io_hdr.pool;
2394 		memcpy(io, (void *)addr, sizeof(*io));
2395 		io->io_hdr.pool = pool_tmp;
2396 
2397 		/*
2398 		 * No status yet, so make sure the status is set properly.
2399 		 */
2400 		io->io_hdr.status = CTL_STATUS_NONE;
2401 
2402 		/*
2403 		 * The user sets the initiator ID, target and LUN IDs.
2404 		 */
2405 		io->io_hdr.nexus.targ_port = softc->ioctl_info.port.targ_port;
2406 		io->io_hdr.flags |= CTL_FLAG_USER_REQ;
2407 		if ((io->io_hdr.io_type == CTL_IO_SCSI)
2408 		 && (io->scsiio.tag_type != CTL_TAG_UNTAGGED))
2409 			io->scsiio.tag_num = softc->ioctl_info.cur_tag_num++;
2410 
2411 		retval = ctl_ioctl_submit_wait(io);
2412 
2413 		if (retval != 0) {
2414 			ctl_free_io(io);
2415 			break;
2416 		}
2417 
2418 		memcpy((void *)addr, io, sizeof(*io));
2419 
2420 		/* return this to our pool */
2421 		ctl_free_io(io);
2422 
2423 		break;
2424 	}
2425 	case CTL_ENABLE_PORT:
2426 	case CTL_DISABLE_PORT:
2427 	case CTL_SET_PORT_WWNS: {
2428 		struct ctl_port *port;
2429 		struct ctl_port_entry *entry;
2430 
2431 		entry = (struct ctl_port_entry *)addr;
2432 
2433 		mtx_lock(&softc->ctl_lock);
2434 		STAILQ_FOREACH(port, &softc->port_list, links) {
2435 			int action, done;
2436 
2437 			action = 0;
2438 			done = 0;
2439 
2440 			if ((entry->port_type == CTL_PORT_NONE)
2441 			 && (entry->targ_port == port->targ_port)) {
2442 				/*
2443 				 * If the user only wants to enable or
2444 				 * disable or set WWNs on a specific port,
2445 				 * do the operation and we're done.
2446 				 */
2447 				action = 1;
2448 				done = 1;
2449 			} else if (entry->port_type & port->port_type) {
2450 				/*
2451 				 * Compare the user's type mask with the
2452 				 * particular frontend type to see if we
2453 				 * have a match.
2454 				 */
2455 				action = 1;
2456 				done = 0;
2457 
2458 				/*
2459 				 * Make sure the user isn't trying to set
2460 				 * WWNs on multiple ports at the same time.
2461 				 */
2462 				if (cmd == CTL_SET_PORT_WWNS) {
2463 					printf("%s: Can't set WWNs on "
2464 					       "multiple ports\n", __func__);
2465 					retval = EINVAL;
2466 					break;
2467 				}
2468 			}
2469 			if (action != 0) {
2470 				/*
2471 				 * XXX KDM we have to drop the lock here,
2472 				 * because the online/offline operations
2473 				 * can potentially block.  We need to
2474 				 * reference count the frontends so they
2475 				 * can't go away,
2476 				 */
2477 				mtx_unlock(&softc->ctl_lock);
2478 
2479 				if (cmd == CTL_ENABLE_PORT) {
2480 					struct ctl_lun *lun;
2481 
2482 					STAILQ_FOREACH(lun, &softc->lun_list,
2483 						       links) {
2484 						port->lun_enable(port->targ_lun_arg,
2485 						    lun->target,
2486 						    lun->lun);
2487 					}
2488 
2489 					ctl_port_online(port);
2490 				} else if (cmd == CTL_DISABLE_PORT) {
2491 					struct ctl_lun *lun;
2492 
2493 					ctl_port_offline(port);
2494 
2495 					STAILQ_FOREACH(lun, &softc->lun_list,
2496 						       links) {
2497 						port->lun_disable(
2498 						    port->targ_lun_arg,
2499 						    lun->target,
2500 						    lun->lun);
2501 					}
2502 				}
2503 
2504 				mtx_lock(&softc->ctl_lock);
2505 
2506 				if (cmd == CTL_SET_PORT_WWNS)
2507 					ctl_port_set_wwns(port,
2508 					    (entry->flags & CTL_PORT_WWNN_VALID) ?
2509 					    1 : 0, entry->wwnn,
2510 					    (entry->flags & CTL_PORT_WWPN_VALID) ?
2511 					    1 : 0, entry->wwpn);
2512 			}
2513 			if (done != 0)
2514 				break;
2515 		}
2516 		mtx_unlock(&softc->ctl_lock);
2517 		break;
2518 	}
2519 	case CTL_GET_PORT_LIST: {
2520 		struct ctl_port *port;
2521 		struct ctl_port_list *list;
2522 		int i;
2523 
2524 		list = (struct ctl_port_list *)addr;
2525 
2526 		if (list->alloc_len != (list->alloc_num *
2527 		    sizeof(struct ctl_port_entry))) {
2528 			printf("%s: CTL_GET_PORT_LIST: alloc_len %u != "
2529 			       "alloc_num %u * sizeof(struct ctl_port_entry) "
2530 			       "%zu\n", __func__, list->alloc_len,
2531 			       list->alloc_num, sizeof(struct ctl_port_entry));
2532 			retval = EINVAL;
2533 			break;
2534 		}
2535 		list->fill_len = 0;
2536 		list->fill_num = 0;
2537 		list->dropped_num = 0;
2538 		i = 0;
2539 		mtx_lock(&softc->ctl_lock);
2540 		STAILQ_FOREACH(port, &softc->port_list, links) {
2541 			struct ctl_port_entry entry, *list_entry;
2542 
2543 			if (list->fill_num >= list->alloc_num) {
2544 				list->dropped_num++;
2545 				continue;
2546 			}
2547 
2548 			entry.port_type = port->port_type;
2549 			strlcpy(entry.port_name, port->port_name,
2550 				sizeof(entry.port_name));
2551 			entry.targ_port = port->targ_port;
2552 			entry.physical_port = port->physical_port;
2553 			entry.virtual_port = port->virtual_port;
2554 			entry.wwnn = port->wwnn;
2555 			entry.wwpn = port->wwpn;
2556 			if (port->status & CTL_PORT_STATUS_ONLINE)
2557 				entry.online = 1;
2558 			else
2559 				entry.online = 0;
2560 
2561 			list_entry = &list->entries[i];
2562 
2563 			retval = copyout(&entry, list_entry, sizeof(entry));
2564 			if (retval != 0) {
2565 				printf("%s: CTL_GET_PORT_LIST: copyout "
2566 				       "returned %d\n", __func__, retval);
2567 				break;
2568 			}
2569 			i++;
2570 			list->fill_num++;
2571 			list->fill_len += sizeof(entry);
2572 		}
2573 		mtx_unlock(&softc->ctl_lock);
2574 
2575 		/*
2576 		 * If this is non-zero, we had a copyout fault, so there's
2577 		 * probably no point in attempting to set the status inside
2578 		 * the structure.
2579 		 */
2580 		if (retval != 0)
2581 			break;
2582 
2583 		if (list->dropped_num > 0)
2584 			list->status = CTL_PORT_LIST_NEED_MORE_SPACE;
2585 		else
2586 			list->status = CTL_PORT_LIST_OK;
2587 		break;
2588 	}
2589 	case CTL_DUMP_OOA: {
2590 		struct ctl_lun *lun;
2591 		union ctl_io *io;
2592 		char printbuf[128];
2593 		struct sbuf sb;
2594 
2595 		mtx_lock(&softc->ctl_lock);
2596 		printf("Dumping OOA queues:\n");
2597 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
2598 			mtx_lock(&lun->lun_lock);
2599 			for (io = (union ctl_io *)TAILQ_FIRST(
2600 			     &lun->ooa_queue); io != NULL;
2601 			     io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2602 			     ooa_links)) {
2603 				sbuf_new(&sb, printbuf, sizeof(printbuf),
2604 					 SBUF_FIXEDLEN);
2605 				sbuf_printf(&sb, "LUN %jd tag 0x%04x%s%s%s%s: ",
2606 					    (intmax_t)lun->lun,
2607 					    io->scsiio.tag_num,
2608 					    (io->io_hdr.flags &
2609 					    CTL_FLAG_BLOCKED) ? "" : " BLOCKED",
2610 					    (io->io_hdr.flags &
2611 					    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
2612 					    (io->io_hdr.flags &
2613 					    CTL_FLAG_ABORT) ? " ABORT" : "",
2614 			                    (io->io_hdr.flags &
2615 		                        CTL_FLAG_IS_WAS_ON_RTR) ? " RTR" : "");
2616 				ctl_scsi_command_string(&io->scsiio, NULL, &sb);
2617 				sbuf_finish(&sb);
2618 				printf("%s\n", sbuf_data(&sb));
2619 			}
2620 			mtx_unlock(&lun->lun_lock);
2621 		}
2622 		printf("OOA queues dump done\n");
2623 		mtx_unlock(&softc->ctl_lock);
2624 		break;
2625 	}
2626 	case CTL_GET_OOA: {
2627 		struct ctl_lun *lun;
2628 		struct ctl_ooa *ooa_hdr;
2629 		struct ctl_ooa_entry *entries;
2630 		uint32_t cur_fill_num;
2631 
2632 		ooa_hdr = (struct ctl_ooa *)addr;
2633 
2634 		if ((ooa_hdr->alloc_len == 0)
2635 		 || (ooa_hdr->alloc_num == 0)) {
2636 			printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2637 			       "must be non-zero\n", __func__,
2638 			       ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2639 			retval = EINVAL;
2640 			break;
2641 		}
2642 
2643 		if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2644 		    sizeof(struct ctl_ooa_entry))) {
2645 			printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2646 			       "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2647 			       __func__, ooa_hdr->alloc_len,
2648 			       ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2649 			retval = EINVAL;
2650 			break;
2651 		}
2652 
2653 		entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2654 		if (entries == NULL) {
2655 			printf("%s: could not allocate %d bytes for OOA "
2656 			       "dump\n", __func__, ooa_hdr->alloc_len);
2657 			retval = ENOMEM;
2658 			break;
2659 		}
2660 
2661 		mtx_lock(&softc->ctl_lock);
2662 		if (((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0)
2663 		 && ((ooa_hdr->lun_num >= CTL_MAX_LUNS)
2664 		  || (softc->ctl_luns[ooa_hdr->lun_num] == NULL))) {
2665 			mtx_unlock(&softc->ctl_lock);
2666 			free(entries, M_CTL);
2667 			printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2668 			       __func__, (uintmax_t)ooa_hdr->lun_num);
2669 			retval = EINVAL;
2670 			break;
2671 		}
2672 
2673 		cur_fill_num = 0;
2674 
2675 		if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2676 			STAILQ_FOREACH(lun, &softc->lun_list, links) {
2677 				retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2678 					ooa_hdr, entries);
2679 				if (retval != 0)
2680 					break;
2681 			}
2682 			if (retval != 0) {
2683 				mtx_unlock(&softc->ctl_lock);
2684 				free(entries, M_CTL);
2685 				break;
2686 			}
2687 		} else {
2688 			lun = softc->ctl_luns[ooa_hdr->lun_num];
2689 
2690 			retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,ooa_hdr,
2691 						    entries);
2692 		}
2693 		mtx_unlock(&softc->ctl_lock);
2694 
2695 		ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2696 		ooa_hdr->fill_len = ooa_hdr->fill_num *
2697 			sizeof(struct ctl_ooa_entry);
2698 		retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2699 		if (retval != 0) {
2700 			printf("%s: error copying out %d bytes for OOA dump\n",
2701 			       __func__, ooa_hdr->fill_len);
2702 		}
2703 
2704 		getbintime(&ooa_hdr->cur_bt);
2705 
2706 		if (cur_fill_num > ooa_hdr->alloc_num) {
2707 			ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2708 			ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2709 		} else {
2710 			ooa_hdr->dropped_num = 0;
2711 			ooa_hdr->status = CTL_OOA_OK;
2712 		}
2713 
2714 		free(entries, M_CTL);
2715 		break;
2716 	}
2717 	case CTL_CHECK_OOA: {
2718 		union ctl_io *io;
2719 		struct ctl_lun *lun;
2720 		struct ctl_ooa_info *ooa_info;
2721 
2722 
2723 		ooa_info = (struct ctl_ooa_info *)addr;
2724 
2725 		if (ooa_info->lun_id >= CTL_MAX_LUNS) {
2726 			ooa_info->status = CTL_OOA_INVALID_LUN;
2727 			break;
2728 		}
2729 		mtx_lock(&softc->ctl_lock);
2730 		lun = softc->ctl_luns[ooa_info->lun_id];
2731 		if (lun == NULL) {
2732 			mtx_unlock(&softc->ctl_lock);
2733 			ooa_info->status = CTL_OOA_INVALID_LUN;
2734 			break;
2735 		}
2736 		mtx_lock(&lun->lun_lock);
2737 		mtx_unlock(&softc->ctl_lock);
2738 		ooa_info->num_entries = 0;
2739 		for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
2740 		     io != NULL; io = (union ctl_io *)TAILQ_NEXT(
2741 		     &io->io_hdr, ooa_links)) {
2742 			ooa_info->num_entries++;
2743 		}
2744 		mtx_unlock(&lun->lun_lock);
2745 
2746 		ooa_info->status = CTL_OOA_SUCCESS;
2747 
2748 		break;
2749 	}
2750 	case CTL_HARD_START:
2751 	case CTL_HARD_STOP: {
2752 		struct ctl_fe_ioctl_startstop_info ss_info;
2753 		struct cfi_metatask *metatask;
2754 		struct mtx hs_mtx;
2755 
2756 		mtx_init(&hs_mtx, "HS Mutex", NULL, MTX_DEF);
2757 
2758 		cv_init(&ss_info.sem, "hard start/stop cv" );
2759 
2760 		metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2761 		if (metatask == NULL) {
2762 			retval = ENOMEM;
2763 			mtx_destroy(&hs_mtx);
2764 			break;
2765 		}
2766 
2767 		if (cmd == CTL_HARD_START)
2768 			metatask->tasktype = CFI_TASK_STARTUP;
2769 		else
2770 			metatask->tasktype = CFI_TASK_SHUTDOWN;
2771 
2772 		metatask->callback = ctl_ioctl_hard_startstop_callback;
2773 		metatask->callback_arg = &ss_info;
2774 
2775 		cfi_action(metatask);
2776 
2777 		/* Wait for the callback */
2778 		mtx_lock(&hs_mtx);
2779 		cv_wait_sig(&ss_info.sem, &hs_mtx);
2780 		mtx_unlock(&hs_mtx);
2781 
2782 		/*
2783 		 * All information has been copied from the metatask by the
2784 		 * time cv_broadcast() is called, so we free the metatask here.
2785 		 */
2786 		cfi_free_metatask(metatask);
2787 
2788 		memcpy((void *)addr, &ss_info.hs_info, sizeof(ss_info.hs_info));
2789 
2790 		mtx_destroy(&hs_mtx);
2791 		break;
2792 	}
2793 	case CTL_BBRREAD: {
2794 		struct ctl_bbrread_info *bbr_info;
2795 		struct ctl_fe_ioctl_bbrread_info fe_bbr_info;
2796 		struct mtx bbr_mtx;
2797 		struct cfi_metatask *metatask;
2798 
2799 		bbr_info = (struct ctl_bbrread_info *)addr;
2800 
2801 		bzero(&fe_bbr_info, sizeof(fe_bbr_info));
2802 
2803 		bzero(&bbr_mtx, sizeof(bbr_mtx));
2804 		mtx_init(&bbr_mtx, "BBR Mutex", NULL, MTX_DEF);
2805 
2806 		fe_bbr_info.bbr_info = bbr_info;
2807 		fe_bbr_info.lock = &bbr_mtx;
2808 
2809 		cv_init(&fe_bbr_info.sem, "BBR read cv");
2810 		metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2811 
2812 		if (metatask == NULL) {
2813 			mtx_destroy(&bbr_mtx);
2814 			cv_destroy(&fe_bbr_info.sem);
2815 			retval = ENOMEM;
2816 			break;
2817 		}
2818 		metatask->tasktype = CFI_TASK_BBRREAD;
2819 		metatask->callback = ctl_ioctl_bbrread_callback;
2820 		metatask->callback_arg = &fe_bbr_info;
2821 		metatask->taskinfo.bbrread.lun_num = bbr_info->lun_num;
2822 		metatask->taskinfo.bbrread.lba = bbr_info->lba;
2823 		metatask->taskinfo.bbrread.len = bbr_info->len;
2824 
2825 		cfi_action(metatask);
2826 
2827 		mtx_lock(&bbr_mtx);
2828 		while (fe_bbr_info.wakeup_done == 0)
2829 			cv_wait_sig(&fe_bbr_info.sem, &bbr_mtx);
2830 		mtx_unlock(&bbr_mtx);
2831 
2832 		bbr_info->status = metatask->status;
2833 		bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2834 		bbr_info->scsi_status = metatask->taskinfo.bbrread.scsi_status;
2835 		memcpy(&bbr_info->sense_data,
2836 		       &metatask->taskinfo.bbrread.sense_data,
2837 		       MIN(sizeof(bbr_info->sense_data),
2838 			   sizeof(metatask->taskinfo.bbrread.sense_data)));
2839 
2840 		cfi_free_metatask(metatask);
2841 
2842 		mtx_destroy(&bbr_mtx);
2843 		cv_destroy(&fe_bbr_info.sem);
2844 
2845 		break;
2846 	}
2847 	case CTL_DELAY_IO: {
2848 		struct ctl_io_delay_info *delay_info;
2849 #ifdef CTL_IO_DELAY
2850 		struct ctl_lun *lun;
2851 #endif /* CTL_IO_DELAY */
2852 
2853 		delay_info = (struct ctl_io_delay_info *)addr;
2854 
2855 #ifdef CTL_IO_DELAY
2856 		mtx_lock(&softc->ctl_lock);
2857 
2858 		if ((delay_info->lun_id >= CTL_MAX_LUNS)
2859 		 || (softc->ctl_luns[delay_info->lun_id] == NULL)) {
2860 			delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2861 		} else {
2862 			lun = softc->ctl_luns[delay_info->lun_id];
2863 			mtx_lock(&lun->lun_lock);
2864 
2865 			delay_info->status = CTL_DELAY_STATUS_OK;
2866 
2867 			switch (delay_info->delay_type) {
2868 			case CTL_DELAY_TYPE_CONT:
2869 				break;
2870 			case CTL_DELAY_TYPE_ONESHOT:
2871 				break;
2872 			default:
2873 				delay_info->status =
2874 					CTL_DELAY_STATUS_INVALID_TYPE;
2875 				break;
2876 			}
2877 
2878 			switch (delay_info->delay_loc) {
2879 			case CTL_DELAY_LOC_DATAMOVE:
2880 				lun->delay_info.datamove_type =
2881 					delay_info->delay_type;
2882 				lun->delay_info.datamove_delay =
2883 					delay_info->delay_secs;
2884 				break;
2885 			case CTL_DELAY_LOC_DONE:
2886 				lun->delay_info.done_type =
2887 					delay_info->delay_type;
2888 				lun->delay_info.done_delay =
2889 					delay_info->delay_secs;
2890 				break;
2891 			default:
2892 				delay_info->status =
2893 					CTL_DELAY_STATUS_INVALID_LOC;
2894 				break;
2895 			}
2896 			mtx_unlock(&lun->lun_lock);
2897 		}
2898 
2899 		mtx_unlock(&softc->ctl_lock);
2900 #else
2901 		delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2902 #endif /* CTL_IO_DELAY */
2903 		break;
2904 	}
2905 	case CTL_REALSYNC_SET: {
2906 		int *syncstate;
2907 
2908 		syncstate = (int *)addr;
2909 
2910 		mtx_lock(&softc->ctl_lock);
2911 		switch (*syncstate) {
2912 		case 0:
2913 			softc->flags &= ~CTL_FLAG_REAL_SYNC;
2914 			break;
2915 		case 1:
2916 			softc->flags |= CTL_FLAG_REAL_SYNC;
2917 			break;
2918 		default:
2919 			retval = EINVAL;
2920 			break;
2921 		}
2922 		mtx_unlock(&softc->ctl_lock);
2923 		break;
2924 	}
2925 	case CTL_REALSYNC_GET: {
2926 		int *syncstate;
2927 
2928 		syncstate = (int*)addr;
2929 
2930 		mtx_lock(&softc->ctl_lock);
2931 		if (softc->flags & CTL_FLAG_REAL_SYNC)
2932 			*syncstate = 1;
2933 		else
2934 			*syncstate = 0;
2935 		mtx_unlock(&softc->ctl_lock);
2936 
2937 		break;
2938 	}
2939 	case CTL_SETSYNC:
2940 	case CTL_GETSYNC: {
2941 		struct ctl_sync_info *sync_info;
2942 		struct ctl_lun *lun;
2943 
2944 		sync_info = (struct ctl_sync_info *)addr;
2945 
2946 		mtx_lock(&softc->ctl_lock);
2947 		lun = softc->ctl_luns[sync_info->lun_id];
2948 		if (lun == NULL) {
2949 			mtx_unlock(&softc->ctl_lock);
2950 			sync_info->status = CTL_GS_SYNC_NO_LUN;
2951 		}
2952 		/*
2953 		 * Get or set the sync interval.  We're not bounds checking
2954 		 * in the set case, hopefully the user won't do something
2955 		 * silly.
2956 		 */
2957 		mtx_lock(&lun->lun_lock);
2958 		mtx_unlock(&softc->ctl_lock);
2959 		if (cmd == CTL_GETSYNC)
2960 			sync_info->sync_interval = lun->sync_interval;
2961 		else
2962 			lun->sync_interval = sync_info->sync_interval;
2963 		mtx_unlock(&lun->lun_lock);
2964 
2965 		sync_info->status = CTL_GS_SYNC_OK;
2966 
2967 		break;
2968 	}
2969 	case CTL_GETSTATS: {
2970 		struct ctl_stats *stats;
2971 		struct ctl_lun *lun;
2972 		int i;
2973 
2974 		stats = (struct ctl_stats *)addr;
2975 
2976 		if ((sizeof(struct ctl_lun_io_stats) * softc->num_luns) >
2977 		     stats->alloc_len) {
2978 			stats->status = CTL_SS_NEED_MORE_SPACE;
2979 			stats->num_luns = softc->num_luns;
2980 			break;
2981 		}
2982 		/*
2983 		 * XXX KDM no locking here.  If the LUN list changes,
2984 		 * things can blow up.
2985 		 */
2986 		for (i = 0, lun = STAILQ_FIRST(&softc->lun_list); lun != NULL;
2987 		     i++, lun = STAILQ_NEXT(lun, links)) {
2988 			retval = copyout(&lun->stats, &stats->lun_stats[i],
2989 					 sizeof(lun->stats));
2990 			if (retval != 0)
2991 				break;
2992 		}
2993 		stats->num_luns = softc->num_luns;
2994 		stats->fill_len = sizeof(struct ctl_lun_io_stats) *
2995 				 softc->num_luns;
2996 		stats->status = CTL_SS_OK;
2997 #ifdef CTL_TIME_IO
2998 		stats->flags = CTL_STATS_FLAG_TIME_VALID;
2999 #else
3000 		stats->flags = CTL_STATS_FLAG_NONE;
3001 #endif
3002 		getnanouptime(&stats->timestamp);
3003 		break;
3004 	}
3005 	case CTL_ERROR_INJECT: {
3006 		struct ctl_error_desc *err_desc, *new_err_desc;
3007 		struct ctl_lun *lun;
3008 
3009 		err_desc = (struct ctl_error_desc *)addr;
3010 
3011 		new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
3012 				      M_WAITOK | M_ZERO);
3013 		bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
3014 
3015 		mtx_lock(&softc->ctl_lock);
3016 		lun = softc->ctl_luns[err_desc->lun_id];
3017 		if (lun == NULL) {
3018 			mtx_unlock(&softc->ctl_lock);
3019 			free(new_err_desc, M_CTL);
3020 			printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
3021 			       __func__, (uintmax_t)err_desc->lun_id);
3022 			retval = EINVAL;
3023 			break;
3024 		}
3025 		mtx_lock(&lun->lun_lock);
3026 		mtx_unlock(&softc->ctl_lock);
3027 
3028 		/*
3029 		 * We could do some checking here to verify the validity
3030 		 * of the request, but given the complexity of error
3031 		 * injection requests, the checking logic would be fairly
3032 		 * complex.
3033 		 *
3034 		 * For now, if the request is invalid, it just won't get
3035 		 * executed and might get deleted.
3036 		 */
3037 		STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
3038 
3039 		/*
3040 		 * XXX KDM check to make sure the serial number is unique,
3041 		 * in case we somehow manage to wrap.  That shouldn't
3042 		 * happen for a very long time, but it's the right thing to
3043 		 * do.
3044 		 */
3045 		new_err_desc->serial = lun->error_serial;
3046 		err_desc->serial = lun->error_serial;
3047 		lun->error_serial++;
3048 
3049 		mtx_unlock(&lun->lun_lock);
3050 		break;
3051 	}
3052 	case CTL_ERROR_INJECT_DELETE: {
3053 		struct ctl_error_desc *delete_desc, *desc, *desc2;
3054 		struct ctl_lun *lun;
3055 		int delete_done;
3056 
3057 		delete_desc = (struct ctl_error_desc *)addr;
3058 		delete_done = 0;
3059 
3060 		mtx_lock(&softc->ctl_lock);
3061 		lun = softc->ctl_luns[delete_desc->lun_id];
3062 		if (lun == NULL) {
3063 			mtx_unlock(&softc->ctl_lock);
3064 			printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
3065 			       __func__, (uintmax_t)delete_desc->lun_id);
3066 			retval = EINVAL;
3067 			break;
3068 		}
3069 		mtx_lock(&lun->lun_lock);
3070 		mtx_unlock(&softc->ctl_lock);
3071 		STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
3072 			if (desc->serial != delete_desc->serial)
3073 				continue;
3074 
3075 			STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
3076 				      links);
3077 			free(desc, M_CTL);
3078 			delete_done = 1;
3079 		}
3080 		mtx_unlock(&lun->lun_lock);
3081 		if (delete_done == 0) {
3082 			printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
3083 			       "error serial %ju on LUN %u\n", __func__,
3084 			       delete_desc->serial, delete_desc->lun_id);
3085 			retval = EINVAL;
3086 			break;
3087 		}
3088 		break;
3089 	}
3090 	case CTL_DUMP_STRUCTS: {
3091 		int i, j, k;
3092 		struct ctl_port *port;
3093 		struct ctl_frontend *fe;
3094 
3095 		mtx_lock(&softc->ctl_lock);
3096 		printf("CTL Persistent Reservation information start:\n");
3097 		for (i = 0; i < CTL_MAX_LUNS; i++) {
3098 			struct ctl_lun *lun;
3099 
3100 			lun = softc->ctl_luns[i];
3101 
3102 			if ((lun == NULL)
3103 			 || ((lun->flags & CTL_LUN_DISABLED) != 0))
3104 				continue;
3105 
3106 			for (j = 0; j < (CTL_MAX_PORTS * 2); j++) {
3107 				if (lun->pr_keys[j] == NULL)
3108 					continue;
3109 				for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
3110 					if (lun->pr_keys[j][k] == 0)
3111 						continue;
3112 					printf("  LUN %d port %d iid %d key "
3113 					       "%#jx\n", i, j, k,
3114 					       (uintmax_t)lun->pr_keys[j][k]);
3115 				}
3116 			}
3117 		}
3118 		printf("CTL Persistent Reservation information end\n");
3119 		printf("CTL Ports:\n");
3120 		STAILQ_FOREACH(port, &softc->port_list, links) {
3121 			printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
3122 			       "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
3123 			       port->frontend->name, port->port_type,
3124 			       port->physical_port, port->virtual_port,
3125 			       (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
3126 			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3127 				if (port->wwpn_iid[j].in_use == 0 &&
3128 				    port->wwpn_iid[j].wwpn == 0 &&
3129 				    port->wwpn_iid[j].name == NULL)
3130 					continue;
3131 
3132 				printf("    iid %u use %d WWPN %#jx '%s'\n",
3133 				    j, port->wwpn_iid[j].in_use,
3134 				    (uintmax_t)port->wwpn_iid[j].wwpn,
3135 				    port->wwpn_iid[j].name);
3136 			}
3137 		}
3138 		printf("CTL Port information end\n");
3139 		mtx_unlock(&softc->ctl_lock);
3140 		/*
3141 		 * XXX KDM calling this without a lock.  We'd likely want
3142 		 * to drop the lock before calling the frontend's dump
3143 		 * routine anyway.
3144 		 */
3145 		printf("CTL Frontends:\n");
3146 		STAILQ_FOREACH(fe, &softc->fe_list, links) {
3147 			printf("  Frontend '%s'\n", fe->name);
3148 			if (fe->fe_dump != NULL)
3149 				fe->fe_dump();
3150 		}
3151 		printf("CTL Frontend information end\n");
3152 		break;
3153 	}
3154 	case CTL_LUN_REQ: {
3155 		struct ctl_lun_req *lun_req;
3156 		struct ctl_backend_driver *backend;
3157 
3158 		lun_req = (struct ctl_lun_req *)addr;
3159 
3160 		backend = ctl_backend_find(lun_req->backend);
3161 		if (backend == NULL) {
3162 			lun_req->status = CTL_LUN_ERROR;
3163 			snprintf(lun_req->error_str,
3164 				 sizeof(lun_req->error_str),
3165 				 "Backend \"%s\" not found.",
3166 				 lun_req->backend);
3167 			break;
3168 		}
3169 		if (lun_req->num_be_args > 0) {
3170 			lun_req->kern_be_args = ctl_copyin_args(
3171 				lun_req->num_be_args,
3172 				lun_req->be_args,
3173 				lun_req->error_str,
3174 				sizeof(lun_req->error_str));
3175 			if (lun_req->kern_be_args == NULL) {
3176 				lun_req->status = CTL_LUN_ERROR;
3177 				break;
3178 			}
3179 		}
3180 
3181 		retval = backend->ioctl(dev, cmd, addr, flag, td);
3182 
3183 		if (lun_req->num_be_args > 0) {
3184 			ctl_copyout_args(lun_req->num_be_args,
3185 				      lun_req->kern_be_args);
3186 			ctl_free_args(lun_req->num_be_args,
3187 				      lun_req->kern_be_args);
3188 		}
3189 		break;
3190 	}
3191 	case CTL_LUN_LIST: {
3192 		struct sbuf *sb;
3193 		struct ctl_lun *lun;
3194 		struct ctl_lun_list *list;
3195 		struct ctl_option *opt;
3196 
3197 		list = (struct ctl_lun_list *)addr;
3198 
3199 		/*
3200 		 * Allocate a fixed length sbuf here, based on the length
3201 		 * of the user's buffer.  We could allocate an auto-extending
3202 		 * buffer, and then tell the user how much larger our
3203 		 * amount of data is than his buffer, but that presents
3204 		 * some problems:
3205 		 *
3206 		 * 1.  The sbuf(9) routines use a blocking malloc, and so
3207 		 *     we can't hold a lock while calling them with an
3208 		 *     auto-extending buffer.
3209  		 *
3210 		 * 2.  There is not currently a LUN reference counting
3211 		 *     mechanism, outside of outstanding transactions on
3212 		 *     the LUN's OOA queue.  So a LUN could go away on us
3213 		 *     while we're getting the LUN number, backend-specific
3214 		 *     information, etc.  Thus, given the way things
3215 		 *     currently work, we need to hold the CTL lock while
3216 		 *     grabbing LUN information.
3217 		 *
3218 		 * So, from the user's standpoint, the best thing to do is
3219 		 * allocate what he thinks is a reasonable buffer length,
3220 		 * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
3221 		 * double the buffer length and try again.  (And repeat
3222 		 * that until he succeeds.)
3223 		 */
3224 		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3225 		if (sb == NULL) {
3226 			list->status = CTL_LUN_LIST_ERROR;
3227 			snprintf(list->error_str, sizeof(list->error_str),
3228 				 "Unable to allocate %d bytes for LUN list",
3229 				 list->alloc_len);
3230 			break;
3231 		}
3232 
3233 		sbuf_printf(sb, "<ctllunlist>\n");
3234 
3235 		mtx_lock(&softc->ctl_lock);
3236 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
3237 			mtx_lock(&lun->lun_lock);
3238 			retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3239 					     (uintmax_t)lun->lun);
3240 
3241 			/*
3242 			 * Bail out as soon as we see that we've overfilled
3243 			 * the buffer.
3244 			 */
3245 			if (retval != 0)
3246 				break;
3247 
3248 			retval = sbuf_printf(sb, "\t<backend_type>%s"
3249 					     "</backend_type>\n",
3250 					     (lun->backend == NULL) ?  "none" :
3251 					     lun->backend->name);
3252 
3253 			if (retval != 0)
3254 				break;
3255 
3256 			retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3257 					     lun->be_lun->lun_type);
3258 
3259 			if (retval != 0)
3260 				break;
3261 
3262 			if (lun->backend == NULL) {
3263 				retval = sbuf_printf(sb, "</lun>\n");
3264 				if (retval != 0)
3265 					break;
3266 				continue;
3267 			}
3268 
3269 			retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3270 					     (lun->be_lun->maxlba > 0) ?
3271 					     lun->be_lun->maxlba + 1 : 0);
3272 
3273 			if (retval != 0)
3274 				break;
3275 
3276 			retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3277 					     lun->be_lun->blocksize);
3278 
3279 			if (retval != 0)
3280 				break;
3281 
3282 			retval = sbuf_printf(sb, "\t<serial_number>");
3283 
3284 			if (retval != 0)
3285 				break;
3286 
3287 			retval = ctl_sbuf_printf_esc(sb,
3288 			    lun->be_lun->serial_num,
3289 			    sizeof(lun->be_lun->serial_num));
3290 
3291 			if (retval != 0)
3292 				break;
3293 
3294 			retval = sbuf_printf(sb, "</serial_number>\n");
3295 
3296 			if (retval != 0)
3297 				break;
3298 
3299 			retval = sbuf_printf(sb, "\t<device_id>");
3300 
3301 			if (retval != 0)
3302 				break;
3303 
3304 			retval = ctl_sbuf_printf_esc(sb,
3305 			    lun->be_lun->device_id,
3306 			    sizeof(lun->be_lun->device_id));
3307 
3308 			if (retval != 0)
3309 				break;
3310 
3311 			retval = sbuf_printf(sb, "</device_id>\n");
3312 
3313 			if (retval != 0)
3314 				break;
3315 
3316 			if (lun->backend->lun_info != NULL) {
3317 				retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
3318 				if (retval != 0)
3319 					break;
3320 			}
3321 			STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
3322 				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3323 				    opt->name, opt->value, opt->name);
3324 				if (retval != 0)
3325 					break;
3326 			}
3327 
3328 			retval = sbuf_printf(sb, "</lun>\n");
3329 
3330 			if (retval != 0)
3331 				break;
3332 			mtx_unlock(&lun->lun_lock);
3333 		}
3334 		if (lun != NULL)
3335 			mtx_unlock(&lun->lun_lock);
3336 		mtx_unlock(&softc->ctl_lock);
3337 
3338 		if ((retval != 0)
3339 		 || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3340 			retval = 0;
3341 			sbuf_delete(sb);
3342 			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3343 			snprintf(list->error_str, sizeof(list->error_str),
3344 				 "Out of space, %d bytes is too small",
3345 				 list->alloc_len);
3346 			break;
3347 		}
3348 
3349 		sbuf_finish(sb);
3350 
3351 		retval = copyout(sbuf_data(sb), list->lun_xml,
3352 				 sbuf_len(sb) + 1);
3353 
3354 		list->fill_len = sbuf_len(sb) + 1;
3355 		list->status = CTL_LUN_LIST_OK;
3356 		sbuf_delete(sb);
3357 		break;
3358 	}
3359 	case CTL_ISCSI: {
3360 		struct ctl_iscsi *ci;
3361 		struct ctl_frontend *fe;
3362 
3363 		ci = (struct ctl_iscsi *)addr;
3364 
3365 		fe = ctl_frontend_find("iscsi");
3366 		if (fe == NULL) {
3367 			ci->status = CTL_ISCSI_ERROR;
3368 			snprintf(ci->error_str, sizeof(ci->error_str),
3369 			    "Frontend \"iscsi\" not found.");
3370 			break;
3371 		}
3372 
3373 		retval = fe->ioctl(dev, cmd, addr, flag, td);
3374 		break;
3375 	}
3376 	case CTL_PORT_REQ: {
3377 		struct ctl_req *req;
3378 		struct ctl_frontend *fe;
3379 
3380 		req = (struct ctl_req *)addr;
3381 
3382 		fe = ctl_frontend_find(req->driver);
3383 		if (fe == NULL) {
3384 			req->status = CTL_LUN_ERROR;
3385 			snprintf(req->error_str, sizeof(req->error_str),
3386 			    "Frontend \"%s\" not found.", req->driver);
3387 			break;
3388 		}
3389 		if (req->num_args > 0) {
3390 			req->kern_args = ctl_copyin_args(req->num_args,
3391 			    req->args, req->error_str, sizeof(req->error_str));
3392 			if (req->kern_args == NULL) {
3393 				req->status = CTL_LUN_ERROR;
3394 				break;
3395 			}
3396 		}
3397 
3398 		retval = fe->ioctl(dev, cmd, addr, flag, td);
3399 
3400 		if (req->num_args > 0) {
3401 			ctl_copyout_args(req->num_args, req->kern_args);
3402 			ctl_free_args(req->num_args, req->kern_args);
3403 		}
3404 		break;
3405 	}
3406 	case CTL_PORT_LIST: {
3407 		struct sbuf *sb;
3408 		struct ctl_port *port;
3409 		struct ctl_lun_list *list;
3410 		struct ctl_option *opt;
3411 		int j;
3412 
3413 		list = (struct ctl_lun_list *)addr;
3414 
3415 		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3416 		if (sb == NULL) {
3417 			list->status = CTL_LUN_LIST_ERROR;
3418 			snprintf(list->error_str, sizeof(list->error_str),
3419 				 "Unable to allocate %d bytes for LUN list",
3420 				 list->alloc_len);
3421 			break;
3422 		}
3423 
3424 		sbuf_printf(sb, "<ctlportlist>\n");
3425 
3426 		mtx_lock(&softc->ctl_lock);
3427 		STAILQ_FOREACH(port, &softc->port_list, links) {
3428 			retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3429 					     (uintmax_t)port->targ_port);
3430 
3431 			/*
3432 			 * Bail out as soon as we see that we've overfilled
3433 			 * the buffer.
3434 			 */
3435 			if (retval != 0)
3436 				break;
3437 
3438 			retval = sbuf_printf(sb, "\t<frontend_type>%s"
3439 			    "</frontend_type>\n", port->frontend->name);
3440 			if (retval != 0)
3441 				break;
3442 
3443 			retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3444 					     port->port_type);
3445 			if (retval != 0)
3446 				break;
3447 
3448 			retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3449 			    (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3450 			if (retval != 0)
3451 				break;
3452 
3453 			retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3454 			    port->port_name);
3455 			if (retval != 0)
3456 				break;
3457 
3458 			retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3459 			    port->physical_port);
3460 			if (retval != 0)
3461 				break;
3462 
3463 			retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3464 			    port->virtual_port);
3465 			if (retval != 0)
3466 				break;
3467 
3468 			if (port->target_devid != NULL) {
3469 				sbuf_printf(sb, "\t<target>");
3470 				ctl_id_sbuf(port->target_devid, sb);
3471 				sbuf_printf(sb, "</target>\n");
3472 			}
3473 
3474 			if (port->port_devid != NULL) {
3475 				sbuf_printf(sb, "\t<port>");
3476 				ctl_id_sbuf(port->port_devid, sb);
3477 				sbuf_printf(sb, "</port>\n");
3478 			}
3479 
3480 			if (port->port_info != NULL) {
3481 				retval = port->port_info(port->onoff_arg, sb);
3482 				if (retval != 0)
3483 					break;
3484 			}
3485 			STAILQ_FOREACH(opt, &port->options, links) {
3486 				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3487 				    opt->name, opt->value, opt->name);
3488 				if (retval != 0)
3489 					break;
3490 			}
3491 
3492 			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3493 				if (port->wwpn_iid[j].in_use == 0 ||
3494 				    (port->wwpn_iid[j].wwpn == 0 &&
3495 				     port->wwpn_iid[j].name == NULL))
3496 					continue;
3497 
3498 				if (port->wwpn_iid[j].name != NULL)
3499 					retval = sbuf_printf(sb,
3500 					    "\t<initiator id=\"%u\">%s</initiator>\n",
3501 					    j, port->wwpn_iid[j].name);
3502 				else
3503 					retval = sbuf_printf(sb,
3504 					    "\t<initiator id=\"%u\">naa.%08jx</initiator>\n",
3505 					    j, port->wwpn_iid[j].wwpn);
3506 				if (retval != 0)
3507 					break;
3508 			}
3509 			if (retval != 0)
3510 				break;
3511 
3512 			retval = sbuf_printf(sb, "</targ_port>\n");
3513 			if (retval != 0)
3514 				break;
3515 		}
3516 		mtx_unlock(&softc->ctl_lock);
3517 
3518 		if ((retval != 0)
3519 		 || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3520 			retval = 0;
3521 			sbuf_delete(sb);
3522 			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3523 			snprintf(list->error_str, sizeof(list->error_str),
3524 				 "Out of space, %d bytes is too small",
3525 				 list->alloc_len);
3526 			break;
3527 		}
3528 
3529 		sbuf_finish(sb);
3530 
3531 		retval = copyout(sbuf_data(sb), list->lun_xml,
3532 				 sbuf_len(sb) + 1);
3533 
3534 		list->fill_len = sbuf_len(sb) + 1;
3535 		list->status = CTL_LUN_LIST_OK;
3536 		sbuf_delete(sb);
3537 		break;
3538 	}
3539 	default: {
3540 		/* XXX KDM should we fix this? */
3541 #if 0
3542 		struct ctl_backend_driver *backend;
3543 		unsigned int type;
3544 		int found;
3545 
3546 		found = 0;
3547 
3548 		/*
3549 		 * We encode the backend type as the ioctl type for backend
3550 		 * ioctls.  So parse it out here, and then search for a
3551 		 * backend of this type.
3552 		 */
3553 		type = _IOC_TYPE(cmd);
3554 
3555 		STAILQ_FOREACH(backend, &softc->be_list, links) {
3556 			if (backend->type == type) {
3557 				found = 1;
3558 				break;
3559 			}
3560 		}
3561 		if (found == 0) {
3562 			printf("ctl: unknown ioctl command %#lx or backend "
3563 			       "%d\n", cmd, type);
3564 			retval = EINVAL;
3565 			break;
3566 		}
3567 		retval = backend->ioctl(dev, cmd, addr, flag, td);
3568 #endif
3569 		retval = ENOTTY;
3570 		break;
3571 	}
3572 	}
3573 	return (retval);
3574 }
3575 
3576 uint32_t
3577 ctl_get_initindex(struct ctl_nexus *nexus)
3578 {
3579 	if (nexus->targ_port < CTL_MAX_PORTS)
3580 		return (nexus->initid.id +
3581 			(nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3582 	else
3583 		return (nexus->initid.id +
3584 		       ((nexus->targ_port - CTL_MAX_PORTS) *
3585 			CTL_MAX_INIT_PER_PORT));
3586 }
3587 
3588 uint32_t
3589 ctl_get_resindex(struct ctl_nexus *nexus)
3590 {
3591 	return (nexus->initid.id + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3592 }
3593 
3594 uint32_t
3595 ctl_port_idx(int port_num)
3596 {
3597 	if (port_num < CTL_MAX_PORTS)
3598 		return(port_num);
3599 	else
3600 		return(port_num - CTL_MAX_PORTS);
3601 }
3602 
3603 static uint32_t
3604 ctl_map_lun(struct ctl_softc *softc, int port_num, uint32_t lun_id)
3605 {
3606 	struct ctl_port *port;
3607 
3608 	port = softc->ctl_ports[ctl_port_idx(port_num)];
3609 	if (port == NULL)
3610 		return (UINT32_MAX);
3611 	if (port->lun_map == NULL)
3612 		return (lun_id);
3613 	return (port->lun_map(port->targ_lun_arg, lun_id));
3614 }
3615 
3616 static uint32_t
3617 ctl_map_lun_back(struct ctl_softc *softc, int port_num, uint32_t lun_id)
3618 {
3619 	struct ctl_port *port;
3620 	uint32_t i;
3621 
3622 	port = softc->ctl_ports[ctl_port_idx(port_num)];
3623 	if (port->lun_map == NULL)
3624 		return (lun_id);
3625 	for (i = 0; i < CTL_MAX_LUNS; i++) {
3626 		if (port->lun_map(port->targ_lun_arg, i) == lun_id)
3627 			return (i);
3628 	}
3629 	return (UINT32_MAX);
3630 }
3631 
3632 /*
3633  * Note:  This only works for bitmask sizes that are at least 32 bits, and
3634  * that are a power of 2.
3635  */
3636 int
3637 ctl_ffz(uint32_t *mask, uint32_t size)
3638 {
3639 	uint32_t num_chunks, num_pieces;
3640 	int i, j;
3641 
3642 	num_chunks = (size >> 5);
3643 	if (num_chunks == 0)
3644 		num_chunks++;
3645 	num_pieces = MIN((sizeof(uint32_t) * 8), size);
3646 
3647 	for (i = 0; i < num_chunks; i++) {
3648 		for (j = 0; j < num_pieces; j++) {
3649 			if ((mask[i] & (1 << j)) == 0)
3650 				return ((i << 5) + j);
3651 		}
3652 	}
3653 
3654 	return (-1);
3655 }
3656 
3657 int
3658 ctl_set_mask(uint32_t *mask, uint32_t bit)
3659 {
3660 	uint32_t chunk, piece;
3661 
3662 	chunk = bit >> 5;
3663 	piece = bit % (sizeof(uint32_t) * 8);
3664 
3665 	if ((mask[chunk] & (1 << piece)) != 0)
3666 		return (-1);
3667 	else
3668 		mask[chunk] |= (1 << piece);
3669 
3670 	return (0);
3671 }
3672 
3673 int
3674 ctl_clear_mask(uint32_t *mask, uint32_t bit)
3675 {
3676 	uint32_t chunk, piece;
3677 
3678 	chunk = bit >> 5;
3679 	piece = bit % (sizeof(uint32_t) * 8);
3680 
3681 	if ((mask[chunk] & (1 << piece)) == 0)
3682 		return (-1);
3683 	else
3684 		mask[chunk] &= ~(1 << piece);
3685 
3686 	return (0);
3687 }
3688 
3689 int
3690 ctl_is_set(uint32_t *mask, uint32_t bit)
3691 {
3692 	uint32_t chunk, piece;
3693 
3694 	chunk = bit >> 5;
3695 	piece = bit % (sizeof(uint32_t) * 8);
3696 
3697 	if ((mask[chunk] & (1 << piece)) == 0)
3698 		return (0);
3699 	else
3700 		return (1);
3701 }
3702 
3703 static uint64_t
3704 ctl_get_prkey(struct ctl_lun *lun, uint32_t residx)
3705 {
3706 	uint64_t *t;
3707 
3708 	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3709 	if (t == NULL)
3710 		return (0);
3711 	return (t[residx % CTL_MAX_INIT_PER_PORT]);
3712 }
3713 
3714 static void
3715 ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx)
3716 {
3717 	uint64_t *t;
3718 
3719 	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3720 	if (t == NULL)
3721 		return;
3722 	t[residx % CTL_MAX_INIT_PER_PORT] = 0;
3723 }
3724 
3725 static void
3726 ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx)
3727 {
3728 	uint64_t *p;
3729 	u_int i;
3730 
3731 	i = residx/CTL_MAX_INIT_PER_PORT;
3732 	if (lun->pr_keys[i] != NULL)
3733 		return;
3734 	mtx_unlock(&lun->lun_lock);
3735 	p = malloc(sizeof(uint64_t) * CTL_MAX_INIT_PER_PORT, M_CTL,
3736 	    M_WAITOK | M_ZERO);
3737 	mtx_lock(&lun->lun_lock);
3738 	if (lun->pr_keys[i] == NULL)
3739 		lun->pr_keys[i] = p;
3740 	else
3741 		free(p, M_CTL);
3742 }
3743 
3744 static void
3745 ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key)
3746 {
3747 	uint64_t *t;
3748 
3749 	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3750 	KASSERT(t != NULL, ("prkey %d is not allocated", residx));
3751 	t[residx % CTL_MAX_INIT_PER_PORT] = key;
3752 }
3753 
3754 /*
3755  * ctl_softc, pool_name, total_ctl_io are passed in.
3756  * npool is passed out.
3757  */
3758 int
3759 ctl_pool_create(struct ctl_softc *ctl_softc, const char *pool_name,
3760 		uint32_t total_ctl_io, void **npool)
3761 {
3762 #ifdef IO_POOLS
3763 	struct ctl_io_pool *pool;
3764 
3765 	pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3766 					    M_NOWAIT | M_ZERO);
3767 	if (pool == NULL)
3768 		return (ENOMEM);
3769 
3770 	snprintf(pool->name, sizeof(pool->name), "CTL IO %s", pool_name);
3771 	pool->ctl_softc = ctl_softc;
3772 	pool->zone = uma_zsecond_create(pool->name, NULL,
3773 	    NULL, NULL, NULL, ctl_softc->io_zone);
3774 	/* uma_prealloc(pool->zone, total_ctl_io); */
3775 
3776 	*npool = pool;
3777 #else
3778 	*npool = ctl_softc->io_zone;
3779 #endif
3780 	return (0);
3781 }
3782 
3783 void
3784 ctl_pool_free(struct ctl_io_pool *pool)
3785 {
3786 
3787 	if (pool == NULL)
3788 		return;
3789 
3790 #ifdef IO_POOLS
3791 	uma_zdestroy(pool->zone);
3792 	free(pool, M_CTL);
3793 #endif
3794 }
3795 
3796 union ctl_io *
3797 ctl_alloc_io(void *pool_ref)
3798 {
3799 	union ctl_io *io;
3800 #ifdef IO_POOLS
3801 	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3802 
3803 	io = uma_zalloc(pool->zone, M_WAITOK);
3804 #else
3805 	io = uma_zalloc((uma_zone_t)pool_ref, M_WAITOK);
3806 #endif
3807 	if (io != NULL)
3808 		io->io_hdr.pool = pool_ref;
3809 	return (io);
3810 }
3811 
3812 union ctl_io *
3813 ctl_alloc_io_nowait(void *pool_ref)
3814 {
3815 	union ctl_io *io;
3816 #ifdef IO_POOLS
3817 	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3818 
3819 	io = uma_zalloc(pool->zone, M_NOWAIT);
3820 #else
3821 	io = uma_zalloc((uma_zone_t)pool_ref, M_NOWAIT);
3822 #endif
3823 	if (io != NULL)
3824 		io->io_hdr.pool = pool_ref;
3825 	return (io);
3826 }
3827 
3828 void
3829 ctl_free_io(union ctl_io *io)
3830 {
3831 #ifdef IO_POOLS
3832 	struct ctl_io_pool *pool;
3833 #endif
3834 
3835 	if (io == NULL)
3836 		return;
3837 
3838 #ifdef IO_POOLS
3839 	pool = (struct ctl_io_pool *)io->io_hdr.pool;
3840 	uma_zfree(pool->zone, io);
3841 #else
3842 	uma_zfree((uma_zone_t)io->io_hdr.pool, io);
3843 #endif
3844 }
3845 
3846 void
3847 ctl_zero_io(union ctl_io *io)
3848 {
3849 	void *pool_ref;
3850 
3851 	if (io == NULL)
3852 		return;
3853 
3854 	/*
3855 	 * May need to preserve linked list pointers at some point too.
3856 	 */
3857 	pool_ref = io->io_hdr.pool;
3858 	memset(io, 0, sizeof(*io));
3859 	io->io_hdr.pool = pool_ref;
3860 }
3861 
3862 /*
3863  * This routine is currently used for internal copies of ctl_ios that need
3864  * to persist for some reason after we've already returned status to the
3865  * FETD.  (Thus the flag set.)
3866  *
3867  * XXX XXX
3868  * Note that this makes a blind copy of all fields in the ctl_io, except
3869  * for the pool reference.  This includes any memory that has been
3870  * allocated!  That memory will no longer be valid after done has been
3871  * called, so this would be VERY DANGEROUS for command that actually does
3872  * any reads or writes.  Right now (11/7/2005), this is only used for immediate
3873  * start and stop commands, which don't transfer any data, so this is not a
3874  * problem.  If it is used for anything else, the caller would also need to
3875  * allocate data buffer space and this routine would need to be modified to
3876  * copy the data buffer(s) as well.
3877  */
3878 void
3879 ctl_copy_io(union ctl_io *src, union ctl_io *dest)
3880 {
3881 	void *pool_ref;
3882 
3883 	if ((src == NULL)
3884 	 || (dest == NULL))
3885 		return;
3886 
3887 	/*
3888 	 * May need to preserve linked list pointers at some point too.
3889 	 */
3890 	pool_ref = dest->io_hdr.pool;
3891 
3892 	memcpy(dest, src, MIN(sizeof(*src), sizeof(*dest)));
3893 
3894 	dest->io_hdr.pool = pool_ref;
3895 	/*
3896 	 * We need to know that this is an internal copy, and doesn't need
3897 	 * to get passed back to the FETD that allocated it.
3898 	 */
3899 	dest->io_hdr.flags |= CTL_FLAG_INT_COPY;
3900 }
3901 
3902 int
3903 ctl_expand_number(const char *buf, uint64_t *num)
3904 {
3905 	char *endptr;
3906 	uint64_t number;
3907 	unsigned shift;
3908 
3909 	number = strtoq(buf, &endptr, 0);
3910 
3911 	switch (tolower((unsigned char)*endptr)) {
3912 	case 'e':
3913 		shift = 60;
3914 		break;
3915 	case 'p':
3916 		shift = 50;
3917 		break;
3918 	case 't':
3919 		shift = 40;
3920 		break;
3921 	case 'g':
3922 		shift = 30;
3923 		break;
3924 	case 'm':
3925 		shift = 20;
3926 		break;
3927 	case 'k':
3928 		shift = 10;
3929 		break;
3930 	case 'b':
3931 	case '\0': /* No unit. */
3932 		*num = number;
3933 		return (0);
3934 	default:
3935 		/* Unrecognized unit. */
3936 		return (-1);
3937 	}
3938 
3939 	if ((number << shift) >> shift != number) {
3940 		/* Overflow */
3941 		return (-1);
3942 	}
3943 	*num = number << shift;
3944 	return (0);
3945 }
3946 
3947 
3948 /*
3949  * This routine could be used in the future to load default and/or saved
3950  * mode page parameters for a particuar lun.
3951  */
3952 static int
3953 ctl_init_page_index(struct ctl_lun *lun)
3954 {
3955 	int i;
3956 	struct ctl_page_index *page_index;
3957 	const char *value;
3958 	uint64_t ival;
3959 
3960 	memcpy(&lun->mode_pages.index, page_index_template,
3961 	       sizeof(page_index_template));
3962 
3963 	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
3964 
3965 		page_index = &lun->mode_pages.index[i];
3966 		/*
3967 		 * If this is a disk-only mode page, there's no point in
3968 		 * setting it up.  For some pages, we have to have some
3969 		 * basic information about the disk in order to calculate the
3970 		 * mode page data.
3971 		 */
3972 		if ((lun->be_lun->lun_type != T_DIRECT)
3973 		 && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
3974 			continue;
3975 
3976 		switch (page_index->page_code & SMPH_PC_MASK) {
3977 		case SMS_RW_ERROR_RECOVERY_PAGE: {
3978 			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3979 				panic("subpage is incorrect!");
3980 			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT],
3981 			       &rw_er_page_default,
3982 			       sizeof(rw_er_page_default));
3983 			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CHANGEABLE],
3984 			       &rw_er_page_changeable,
3985 			       sizeof(rw_er_page_changeable));
3986 			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_DEFAULT],
3987 			       &rw_er_page_default,
3988 			       sizeof(rw_er_page_default));
3989 			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_SAVED],
3990 			       &rw_er_page_default,
3991 			       sizeof(rw_er_page_default));
3992 			page_index->page_data =
3993 				(uint8_t *)lun->mode_pages.rw_er_page;
3994 			break;
3995 		}
3996 		case SMS_FORMAT_DEVICE_PAGE: {
3997 			struct scsi_format_page *format_page;
3998 
3999 			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4000 				panic("subpage is incorrect!");
4001 
4002 			/*
4003 			 * Sectors per track are set above.  Bytes per
4004 			 * sector need to be set here on a per-LUN basis.
4005 			 */
4006 			memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
4007 			       &format_page_default,
4008 			       sizeof(format_page_default));
4009 			memcpy(&lun->mode_pages.format_page[
4010 			       CTL_PAGE_CHANGEABLE], &format_page_changeable,
4011 			       sizeof(format_page_changeable));
4012 			memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
4013 			       &format_page_default,
4014 			       sizeof(format_page_default));
4015 			memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
4016 			       &format_page_default,
4017 			       sizeof(format_page_default));
4018 
4019 			format_page = &lun->mode_pages.format_page[
4020 				CTL_PAGE_CURRENT];
4021 			scsi_ulto2b(lun->be_lun->blocksize,
4022 				    format_page->bytes_per_sector);
4023 
4024 			format_page = &lun->mode_pages.format_page[
4025 				CTL_PAGE_DEFAULT];
4026 			scsi_ulto2b(lun->be_lun->blocksize,
4027 				    format_page->bytes_per_sector);
4028 
4029 			format_page = &lun->mode_pages.format_page[
4030 				CTL_PAGE_SAVED];
4031 			scsi_ulto2b(lun->be_lun->blocksize,
4032 				    format_page->bytes_per_sector);
4033 
4034 			page_index->page_data =
4035 				(uint8_t *)lun->mode_pages.format_page;
4036 			break;
4037 		}
4038 		case SMS_RIGID_DISK_PAGE: {
4039 			struct scsi_rigid_disk_page *rigid_disk_page;
4040 			uint32_t sectors_per_cylinder;
4041 			uint64_t cylinders;
4042 #ifndef	__XSCALE__
4043 			int shift;
4044 #endif /* !__XSCALE__ */
4045 
4046 			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4047 				panic("invalid subpage value %d",
4048 				      page_index->subpage);
4049 
4050 			/*
4051 			 * Rotation rate and sectors per track are set
4052 			 * above.  We calculate the cylinders here based on
4053 			 * capacity.  Due to the number of heads and
4054 			 * sectors per track we're using, smaller arrays
4055 			 * may turn out to have 0 cylinders.  Linux and
4056 			 * FreeBSD don't pay attention to these mode pages
4057 			 * to figure out capacity, but Solaris does.  It
4058 			 * seems to deal with 0 cylinders just fine, and
4059 			 * works out a fake geometry based on the capacity.
4060 			 */
4061 			memcpy(&lun->mode_pages.rigid_disk_page[
4062 			       CTL_PAGE_DEFAULT], &rigid_disk_page_default,
4063 			       sizeof(rigid_disk_page_default));
4064 			memcpy(&lun->mode_pages.rigid_disk_page[
4065 			       CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
4066 			       sizeof(rigid_disk_page_changeable));
4067 
4068 			sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
4069 				CTL_DEFAULT_HEADS;
4070 
4071 			/*
4072 			 * The divide method here will be more accurate,
4073 			 * probably, but results in floating point being
4074 			 * used in the kernel on i386 (__udivdi3()).  On the
4075 			 * XScale, though, __udivdi3() is implemented in
4076 			 * software.
4077 			 *
4078 			 * The shift method for cylinder calculation is
4079 			 * accurate if sectors_per_cylinder is a power of
4080 			 * 2.  Otherwise it might be slightly off -- you
4081 			 * might have a bit of a truncation problem.
4082 			 */
4083 #ifdef	__XSCALE__
4084 			cylinders = (lun->be_lun->maxlba + 1) /
4085 				sectors_per_cylinder;
4086 #else
4087 			for (shift = 31; shift > 0; shift--) {
4088 				if (sectors_per_cylinder & (1 << shift))
4089 					break;
4090 			}
4091 			cylinders = (lun->be_lun->maxlba + 1) >> shift;
4092 #endif
4093 
4094 			/*
4095 			 * We've basically got 3 bytes, or 24 bits for the
4096 			 * cylinder size in the mode page.  If we're over,
4097 			 * just round down to 2^24.
4098 			 */
4099 			if (cylinders > 0xffffff)
4100 				cylinders = 0xffffff;
4101 
4102 			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4103 				CTL_PAGE_DEFAULT];
4104 			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4105 
4106 			if ((value = ctl_get_opt(&lun->be_lun->options,
4107 			    "rpm")) != NULL) {
4108 				scsi_ulto2b(strtol(value, NULL, 0),
4109 				     rigid_disk_page->rotation_rate);
4110 			}
4111 
4112 			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_CURRENT],
4113 			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4114 			       sizeof(rigid_disk_page_default));
4115 			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_SAVED],
4116 			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4117 			       sizeof(rigid_disk_page_default));
4118 
4119 			page_index->page_data =
4120 				(uint8_t *)lun->mode_pages.rigid_disk_page;
4121 			break;
4122 		}
4123 		case SMS_CACHING_PAGE: {
4124 			struct scsi_caching_page *caching_page;
4125 
4126 			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4127 				panic("invalid subpage value %d",
4128 				      page_index->subpage);
4129 			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4130 			       &caching_page_default,
4131 			       sizeof(caching_page_default));
4132 			memcpy(&lun->mode_pages.caching_page[
4133 			       CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4134 			       sizeof(caching_page_changeable));
4135 			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4136 			       &caching_page_default,
4137 			       sizeof(caching_page_default));
4138 			caching_page = &lun->mode_pages.caching_page[
4139 			    CTL_PAGE_SAVED];
4140 			value = ctl_get_opt(&lun->be_lun->options, "writecache");
4141 			if (value != NULL && strcmp(value, "off") == 0)
4142 				caching_page->flags1 &= ~SCP_WCE;
4143 			value = ctl_get_opt(&lun->be_lun->options, "readcache");
4144 			if (value != NULL && strcmp(value, "off") == 0)
4145 				caching_page->flags1 |= SCP_RCD;
4146 			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4147 			       &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4148 			       sizeof(caching_page_default));
4149 			page_index->page_data =
4150 				(uint8_t *)lun->mode_pages.caching_page;
4151 			break;
4152 		}
4153 		case SMS_CONTROL_MODE_PAGE: {
4154 			struct scsi_control_page *control_page;
4155 
4156 			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4157 				panic("invalid subpage value %d",
4158 				      page_index->subpage);
4159 
4160 			memcpy(&lun->mode_pages.control_page[CTL_PAGE_DEFAULT],
4161 			       &control_page_default,
4162 			       sizeof(control_page_default));
4163 			memcpy(&lun->mode_pages.control_page[
4164 			       CTL_PAGE_CHANGEABLE], &control_page_changeable,
4165 			       sizeof(control_page_changeable));
4166 			memcpy(&lun->mode_pages.control_page[CTL_PAGE_SAVED],
4167 			       &control_page_default,
4168 			       sizeof(control_page_default));
4169 			control_page = &lun->mode_pages.control_page[
4170 			    CTL_PAGE_SAVED];
4171 			value = ctl_get_opt(&lun->be_lun->options, "reordering");
4172 			if (value != NULL && strcmp(value, "unrestricted") == 0) {
4173 				control_page->queue_flags &= ~SCP_QUEUE_ALG_MASK;
4174 				control_page->queue_flags |= SCP_QUEUE_ALG_UNRESTRICTED;
4175 			}
4176 			memcpy(&lun->mode_pages.control_page[CTL_PAGE_CURRENT],
4177 			       &lun->mode_pages.control_page[CTL_PAGE_SAVED],
4178 			       sizeof(control_page_default));
4179 			page_index->page_data =
4180 				(uint8_t *)lun->mode_pages.control_page;
4181 			break;
4182 
4183 		}
4184 		case SMS_INFO_EXCEPTIONS_PAGE: {
4185 			switch (page_index->subpage) {
4186 			case SMS_SUBPAGE_PAGE_0:
4187 				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_CURRENT],
4188 				       &ie_page_default,
4189 				       sizeof(ie_page_default));
4190 				memcpy(&lun->mode_pages.ie_page[
4191 				       CTL_PAGE_CHANGEABLE], &ie_page_changeable,
4192 				       sizeof(ie_page_changeable));
4193 				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_DEFAULT],
4194 				       &ie_page_default,
4195 				       sizeof(ie_page_default));
4196 				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_SAVED],
4197 				       &ie_page_default,
4198 				       sizeof(ie_page_default));
4199 				page_index->page_data =
4200 					(uint8_t *)lun->mode_pages.ie_page;
4201 				break;
4202 			case 0x02: {
4203 				struct ctl_logical_block_provisioning_page *page;
4204 
4205 				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_DEFAULT],
4206 				       &lbp_page_default,
4207 				       sizeof(lbp_page_default));
4208 				memcpy(&lun->mode_pages.lbp_page[
4209 				       CTL_PAGE_CHANGEABLE], &lbp_page_changeable,
4210 				       sizeof(lbp_page_changeable));
4211 				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4212 				       &lbp_page_default,
4213 				       sizeof(lbp_page_default));
4214 				page = &lun->mode_pages.lbp_page[CTL_PAGE_SAVED];
4215 				value = ctl_get_opt(&lun->be_lun->options,
4216 				    "avail-threshold");
4217 				if (value != NULL &&
4218 				    ctl_expand_number(value, &ival) == 0) {
4219 					page->descr[0].flags |= SLBPPD_ENABLED |
4220 					    SLBPPD_ARMING_DEC;
4221 					if (lun->be_lun->blocksize)
4222 						ival /= lun->be_lun->blocksize;
4223 					else
4224 						ival /= 512;
4225 					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4226 					    page->descr[0].count);
4227 				}
4228 				value = ctl_get_opt(&lun->be_lun->options,
4229 				    "used-threshold");
4230 				if (value != NULL &&
4231 				    ctl_expand_number(value, &ival) == 0) {
4232 					page->descr[1].flags |= SLBPPD_ENABLED |
4233 					    SLBPPD_ARMING_INC;
4234 					if (lun->be_lun->blocksize)
4235 						ival /= lun->be_lun->blocksize;
4236 					else
4237 						ival /= 512;
4238 					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4239 					    page->descr[1].count);
4240 				}
4241 				value = ctl_get_opt(&lun->be_lun->options,
4242 				    "pool-avail-threshold");
4243 				if (value != NULL &&
4244 				    ctl_expand_number(value, &ival) == 0) {
4245 					page->descr[2].flags |= SLBPPD_ENABLED |
4246 					    SLBPPD_ARMING_DEC;
4247 					if (lun->be_lun->blocksize)
4248 						ival /= lun->be_lun->blocksize;
4249 					else
4250 						ival /= 512;
4251 					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4252 					    page->descr[2].count);
4253 				}
4254 				value = ctl_get_opt(&lun->be_lun->options,
4255 				    "pool-used-threshold");
4256 				if (value != NULL &&
4257 				    ctl_expand_number(value, &ival) == 0) {
4258 					page->descr[3].flags |= SLBPPD_ENABLED |
4259 					    SLBPPD_ARMING_INC;
4260 					if (lun->be_lun->blocksize)
4261 						ival /= lun->be_lun->blocksize;
4262 					else
4263 						ival /= 512;
4264 					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4265 					    page->descr[3].count);
4266 				}
4267 				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_CURRENT],
4268 				       &lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4269 				       sizeof(lbp_page_default));
4270 				page_index->page_data =
4271 					(uint8_t *)lun->mode_pages.lbp_page;
4272 			}}
4273 			break;
4274 		}
4275 		case SMS_VENDOR_SPECIFIC_PAGE:{
4276 			switch (page_index->subpage) {
4277 			case DBGCNF_SUBPAGE_CODE: {
4278 				struct copan_debugconf_subpage *current_page,
4279 							       *saved_page;
4280 
4281 				memcpy(&lun->mode_pages.debugconf_subpage[
4282 				       CTL_PAGE_CURRENT],
4283 				       &debugconf_page_default,
4284 				       sizeof(debugconf_page_default));
4285 				memcpy(&lun->mode_pages.debugconf_subpage[
4286 				       CTL_PAGE_CHANGEABLE],
4287 				       &debugconf_page_changeable,
4288 				       sizeof(debugconf_page_changeable));
4289 				memcpy(&lun->mode_pages.debugconf_subpage[
4290 				       CTL_PAGE_DEFAULT],
4291 				       &debugconf_page_default,
4292 				       sizeof(debugconf_page_default));
4293 				memcpy(&lun->mode_pages.debugconf_subpage[
4294 				       CTL_PAGE_SAVED],
4295 				       &debugconf_page_default,
4296 				       sizeof(debugconf_page_default));
4297 				page_index->page_data =
4298 					(uint8_t *)lun->mode_pages.debugconf_subpage;
4299 
4300 				current_page = (struct copan_debugconf_subpage *)
4301 					(page_index->page_data +
4302 					 (page_index->page_len *
4303 					  CTL_PAGE_CURRENT));
4304 				saved_page = (struct copan_debugconf_subpage *)
4305 					(page_index->page_data +
4306 					 (page_index->page_len *
4307 					  CTL_PAGE_SAVED));
4308 				break;
4309 			}
4310 			default:
4311 				panic("invalid subpage value %d",
4312 				      page_index->subpage);
4313 				break;
4314 			}
4315    			break;
4316 		}
4317 		default:
4318 			panic("invalid page value %d",
4319 			      page_index->page_code & SMPH_PC_MASK);
4320 			break;
4321     	}
4322 	}
4323 
4324 	return (CTL_RETVAL_COMPLETE);
4325 }
4326 
4327 static int
4328 ctl_init_log_page_index(struct ctl_lun *lun)
4329 {
4330 	struct ctl_page_index *page_index;
4331 	int i, j, k, prev;
4332 
4333 	memcpy(&lun->log_pages.index, log_page_index_template,
4334 	       sizeof(log_page_index_template));
4335 
4336 	prev = -1;
4337 	for (i = 0, j = 0, k = 0; i < CTL_NUM_LOG_PAGES; i++) {
4338 
4339 		page_index = &lun->log_pages.index[i];
4340 		/*
4341 		 * If this is a disk-only mode page, there's no point in
4342 		 * setting it up.  For some pages, we have to have some
4343 		 * basic information about the disk in order to calculate the
4344 		 * mode page data.
4345 		 */
4346 		if ((lun->be_lun->lun_type != T_DIRECT)
4347 		 && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
4348 			continue;
4349 
4350 		if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING &&
4351 		     lun->backend->lun_attr == NULL)
4352 			continue;
4353 
4354 		if (page_index->page_code != prev) {
4355 			lun->log_pages.pages_page[j] = page_index->page_code;
4356 			prev = page_index->page_code;
4357 			j++;
4358 		}
4359 		lun->log_pages.subpages_page[k*2] = page_index->page_code;
4360 		lun->log_pages.subpages_page[k*2+1] = page_index->subpage;
4361 		k++;
4362 	}
4363 	lun->log_pages.index[0].page_data = &lun->log_pages.pages_page[0];
4364 	lun->log_pages.index[0].page_len = j;
4365 	lun->log_pages.index[1].page_data = &lun->log_pages.subpages_page[0];
4366 	lun->log_pages.index[1].page_len = k * 2;
4367 	lun->log_pages.index[2].page_data = &lun->log_pages.lbp_page[0];
4368 	lun->log_pages.index[2].page_len = 12*CTL_NUM_LBP_PARAMS;
4369 
4370 	return (CTL_RETVAL_COMPLETE);
4371 }
4372 
4373 static int
4374 hex2bin(const char *str, uint8_t *buf, int buf_size)
4375 {
4376 	int i;
4377 	u_char c;
4378 
4379 	memset(buf, 0, buf_size);
4380 	while (isspace(str[0]))
4381 		str++;
4382 	if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
4383 		str += 2;
4384 	buf_size *= 2;
4385 	for (i = 0; str[i] != 0 && i < buf_size; i++) {
4386 		c = str[i];
4387 		if (isdigit(c))
4388 			c -= '0';
4389 		else if (isalpha(c))
4390 			c -= isupper(c) ? 'A' - 10 : 'a' - 10;
4391 		else
4392 			break;
4393 		if (c >= 16)
4394 			break;
4395 		if ((i & 1) == 0)
4396 			buf[i / 2] |= (c << 4);
4397 		else
4398 			buf[i / 2] |= c;
4399 	}
4400 	return ((i + 1) / 2);
4401 }
4402 
4403 /*
4404  * LUN allocation.
4405  *
4406  * Requirements:
4407  * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4408  *   wants us to allocate the LUN and he can block.
4409  * - ctl_softc is always set
4410  * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4411  *
4412  * Returns 0 for success, non-zero (errno) for failure.
4413  */
4414 static int
4415 ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4416 	      struct ctl_be_lun *const be_lun, struct ctl_id target_id)
4417 {
4418 	struct ctl_lun *nlun, *lun;
4419 	struct ctl_port *port;
4420 	struct scsi_vpd_id_descriptor *desc;
4421 	struct scsi_vpd_id_t10 *t10id;
4422 	const char *eui, *naa, *scsiname, *vendor, *value;
4423 	int lun_number, i, lun_malloced;
4424 	int devidlen, idlen1, idlen2 = 0, len;
4425 
4426 	if (be_lun == NULL)
4427 		return (EINVAL);
4428 
4429 	/*
4430 	 * We currently only support Direct Access or Processor LUN types.
4431 	 */
4432 	switch (be_lun->lun_type) {
4433 	case T_DIRECT:
4434 		break;
4435 	case T_PROCESSOR:
4436 		break;
4437 	case T_SEQUENTIAL:
4438 	case T_CHANGER:
4439 	default:
4440 		be_lun->lun_config_status(be_lun->be_lun,
4441 					  CTL_LUN_CONFIG_FAILURE);
4442 		break;
4443 	}
4444 	if (ctl_lun == NULL) {
4445 		lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4446 		lun_malloced = 1;
4447 	} else {
4448 		lun_malloced = 0;
4449 		lun = ctl_lun;
4450 	}
4451 
4452 	memset(lun, 0, sizeof(*lun));
4453 	if (lun_malloced)
4454 		lun->flags = CTL_LUN_MALLOCED;
4455 
4456 	/* Generate LUN ID. */
4457 	devidlen = max(CTL_DEVID_MIN_LEN,
4458 	    strnlen(be_lun->device_id, CTL_DEVID_LEN));
4459 	idlen1 = sizeof(*t10id) + devidlen;
4460 	len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4461 	scsiname = ctl_get_opt(&be_lun->options, "scsiname");
4462 	if (scsiname != NULL) {
4463 		idlen2 = roundup2(strlen(scsiname) + 1, 4);
4464 		len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4465 	}
4466 	eui = ctl_get_opt(&be_lun->options, "eui");
4467 	if (eui != NULL) {
4468 		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4469 	}
4470 	naa = ctl_get_opt(&be_lun->options, "naa");
4471 	if (naa != NULL) {
4472 		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4473 	}
4474 	lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4475 	    M_CTL, M_WAITOK | M_ZERO);
4476 	desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4477 	desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4478 	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4479 	desc->length = idlen1;
4480 	t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4481 	memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4482 	if ((vendor = ctl_get_opt(&be_lun->options, "vendor")) == NULL) {
4483 		strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4484 	} else {
4485 		strncpy(t10id->vendor, vendor,
4486 		    min(sizeof(t10id->vendor), strlen(vendor)));
4487 	}
4488 	strncpy((char *)t10id->vendor_spec_id,
4489 	    (char *)be_lun->device_id, devidlen);
4490 	if (scsiname != NULL) {
4491 		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4492 		    desc->length);
4493 		desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4494 		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4495 		    SVPD_ID_TYPE_SCSI_NAME;
4496 		desc->length = idlen2;
4497 		strlcpy(desc->identifier, scsiname, idlen2);
4498 	}
4499 	if (eui != NULL) {
4500 		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4501 		    desc->length);
4502 		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4503 		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4504 		    SVPD_ID_TYPE_EUI64;
4505 		desc->length = hex2bin(eui, desc->identifier, 16);
4506 		desc->length = desc->length > 12 ? 16 :
4507 		    (desc->length > 8 ? 12 : 8);
4508 		len -= 16 - desc->length;
4509 	}
4510 	if (naa != NULL) {
4511 		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4512 		    desc->length);
4513 		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4514 		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4515 		    SVPD_ID_TYPE_NAA;
4516 		desc->length = hex2bin(naa, desc->identifier, 16);
4517 		desc->length = desc->length > 8 ? 16 : 8;
4518 		len -= 16 - desc->length;
4519 	}
4520 	lun->lun_devid->len = len;
4521 
4522 	mtx_lock(&ctl_softc->ctl_lock);
4523 	/*
4524 	 * See if the caller requested a particular LUN number.  If so, see
4525 	 * if it is available.  Otherwise, allocate the first available LUN.
4526 	 */
4527 	if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4528 		if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4529 		 || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4530 			mtx_unlock(&ctl_softc->ctl_lock);
4531 			if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4532 				printf("ctl: requested LUN ID %d is higher "
4533 				       "than CTL_MAX_LUNS - 1 (%d)\n",
4534 				       be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4535 			} else {
4536 				/*
4537 				 * XXX KDM return an error, or just assign
4538 				 * another LUN ID in this case??
4539 				 */
4540 				printf("ctl: requested LUN ID %d is already "
4541 				       "in use\n", be_lun->req_lun_id);
4542 			}
4543 			if (lun->flags & CTL_LUN_MALLOCED)
4544 				free(lun, M_CTL);
4545 			be_lun->lun_config_status(be_lun->be_lun,
4546 						  CTL_LUN_CONFIG_FAILURE);
4547 			return (ENOSPC);
4548 		}
4549 		lun_number = be_lun->req_lun_id;
4550 	} else {
4551 		lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, CTL_MAX_LUNS);
4552 		if (lun_number == -1) {
4553 			mtx_unlock(&ctl_softc->ctl_lock);
4554 			printf("ctl: can't allocate LUN on target %ju, out of "
4555 			       "LUNs\n", (uintmax_t)target_id.id);
4556 			if (lun->flags & CTL_LUN_MALLOCED)
4557 				free(lun, M_CTL);
4558 			be_lun->lun_config_status(be_lun->be_lun,
4559 						  CTL_LUN_CONFIG_FAILURE);
4560 			return (ENOSPC);
4561 		}
4562 	}
4563 	ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4564 
4565 	mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4566 	lun->target = target_id;
4567 	lun->lun = lun_number;
4568 	lun->be_lun = be_lun;
4569 	/*
4570 	 * The processor LUN is always enabled.  Disk LUNs come on line
4571 	 * disabled, and must be enabled by the backend.
4572 	 */
4573 	lun->flags |= CTL_LUN_DISABLED;
4574 	lun->backend = be_lun->be;
4575 	be_lun->ctl_lun = lun;
4576 	be_lun->lun_id = lun_number;
4577 	atomic_add_int(&be_lun->be->num_luns, 1);
4578 	if (be_lun->flags & CTL_LUN_FLAG_OFFLINE)
4579 		lun->flags |= CTL_LUN_OFFLINE;
4580 
4581 	if (be_lun->flags & CTL_LUN_FLAG_POWERED_OFF)
4582 		lun->flags |= CTL_LUN_STOPPED;
4583 
4584 	if (be_lun->flags & CTL_LUN_FLAG_INOPERABLE)
4585 		lun->flags |= CTL_LUN_INOPERABLE;
4586 
4587 	if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4588 		lun->flags |= CTL_LUN_PRIMARY_SC;
4589 
4590 	value = ctl_get_opt(&be_lun->options, "readonly");
4591 	if (value != NULL && strcmp(value, "on") == 0)
4592 		lun->flags |= CTL_LUN_READONLY;
4593 
4594 	lun->serseq = CTL_LUN_SERSEQ_OFF;
4595 	if (be_lun->flags & CTL_LUN_FLAG_SERSEQ_READ)
4596 		lun->serseq = CTL_LUN_SERSEQ_READ;
4597 	value = ctl_get_opt(&be_lun->options, "serseq");
4598 	if (value != NULL && strcmp(value, "on") == 0)
4599 		lun->serseq = CTL_LUN_SERSEQ_ON;
4600 	else if (value != NULL && strcmp(value, "read") == 0)
4601 		lun->serseq = CTL_LUN_SERSEQ_READ;
4602 	else if (value != NULL && strcmp(value, "off") == 0)
4603 		lun->serseq = CTL_LUN_SERSEQ_OFF;
4604 
4605 	lun->ctl_softc = ctl_softc;
4606 	TAILQ_INIT(&lun->ooa_queue);
4607 	TAILQ_INIT(&lun->blocked_queue);
4608 	STAILQ_INIT(&lun->error_list);
4609 	ctl_tpc_lun_init(lun);
4610 
4611 	/*
4612 	 * Initialize the mode and log page index.
4613 	 */
4614 	ctl_init_page_index(lun);
4615 	ctl_init_log_page_index(lun);
4616 
4617 	/*
4618 	 * Now, before we insert this lun on the lun list, set the lun
4619 	 * inventory changed UA for all other luns.
4620 	 */
4621 	STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4622 		mtx_lock(&nlun->lun_lock);
4623 		ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4624 		mtx_unlock(&nlun->lun_lock);
4625 	}
4626 
4627 	STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4628 
4629 	ctl_softc->ctl_luns[lun_number] = lun;
4630 
4631 	ctl_softc->num_luns++;
4632 
4633 	/* Setup statistics gathering */
4634 	lun->stats.device_type = be_lun->lun_type;
4635 	lun->stats.lun_number = lun_number;
4636 	if (lun->stats.device_type == T_DIRECT)
4637 		lun->stats.blocksize = be_lun->blocksize;
4638 	else
4639 		lun->stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4640 	for (i = 0;i < CTL_MAX_PORTS;i++)
4641 		lun->stats.ports[i].targ_port = i;
4642 
4643 	mtx_unlock(&ctl_softc->ctl_lock);
4644 
4645 	lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4646 
4647 	/*
4648 	 * Run through each registered FETD and bring it online if it isn't
4649 	 * already.  Enable the target ID if it hasn't been enabled, and
4650 	 * enable this particular LUN.
4651 	 */
4652 	STAILQ_FOREACH(port, &ctl_softc->port_list, links) {
4653 		int retval;
4654 
4655 		retval = port->lun_enable(port->targ_lun_arg, target_id,lun_number);
4656 		if (retval != 0) {
4657 			printf("ctl_alloc_lun: FETD %s port %d returned error "
4658 			       "%d for lun_enable on target %ju lun %d\n",
4659 			       port->port_name, port->targ_port, retval,
4660 			       (uintmax_t)target_id.id, lun_number);
4661 		} else
4662 			port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4663 	}
4664 	return (0);
4665 }
4666 
4667 /*
4668  * Delete a LUN.
4669  * Assumptions:
4670  * - LUN has already been marked invalid and any pending I/O has been taken
4671  *   care of.
4672  */
4673 static int
4674 ctl_free_lun(struct ctl_lun *lun)
4675 {
4676 	struct ctl_softc *softc;
4677 #if 0
4678 	struct ctl_port *port;
4679 #endif
4680 	struct ctl_lun *nlun;
4681 	int i;
4682 
4683 	softc = lun->ctl_softc;
4684 
4685 	mtx_assert(&softc->ctl_lock, MA_OWNED);
4686 
4687 	STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4688 
4689 	ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4690 
4691 	softc->ctl_luns[lun->lun] = NULL;
4692 
4693 	if (!TAILQ_EMPTY(&lun->ooa_queue))
4694 		panic("Freeing a LUN %p with outstanding I/O!!\n", lun);
4695 
4696 	softc->num_luns--;
4697 
4698 	/*
4699 	 * XXX KDM this scheme only works for a single target/multiple LUN
4700 	 * setup.  It needs to be revamped for a multiple target scheme.
4701 	 *
4702 	 * XXX KDM this results in port->lun_disable() getting called twice,
4703 	 * once when ctl_disable_lun() is called, and a second time here.
4704 	 * We really need to re-think the LUN disable semantics.  There
4705 	 * should probably be several steps/levels to LUN removal:
4706 	 *  - disable
4707 	 *  - invalidate
4708 	 *  - free
4709  	 *
4710 	 * Right now we only have a disable method when communicating to
4711 	 * the front end ports, at least for individual LUNs.
4712 	 */
4713 #if 0
4714 	STAILQ_FOREACH(port, &softc->port_list, links) {
4715 		int retval;
4716 
4717 		retval = port->lun_disable(port->targ_lun_arg, lun->target,
4718 					 lun->lun);
4719 		if (retval != 0) {
4720 			printf("ctl_free_lun: FETD %s port %d returned error "
4721 			       "%d for lun_disable on target %ju lun %jd\n",
4722 			       port->port_name, port->targ_port, retval,
4723 			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4724 		}
4725 
4726 		if (STAILQ_FIRST(&softc->lun_list) == NULL) {
4727 			port->status &= ~CTL_PORT_STATUS_LUN_ONLINE;
4728 
4729 			retval = port->targ_disable(port->targ_lun_arg,lun->target);
4730 			if (retval != 0) {
4731 				printf("ctl_free_lun: FETD %s port %d "
4732 				       "returned error %d for targ_disable on "
4733 				       "target %ju\n", port->port_name,
4734 				       port->targ_port, retval,
4735 				       (uintmax_t)lun->target.id);
4736 			} else
4737 				port->status &= ~CTL_PORT_STATUS_TARG_ONLINE;
4738 
4739 			if ((port->status & CTL_PORT_STATUS_TARG_ONLINE) != 0)
4740 				continue;
4741 
4742 #if 0
4743 			port->port_offline(port->onoff_arg);
4744 			port->status &= ~CTL_PORT_STATUS_ONLINE;
4745 #endif
4746 		}
4747 	}
4748 #endif
4749 
4750 	/*
4751 	 * Tell the backend to free resources, if this LUN has a backend.
4752 	 */
4753 	atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4754 	lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4755 
4756 	ctl_tpc_lun_shutdown(lun);
4757 	mtx_destroy(&lun->lun_lock);
4758 	free(lun->lun_devid, M_CTL);
4759 	for (i = 0; i < CTL_MAX_PORTS; i++)
4760 		free(lun->pending_ua[i], M_CTL);
4761 	for (i = 0; i < 2 * CTL_MAX_PORTS; i++)
4762 		free(lun->pr_keys[i], M_CTL);
4763 	free(lun->write_buffer, M_CTL);
4764 	if (lun->flags & CTL_LUN_MALLOCED)
4765 		free(lun, M_CTL);
4766 
4767 	STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4768 		mtx_lock(&nlun->lun_lock);
4769 		ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4770 		mtx_unlock(&nlun->lun_lock);
4771 	}
4772 
4773 	return (0);
4774 }
4775 
4776 static void
4777 ctl_create_lun(struct ctl_be_lun *be_lun)
4778 {
4779 	struct ctl_softc *softc;
4780 
4781 	softc = control_softc;
4782 
4783 	/*
4784 	 * ctl_alloc_lun() should handle all potential failure cases.
4785 	 */
4786 	ctl_alloc_lun(softc, NULL, be_lun, softc->target);
4787 }
4788 
4789 int
4790 ctl_add_lun(struct ctl_be_lun *be_lun)
4791 {
4792 	struct ctl_softc *softc = control_softc;
4793 
4794 	mtx_lock(&softc->ctl_lock);
4795 	STAILQ_INSERT_TAIL(&softc->pending_lun_queue, be_lun, links);
4796 	mtx_unlock(&softc->ctl_lock);
4797 	wakeup(&softc->pending_lun_queue);
4798 
4799 	return (0);
4800 }
4801 
4802 int
4803 ctl_enable_lun(struct ctl_be_lun *be_lun)
4804 {
4805 	struct ctl_softc *softc;
4806 	struct ctl_port *port, *nport;
4807 	struct ctl_lun *lun;
4808 	int retval;
4809 
4810 	lun = (struct ctl_lun *)be_lun->ctl_lun;
4811 	softc = lun->ctl_softc;
4812 
4813 	mtx_lock(&softc->ctl_lock);
4814 	mtx_lock(&lun->lun_lock);
4815 	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4816 		/*
4817 		 * eh?  Why did we get called if the LUN is already
4818 		 * enabled?
4819 		 */
4820 		mtx_unlock(&lun->lun_lock);
4821 		mtx_unlock(&softc->ctl_lock);
4822 		return (0);
4823 	}
4824 	lun->flags &= ~CTL_LUN_DISABLED;
4825 	mtx_unlock(&lun->lun_lock);
4826 
4827 	for (port = STAILQ_FIRST(&softc->port_list); port != NULL; port = nport) {
4828 		nport = STAILQ_NEXT(port, links);
4829 
4830 		/*
4831 		 * Drop the lock while we call the FETD's enable routine.
4832 		 * This can lead to a callback into CTL (at least in the
4833 		 * case of the internal initiator frontend.
4834 		 */
4835 		mtx_unlock(&softc->ctl_lock);
4836 		retval = port->lun_enable(port->targ_lun_arg, lun->target,lun->lun);
4837 		mtx_lock(&softc->ctl_lock);
4838 		if (retval != 0) {
4839 			printf("%s: FETD %s port %d returned error "
4840 			       "%d for lun_enable on target %ju lun %jd\n",
4841 			       __func__, port->port_name, port->targ_port, retval,
4842 			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4843 		}
4844 #if 0
4845 		 else {
4846             /* NOTE:  TODO:  why does lun enable affect port status? */
4847 			port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4848 		}
4849 #endif
4850 	}
4851 
4852 	mtx_unlock(&softc->ctl_lock);
4853 
4854 	return (0);
4855 }
4856 
4857 int
4858 ctl_disable_lun(struct ctl_be_lun *be_lun)
4859 {
4860 	struct ctl_softc *softc;
4861 	struct ctl_port *port;
4862 	struct ctl_lun *lun;
4863 	int retval;
4864 
4865 	lun = (struct ctl_lun *)be_lun->ctl_lun;
4866 	softc = lun->ctl_softc;
4867 
4868 	mtx_lock(&softc->ctl_lock);
4869 	mtx_lock(&lun->lun_lock);
4870 	if (lun->flags & CTL_LUN_DISABLED) {
4871 		mtx_unlock(&lun->lun_lock);
4872 		mtx_unlock(&softc->ctl_lock);
4873 		return (0);
4874 	}
4875 	lun->flags |= CTL_LUN_DISABLED;
4876 	mtx_unlock(&lun->lun_lock);
4877 
4878 	STAILQ_FOREACH(port, &softc->port_list, links) {
4879 		mtx_unlock(&softc->ctl_lock);
4880 		/*
4881 		 * Drop the lock before we call the frontend's disable
4882 		 * routine, to avoid lock order reversals.
4883 		 *
4884 		 * XXX KDM what happens if the frontend list changes while
4885 		 * we're traversing it?  It's unlikely, but should be handled.
4886 		 */
4887 		retval = port->lun_disable(port->targ_lun_arg, lun->target,
4888 					 lun->lun);
4889 		mtx_lock(&softc->ctl_lock);
4890 		if (retval != 0) {
4891 			printf("ctl_alloc_lun: FETD %s port %d returned error "
4892 			       "%d for lun_disable on target %ju lun %jd\n",
4893 			       port->port_name, port->targ_port, retval,
4894 			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4895 		}
4896 	}
4897 
4898 	mtx_unlock(&softc->ctl_lock);
4899 
4900 	return (0);
4901 }
4902 
4903 int
4904 ctl_start_lun(struct ctl_be_lun *be_lun)
4905 {
4906 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4907 
4908 	mtx_lock(&lun->lun_lock);
4909 	lun->flags &= ~CTL_LUN_STOPPED;
4910 	mtx_unlock(&lun->lun_lock);
4911 	return (0);
4912 }
4913 
4914 int
4915 ctl_stop_lun(struct ctl_be_lun *be_lun)
4916 {
4917 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4918 
4919 	mtx_lock(&lun->lun_lock);
4920 	lun->flags |= CTL_LUN_STOPPED;
4921 	mtx_unlock(&lun->lun_lock);
4922 	return (0);
4923 }
4924 
4925 int
4926 ctl_lun_offline(struct ctl_be_lun *be_lun)
4927 {
4928 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4929 
4930 	mtx_lock(&lun->lun_lock);
4931 	lun->flags |= CTL_LUN_OFFLINE;
4932 	mtx_unlock(&lun->lun_lock);
4933 	return (0);
4934 }
4935 
4936 int
4937 ctl_lun_online(struct ctl_be_lun *be_lun)
4938 {
4939 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4940 
4941 	mtx_lock(&lun->lun_lock);
4942 	lun->flags &= ~CTL_LUN_OFFLINE;
4943 	mtx_unlock(&lun->lun_lock);
4944 	return (0);
4945 }
4946 
4947 int
4948 ctl_invalidate_lun(struct ctl_be_lun *be_lun)
4949 {
4950 	struct ctl_softc *softc;
4951 	struct ctl_lun *lun;
4952 
4953 	lun = (struct ctl_lun *)be_lun->ctl_lun;
4954 	softc = lun->ctl_softc;
4955 
4956 	mtx_lock(&lun->lun_lock);
4957 
4958 	/*
4959 	 * The LUN needs to be disabled before it can be marked invalid.
4960 	 */
4961 	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4962 		mtx_unlock(&lun->lun_lock);
4963 		return (-1);
4964 	}
4965 	/*
4966 	 * Mark the LUN invalid.
4967 	 */
4968 	lun->flags |= CTL_LUN_INVALID;
4969 
4970 	/*
4971 	 * If there is nothing in the OOA queue, go ahead and free the LUN.
4972 	 * If we have something in the OOA queue, we'll free it when the
4973 	 * last I/O completes.
4974 	 */
4975 	if (TAILQ_EMPTY(&lun->ooa_queue)) {
4976 		mtx_unlock(&lun->lun_lock);
4977 		mtx_lock(&softc->ctl_lock);
4978 		ctl_free_lun(lun);
4979 		mtx_unlock(&softc->ctl_lock);
4980 	} else
4981 		mtx_unlock(&lun->lun_lock);
4982 
4983 	return (0);
4984 }
4985 
4986 int
4987 ctl_lun_inoperable(struct ctl_be_lun *be_lun)
4988 {
4989 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4990 
4991 	mtx_lock(&lun->lun_lock);
4992 	lun->flags |= CTL_LUN_INOPERABLE;
4993 	mtx_unlock(&lun->lun_lock);
4994 	return (0);
4995 }
4996 
4997 int
4998 ctl_lun_operable(struct ctl_be_lun *be_lun)
4999 {
5000 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5001 
5002 	mtx_lock(&lun->lun_lock);
5003 	lun->flags &= ~CTL_LUN_INOPERABLE;
5004 	mtx_unlock(&lun->lun_lock);
5005 	return (0);
5006 }
5007 
5008 void
5009 ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
5010 {
5011 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5012 
5013 	mtx_lock(&lun->lun_lock);
5014 	ctl_est_ua_all(lun, -1, CTL_UA_CAPACITY_CHANGED);
5015 	mtx_unlock(&lun->lun_lock);
5016 }
5017 
5018 /*
5019  * Backend "memory move is complete" callback for requests that never
5020  * make it down to say RAIDCore's configuration code.
5021  */
5022 int
5023 ctl_config_move_done(union ctl_io *io)
5024 {
5025 	int retval;
5026 
5027 	CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
5028 	KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
5029 	    ("Config I/O type isn't CTL_IO_SCSI (%d)!", io->io_hdr.io_type));
5030 
5031 	if ((io->io_hdr.port_status != 0) &&
5032 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5033 	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5034 		/*
5035 		 * For hardware error sense keys, the sense key
5036 		 * specific value is defined to be a retry count,
5037 		 * but we use it to pass back an internal FETD
5038 		 * error code.  XXX KDM  Hopefully the FETD is only
5039 		 * using 16 bits for an error code, since that's
5040 		 * all the space we have in the sks field.
5041 		 */
5042 		ctl_set_internal_failure(&io->scsiio,
5043 					 /*sks_valid*/ 1,
5044 					 /*retry_count*/
5045 					 io->io_hdr.port_status);
5046 	}
5047 
5048 	if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN) ||
5049 	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5050 	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) ||
5051 	    ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
5052 		/*
5053 		 * XXX KDM just assuming a single pointer here, and not a
5054 		 * S/G list.  If we start using S/G lists for config data,
5055 		 * we'll need to know how to clean them up here as well.
5056 		 */
5057 		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5058 			free(io->scsiio.kern_data_ptr, M_CTL);
5059 		ctl_done(io);
5060 		retval = CTL_RETVAL_COMPLETE;
5061 	} else {
5062 		/*
5063 		 * XXX KDM now we need to continue data movement.  Some
5064 		 * options:
5065 		 * - call ctl_scsiio() again?  We don't do this for data
5066 		 *   writes, because for those at least we know ahead of
5067 		 *   time where the write will go and how long it is.  For
5068 		 *   config writes, though, that information is largely
5069 		 *   contained within the write itself, thus we need to
5070 		 *   parse out the data again.
5071 		 *
5072 		 * - Call some other function once the data is in?
5073 		 */
5074 		if (ctl_debug & CTL_DEBUG_CDB_DATA)
5075 			ctl_data_print(io);
5076 
5077 		/*
5078 		 * XXX KDM call ctl_scsiio() again for now, and check flag
5079 		 * bits to see whether we're allocated or not.
5080 		 */
5081 		retval = ctl_scsiio(&io->scsiio);
5082 	}
5083 	return (retval);
5084 }
5085 
5086 /*
5087  * This gets called by a backend driver when it is done with a
5088  * data_submit method.
5089  */
5090 void
5091 ctl_data_submit_done(union ctl_io *io)
5092 {
5093 	/*
5094 	 * If the IO_CONT flag is set, we need to call the supplied
5095 	 * function to continue processing the I/O, instead of completing
5096 	 * the I/O just yet.
5097 	 *
5098 	 * If there is an error, though, we don't want to keep processing.
5099 	 * Instead, just send status back to the initiator.
5100 	 */
5101 	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5102 	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5103 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5104 	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5105 		io->scsiio.io_cont(io);
5106 		return;
5107 	}
5108 	ctl_done(io);
5109 }
5110 
5111 /*
5112  * This gets called by a backend driver when it is done with a
5113  * configuration write.
5114  */
5115 void
5116 ctl_config_write_done(union ctl_io *io)
5117 {
5118 	uint8_t *buf;
5119 
5120 	/*
5121 	 * If the IO_CONT flag is set, we need to call the supplied
5122 	 * function to continue processing the I/O, instead of completing
5123 	 * the I/O just yet.
5124 	 *
5125 	 * If there is an error, though, we don't want to keep processing.
5126 	 * Instead, just send status back to the initiator.
5127 	 */
5128 	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5129 	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5130 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5131 	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5132 		io->scsiio.io_cont(io);
5133 		return;
5134 	}
5135 	/*
5136 	 * Since a configuration write can be done for commands that actually
5137 	 * have data allocated, like write buffer, and commands that have
5138 	 * no data, like start/stop unit, we need to check here.
5139 	 */
5140 	if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5141 		buf = io->scsiio.kern_data_ptr;
5142 	else
5143 		buf = NULL;
5144 	ctl_done(io);
5145 	if (buf)
5146 		free(buf, M_CTL);
5147 }
5148 
5149 void
5150 ctl_config_read_done(union ctl_io *io)
5151 {
5152 	uint8_t *buf;
5153 
5154 	/*
5155 	 * If there is some error -- we are done, skip data transfer.
5156 	 */
5157 	if ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0 ||
5158 	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5159 	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)) {
5160 		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5161 			buf = io->scsiio.kern_data_ptr;
5162 		else
5163 			buf = NULL;
5164 		ctl_done(io);
5165 		if (buf)
5166 			free(buf, M_CTL);
5167 		return;
5168 	}
5169 
5170 	/*
5171 	 * If the IO_CONT flag is set, we need to call the supplied
5172 	 * function to continue processing the I/O, instead of completing
5173 	 * the I/O just yet.
5174 	 */
5175 	if (io->io_hdr.flags & CTL_FLAG_IO_CONT) {
5176 		io->scsiio.io_cont(io);
5177 		return;
5178 	}
5179 
5180 	ctl_datamove(io);
5181 }
5182 
5183 /*
5184  * SCSI release command.
5185  */
5186 int
5187 ctl_scsi_release(struct ctl_scsiio *ctsio)
5188 {
5189 	int length, longid, thirdparty_id, resv_id;
5190 	struct ctl_lun *lun;
5191 	uint32_t residx;
5192 
5193 	length = 0;
5194 	resv_id = 0;
5195 
5196 	CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5197 
5198 	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5199 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5200 
5201 	switch (ctsio->cdb[0]) {
5202 	case RELEASE_10: {
5203 		struct scsi_release_10 *cdb;
5204 
5205 		cdb = (struct scsi_release_10 *)ctsio->cdb;
5206 
5207 		if (cdb->byte2 & SR10_LONGID)
5208 			longid = 1;
5209 		else
5210 			thirdparty_id = cdb->thirdparty_id;
5211 
5212 		resv_id = cdb->resv_id;
5213 		length = scsi_2btoul(cdb->length);
5214 		break;
5215 	}
5216 	}
5217 
5218 
5219 	/*
5220 	 * XXX KDM right now, we only support LUN reservation.  We don't
5221 	 * support 3rd party reservations, or extent reservations, which
5222 	 * might actually need the parameter list.  If we've gotten this
5223 	 * far, we've got a LUN reservation.  Anything else got kicked out
5224 	 * above.  So, according to SPC, ignore the length.
5225 	 */
5226 	length = 0;
5227 
5228 	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5229 	 && (length > 0)) {
5230 		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5231 		ctsio->kern_data_len = length;
5232 		ctsio->kern_total_len = length;
5233 		ctsio->kern_data_resid = 0;
5234 		ctsio->kern_rel_offset = 0;
5235 		ctsio->kern_sg_entries = 0;
5236 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5237 		ctsio->be_move_done = ctl_config_move_done;
5238 		ctl_datamove((union ctl_io *)ctsio);
5239 
5240 		return (CTL_RETVAL_COMPLETE);
5241 	}
5242 
5243 	if (length > 0)
5244 		thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5245 
5246 	mtx_lock(&lun->lun_lock);
5247 
5248 	/*
5249 	 * According to SPC, it is not an error for an intiator to attempt
5250 	 * to release a reservation on a LUN that isn't reserved, or that
5251 	 * is reserved by another initiator.  The reservation can only be
5252 	 * released, though, by the initiator who made it or by one of
5253 	 * several reset type events.
5254 	 */
5255 	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
5256 			lun->flags &= ~CTL_LUN_RESERVED;
5257 
5258 	mtx_unlock(&lun->lun_lock);
5259 
5260 	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5261 		free(ctsio->kern_data_ptr, M_CTL);
5262 		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5263 	}
5264 
5265 	ctl_set_success(ctsio);
5266 	ctl_done((union ctl_io *)ctsio);
5267 	return (CTL_RETVAL_COMPLETE);
5268 }
5269 
5270 int
5271 ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5272 {
5273 	int extent, thirdparty, longid;
5274 	int resv_id, length;
5275 	uint64_t thirdparty_id;
5276 	struct ctl_lun *lun;
5277 	uint32_t residx;
5278 
5279 	extent = 0;
5280 	thirdparty = 0;
5281 	longid = 0;
5282 	resv_id = 0;
5283 	length = 0;
5284 	thirdparty_id = 0;
5285 
5286 	CTL_DEBUG_PRINT(("ctl_reserve\n"));
5287 
5288 	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5289 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5290 
5291 	switch (ctsio->cdb[0]) {
5292 	case RESERVE_10: {
5293 		struct scsi_reserve_10 *cdb;
5294 
5295 		cdb = (struct scsi_reserve_10 *)ctsio->cdb;
5296 
5297 		if (cdb->byte2 & SR10_LONGID)
5298 			longid = 1;
5299 		else
5300 			thirdparty_id = cdb->thirdparty_id;
5301 
5302 		resv_id = cdb->resv_id;
5303 		length = scsi_2btoul(cdb->length);
5304 		break;
5305 	}
5306 	}
5307 
5308 	/*
5309 	 * XXX KDM right now, we only support LUN reservation.  We don't
5310 	 * support 3rd party reservations, or extent reservations, which
5311 	 * might actually need the parameter list.  If we've gotten this
5312 	 * far, we've got a LUN reservation.  Anything else got kicked out
5313 	 * above.  So, according to SPC, ignore the length.
5314 	 */
5315 	length = 0;
5316 
5317 	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5318 	 && (length > 0)) {
5319 		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5320 		ctsio->kern_data_len = length;
5321 		ctsio->kern_total_len = length;
5322 		ctsio->kern_data_resid = 0;
5323 		ctsio->kern_rel_offset = 0;
5324 		ctsio->kern_sg_entries = 0;
5325 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5326 		ctsio->be_move_done = ctl_config_move_done;
5327 		ctl_datamove((union ctl_io *)ctsio);
5328 
5329 		return (CTL_RETVAL_COMPLETE);
5330 	}
5331 
5332 	if (length > 0)
5333 		thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5334 
5335 	mtx_lock(&lun->lun_lock);
5336 	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
5337 		ctl_set_reservation_conflict(ctsio);
5338 		goto bailout;
5339 	}
5340 
5341 	lun->flags |= CTL_LUN_RESERVED;
5342 	lun->res_idx = residx;
5343 
5344 	ctl_set_success(ctsio);
5345 
5346 bailout:
5347 	mtx_unlock(&lun->lun_lock);
5348 
5349 	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5350 		free(ctsio->kern_data_ptr, M_CTL);
5351 		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5352 	}
5353 
5354 	ctl_done((union ctl_io *)ctsio);
5355 	return (CTL_RETVAL_COMPLETE);
5356 }
5357 
5358 int
5359 ctl_start_stop(struct ctl_scsiio *ctsio)
5360 {
5361 	struct scsi_start_stop_unit *cdb;
5362 	struct ctl_lun *lun;
5363 	int retval;
5364 
5365 	CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5366 
5367 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5368 	retval = 0;
5369 
5370 	cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5371 
5372 	/*
5373 	 * XXX KDM
5374 	 * We don't support the immediate bit on a stop unit.  In order to
5375 	 * do that, we would need to code up a way to know that a stop is
5376 	 * pending, and hold off any new commands until it completes, one
5377 	 * way or another.  Then we could accept or reject those commands
5378 	 * depending on its status.  We would almost need to do the reverse
5379 	 * of what we do below for an immediate start -- return the copy of
5380 	 * the ctl_io to the FETD with status to send to the host (and to
5381 	 * free the copy!) and then free the original I/O once the stop
5382 	 * actually completes.  That way, the OOA queue mechanism can work
5383 	 * to block commands that shouldn't proceed.  Another alternative
5384 	 * would be to put the copy in the queue in place of the original,
5385 	 * and return the original back to the caller.  That could be
5386 	 * slightly safer..
5387 	 */
5388 	if ((cdb->byte2 & SSS_IMMED)
5389 	 && ((cdb->how & SSS_START) == 0)) {
5390 		ctl_set_invalid_field(ctsio,
5391 				      /*sks_valid*/ 1,
5392 				      /*command*/ 1,
5393 				      /*field*/ 1,
5394 				      /*bit_valid*/ 1,
5395 				      /*bit*/ 0);
5396 		ctl_done((union ctl_io *)ctsio);
5397 		return (CTL_RETVAL_COMPLETE);
5398 	}
5399 
5400 	if ((lun->flags & CTL_LUN_PR_RESERVED)
5401 	 && ((cdb->how & SSS_START)==0)) {
5402 		uint32_t residx;
5403 
5404 		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5405 		if (ctl_get_prkey(lun, residx) == 0
5406 		 || (lun->pr_res_idx!=residx && lun->res_type < 4)) {
5407 
5408 			ctl_set_reservation_conflict(ctsio);
5409 			ctl_done((union ctl_io *)ctsio);
5410 			return (CTL_RETVAL_COMPLETE);
5411 		}
5412 	}
5413 
5414 	/*
5415 	 * If there is no backend on this device, we can't start or stop
5416 	 * it.  In theory we shouldn't get any start/stop commands in the
5417 	 * first place at this level if the LUN doesn't have a backend.
5418 	 * That should get stopped by the command decode code.
5419 	 */
5420 	if (lun->backend == NULL) {
5421 		ctl_set_invalid_opcode(ctsio);
5422 		ctl_done((union ctl_io *)ctsio);
5423 		return (CTL_RETVAL_COMPLETE);
5424 	}
5425 
5426 	/*
5427 	 * XXX KDM Copan-specific offline behavior.
5428 	 * Figure out a reasonable way to port this?
5429 	 */
5430 #ifdef NEEDTOPORT
5431 	mtx_lock(&lun->lun_lock);
5432 
5433 	if (((cdb->byte2 & SSS_ONOFFLINE) == 0)
5434 	 && (lun->flags & CTL_LUN_OFFLINE)) {
5435 		/*
5436 		 * If the LUN is offline, and the on/offline bit isn't set,
5437 		 * reject the start or stop.  Otherwise, let it through.
5438 		 */
5439 		mtx_unlock(&lun->lun_lock);
5440 		ctl_set_lun_not_ready(ctsio);
5441 		ctl_done((union ctl_io *)ctsio);
5442 	} else {
5443 		mtx_unlock(&lun->lun_lock);
5444 #endif /* NEEDTOPORT */
5445 		/*
5446 		 * This could be a start or a stop when we're online,
5447 		 * or a stop/offline or start/online.  A start or stop when
5448 		 * we're offline is covered in the case above.
5449 		 */
5450 		/*
5451 		 * In the non-immediate case, we send the request to
5452 		 * the backend and return status to the user when
5453 		 * it is done.
5454 		 *
5455 		 * In the immediate case, we allocate a new ctl_io
5456 		 * to hold a copy of the request, and send that to
5457 		 * the backend.  We then set good status on the
5458 		 * user's request and return it immediately.
5459 		 */
5460 		if (cdb->byte2 & SSS_IMMED) {
5461 			union ctl_io *new_io;
5462 
5463 			new_io = ctl_alloc_io(ctsio->io_hdr.pool);
5464 			ctl_copy_io((union ctl_io *)ctsio, new_io);
5465 			retval = lun->backend->config_write(new_io);
5466 			ctl_set_success(ctsio);
5467 			ctl_done((union ctl_io *)ctsio);
5468 		} else {
5469 			retval = lun->backend->config_write(
5470 				(union ctl_io *)ctsio);
5471 		}
5472 #ifdef NEEDTOPORT
5473 	}
5474 #endif
5475 	return (retval);
5476 }
5477 
5478 /*
5479  * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5480  * we don't really do anything with the LBA and length fields if the user
5481  * passes them in.  Instead we'll just flush out the cache for the entire
5482  * LUN.
5483  */
5484 int
5485 ctl_sync_cache(struct ctl_scsiio *ctsio)
5486 {
5487 	struct ctl_lun *lun;
5488 	struct ctl_softc *softc;
5489 	uint64_t starting_lba;
5490 	uint32_t block_count;
5491 	int retval;
5492 
5493 	CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5494 
5495 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5496 	softc = lun->ctl_softc;
5497 	retval = 0;
5498 
5499 	switch (ctsio->cdb[0]) {
5500 	case SYNCHRONIZE_CACHE: {
5501 		struct scsi_sync_cache *cdb;
5502 		cdb = (struct scsi_sync_cache *)ctsio->cdb;
5503 
5504 		starting_lba = scsi_4btoul(cdb->begin_lba);
5505 		block_count = scsi_2btoul(cdb->lb_count);
5506 		break;
5507 	}
5508 	case SYNCHRONIZE_CACHE_16: {
5509 		struct scsi_sync_cache_16 *cdb;
5510 		cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5511 
5512 		starting_lba = scsi_8btou64(cdb->begin_lba);
5513 		block_count = scsi_4btoul(cdb->lb_count);
5514 		break;
5515 	}
5516 	default:
5517 		ctl_set_invalid_opcode(ctsio);
5518 		ctl_done((union ctl_io *)ctsio);
5519 		goto bailout;
5520 		break; /* NOTREACHED */
5521 	}
5522 
5523 	/*
5524 	 * We check the LBA and length, but don't do anything with them.
5525 	 * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5526 	 * get flushed.  This check will just help satisfy anyone who wants
5527 	 * to see an error for an out of range LBA.
5528 	 */
5529 	if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5530 		ctl_set_lba_out_of_range(ctsio);
5531 		ctl_done((union ctl_io *)ctsio);
5532 		goto bailout;
5533 	}
5534 
5535 	/*
5536 	 * If this LUN has no backend, we can't flush the cache anyway.
5537 	 */
5538 	if (lun->backend == NULL) {
5539 		ctl_set_invalid_opcode(ctsio);
5540 		ctl_done((union ctl_io *)ctsio);
5541 		goto bailout;
5542 	}
5543 
5544 	/*
5545 	 * Check to see whether we're configured to send the SYNCHRONIZE
5546 	 * CACHE command directly to the back end.
5547 	 */
5548 	mtx_lock(&lun->lun_lock);
5549 	if ((softc->flags & CTL_FLAG_REAL_SYNC)
5550 	 && (++(lun->sync_count) >= lun->sync_interval)) {
5551 		lun->sync_count = 0;
5552 		mtx_unlock(&lun->lun_lock);
5553 		retval = lun->backend->config_write((union ctl_io *)ctsio);
5554 	} else {
5555 		mtx_unlock(&lun->lun_lock);
5556 		ctl_set_success(ctsio);
5557 		ctl_done((union ctl_io *)ctsio);
5558 	}
5559 
5560 bailout:
5561 
5562 	return (retval);
5563 }
5564 
5565 int
5566 ctl_format(struct ctl_scsiio *ctsio)
5567 {
5568 	struct scsi_format *cdb;
5569 	struct ctl_lun *lun;
5570 	int length, defect_list_len;
5571 
5572 	CTL_DEBUG_PRINT(("ctl_format\n"));
5573 
5574 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5575 
5576 	cdb = (struct scsi_format *)ctsio->cdb;
5577 
5578 	length = 0;
5579 	if (cdb->byte2 & SF_FMTDATA) {
5580 		if (cdb->byte2 & SF_LONGLIST)
5581 			length = sizeof(struct scsi_format_header_long);
5582 		else
5583 			length = sizeof(struct scsi_format_header_short);
5584 	}
5585 
5586 	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5587 	 && (length > 0)) {
5588 		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5589 		ctsio->kern_data_len = length;
5590 		ctsio->kern_total_len = length;
5591 		ctsio->kern_data_resid = 0;
5592 		ctsio->kern_rel_offset = 0;
5593 		ctsio->kern_sg_entries = 0;
5594 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5595 		ctsio->be_move_done = ctl_config_move_done;
5596 		ctl_datamove((union ctl_io *)ctsio);
5597 
5598 		return (CTL_RETVAL_COMPLETE);
5599 	}
5600 
5601 	defect_list_len = 0;
5602 
5603 	if (cdb->byte2 & SF_FMTDATA) {
5604 		if (cdb->byte2 & SF_LONGLIST) {
5605 			struct scsi_format_header_long *header;
5606 
5607 			header = (struct scsi_format_header_long *)
5608 				ctsio->kern_data_ptr;
5609 
5610 			defect_list_len = scsi_4btoul(header->defect_list_len);
5611 			if (defect_list_len != 0) {
5612 				ctl_set_invalid_field(ctsio,
5613 						      /*sks_valid*/ 1,
5614 						      /*command*/ 0,
5615 						      /*field*/ 2,
5616 						      /*bit_valid*/ 0,
5617 						      /*bit*/ 0);
5618 				goto bailout;
5619 			}
5620 		} else {
5621 			struct scsi_format_header_short *header;
5622 
5623 			header = (struct scsi_format_header_short *)
5624 				ctsio->kern_data_ptr;
5625 
5626 			defect_list_len = scsi_2btoul(header->defect_list_len);
5627 			if (defect_list_len != 0) {
5628 				ctl_set_invalid_field(ctsio,
5629 						      /*sks_valid*/ 1,
5630 						      /*command*/ 0,
5631 						      /*field*/ 2,
5632 						      /*bit_valid*/ 0,
5633 						      /*bit*/ 0);
5634 				goto bailout;
5635 			}
5636 		}
5637 	}
5638 
5639 	/*
5640 	 * The format command will clear out the "Medium format corrupted"
5641 	 * status if set by the configuration code.  That status is really
5642 	 * just a way to notify the host that we have lost the media, and
5643 	 * get them to issue a command that will basically make them think
5644 	 * they're blowing away the media.
5645 	 */
5646 	mtx_lock(&lun->lun_lock);
5647 	lun->flags &= ~CTL_LUN_INOPERABLE;
5648 	mtx_unlock(&lun->lun_lock);
5649 
5650 	ctl_set_success(ctsio);
5651 bailout:
5652 
5653 	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5654 		free(ctsio->kern_data_ptr, M_CTL);
5655 		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5656 	}
5657 
5658 	ctl_done((union ctl_io *)ctsio);
5659 	return (CTL_RETVAL_COMPLETE);
5660 }
5661 
5662 int
5663 ctl_read_buffer(struct ctl_scsiio *ctsio)
5664 {
5665 	struct scsi_read_buffer *cdb;
5666 	struct ctl_lun *lun;
5667 	int buffer_offset, len;
5668 	static uint8_t descr[4];
5669 	static uint8_t echo_descr[4] = { 0 };
5670 
5671 	CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5672 
5673 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5674 	cdb = (struct scsi_read_buffer *)ctsio->cdb;
5675 
5676 	if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA &&
5677 	    (cdb->byte2 & RWB_MODE) != RWB_MODE_ECHO_DESCR &&
5678 	    (cdb->byte2 & RWB_MODE) != RWB_MODE_DESCR) {
5679 		ctl_set_invalid_field(ctsio,
5680 				      /*sks_valid*/ 1,
5681 				      /*command*/ 1,
5682 				      /*field*/ 1,
5683 				      /*bit_valid*/ 1,
5684 				      /*bit*/ 4);
5685 		ctl_done((union ctl_io *)ctsio);
5686 		return (CTL_RETVAL_COMPLETE);
5687 	}
5688 
5689 	len = scsi_3btoul(cdb->length);
5690 	buffer_offset = scsi_3btoul(cdb->offset);
5691 
5692 	if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5693 		ctl_set_invalid_field(ctsio,
5694 				      /*sks_valid*/ 1,
5695 				      /*command*/ 1,
5696 				      /*field*/ 6,
5697 				      /*bit_valid*/ 0,
5698 				      /*bit*/ 0);
5699 		ctl_done((union ctl_io *)ctsio);
5700 		return (CTL_RETVAL_COMPLETE);
5701 	}
5702 
5703 	if ((cdb->byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5704 		descr[0] = 0;
5705 		scsi_ulto3b(CTL_WRITE_BUFFER_SIZE, &descr[1]);
5706 		ctsio->kern_data_ptr = descr;
5707 		len = min(len, sizeof(descr));
5708 	} else if ((cdb->byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5709 		ctsio->kern_data_ptr = echo_descr;
5710 		len = min(len, sizeof(echo_descr));
5711 	} else {
5712 		if (lun->write_buffer == NULL) {
5713 			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5714 			    M_CTL, M_WAITOK);
5715 		}
5716 		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5717 	}
5718 	ctsio->kern_data_len = len;
5719 	ctsio->kern_total_len = len;
5720 	ctsio->kern_data_resid = 0;
5721 	ctsio->kern_rel_offset = 0;
5722 	ctsio->kern_sg_entries = 0;
5723 	ctl_set_success(ctsio);
5724 	ctsio->be_move_done = ctl_config_move_done;
5725 	ctl_datamove((union ctl_io *)ctsio);
5726 	return (CTL_RETVAL_COMPLETE);
5727 }
5728 
5729 int
5730 ctl_write_buffer(struct ctl_scsiio *ctsio)
5731 {
5732 	struct scsi_write_buffer *cdb;
5733 	struct ctl_lun *lun;
5734 	int buffer_offset, len;
5735 
5736 	CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5737 
5738 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5739 	cdb = (struct scsi_write_buffer *)ctsio->cdb;
5740 
5741 	if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA) {
5742 		ctl_set_invalid_field(ctsio,
5743 				      /*sks_valid*/ 1,
5744 				      /*command*/ 1,
5745 				      /*field*/ 1,
5746 				      /*bit_valid*/ 1,
5747 				      /*bit*/ 4);
5748 		ctl_done((union ctl_io *)ctsio);
5749 		return (CTL_RETVAL_COMPLETE);
5750 	}
5751 
5752 	len = scsi_3btoul(cdb->length);
5753 	buffer_offset = scsi_3btoul(cdb->offset);
5754 
5755 	if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5756 		ctl_set_invalid_field(ctsio,
5757 				      /*sks_valid*/ 1,
5758 				      /*command*/ 1,
5759 				      /*field*/ 6,
5760 				      /*bit_valid*/ 0,
5761 				      /*bit*/ 0);
5762 		ctl_done((union ctl_io *)ctsio);
5763 		return (CTL_RETVAL_COMPLETE);
5764 	}
5765 
5766 	/*
5767 	 * If we've got a kernel request that hasn't been malloced yet,
5768 	 * malloc it and tell the caller the data buffer is here.
5769 	 */
5770 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5771 		if (lun->write_buffer == NULL) {
5772 			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5773 			    M_CTL, M_WAITOK);
5774 		}
5775 		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5776 		ctsio->kern_data_len = len;
5777 		ctsio->kern_total_len = len;
5778 		ctsio->kern_data_resid = 0;
5779 		ctsio->kern_rel_offset = 0;
5780 		ctsio->kern_sg_entries = 0;
5781 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5782 		ctsio->be_move_done = ctl_config_move_done;
5783 		ctl_datamove((union ctl_io *)ctsio);
5784 
5785 		return (CTL_RETVAL_COMPLETE);
5786 	}
5787 
5788 	ctl_set_success(ctsio);
5789 	ctl_done((union ctl_io *)ctsio);
5790 	return (CTL_RETVAL_COMPLETE);
5791 }
5792 
5793 int
5794 ctl_write_same(struct ctl_scsiio *ctsio)
5795 {
5796 	struct ctl_lun *lun;
5797 	struct ctl_lba_len_flags *lbalen;
5798 	uint64_t lba;
5799 	uint32_t num_blocks;
5800 	int len, retval;
5801 	uint8_t byte2;
5802 
5803 	retval = CTL_RETVAL_COMPLETE;
5804 
5805 	CTL_DEBUG_PRINT(("ctl_write_same\n"));
5806 
5807 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5808 
5809 	switch (ctsio->cdb[0]) {
5810 	case WRITE_SAME_10: {
5811 		struct scsi_write_same_10 *cdb;
5812 
5813 		cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5814 
5815 		lba = scsi_4btoul(cdb->addr);
5816 		num_blocks = scsi_2btoul(cdb->length);
5817 		byte2 = cdb->byte2;
5818 		break;
5819 	}
5820 	case WRITE_SAME_16: {
5821 		struct scsi_write_same_16 *cdb;
5822 
5823 		cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5824 
5825 		lba = scsi_8btou64(cdb->addr);
5826 		num_blocks = scsi_4btoul(cdb->length);
5827 		byte2 = cdb->byte2;
5828 		break;
5829 	}
5830 	default:
5831 		/*
5832 		 * We got a command we don't support.  This shouldn't
5833 		 * happen, commands should be filtered out above us.
5834 		 */
5835 		ctl_set_invalid_opcode(ctsio);
5836 		ctl_done((union ctl_io *)ctsio);
5837 
5838 		return (CTL_RETVAL_COMPLETE);
5839 		break; /* NOTREACHED */
5840 	}
5841 
5842 	/* NDOB and ANCHOR flags can be used only together with UNMAP */
5843 	if ((byte2 & SWS_UNMAP) == 0 &&
5844 	    (byte2 & (SWS_NDOB | SWS_ANCHOR)) != 0) {
5845 		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
5846 		    /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
5847 		ctl_done((union ctl_io *)ctsio);
5848 		return (CTL_RETVAL_COMPLETE);
5849 	}
5850 
5851 	/*
5852 	 * The first check is to make sure we're in bounds, the second
5853 	 * check is to catch wrap-around problems.  If the lba + num blocks
5854 	 * is less than the lba, then we've wrapped around and the block
5855 	 * range is invalid anyway.
5856 	 */
5857 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5858 	 || ((lba + num_blocks) < lba)) {
5859 		ctl_set_lba_out_of_range(ctsio);
5860 		ctl_done((union ctl_io *)ctsio);
5861 		return (CTL_RETVAL_COMPLETE);
5862 	}
5863 
5864 	/* Zero number of blocks means "to the last logical block" */
5865 	if (num_blocks == 0) {
5866 		if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5867 			ctl_set_invalid_field(ctsio,
5868 					      /*sks_valid*/ 0,
5869 					      /*command*/ 1,
5870 					      /*field*/ 0,
5871 					      /*bit_valid*/ 0,
5872 					      /*bit*/ 0);
5873 			ctl_done((union ctl_io *)ctsio);
5874 			return (CTL_RETVAL_COMPLETE);
5875 		}
5876 		num_blocks = (lun->be_lun->maxlba + 1) - lba;
5877 	}
5878 
5879 	len = lun->be_lun->blocksize;
5880 
5881 	/*
5882 	 * If we've got a kernel request that hasn't been malloced yet,
5883 	 * malloc it and tell the caller the data buffer is here.
5884 	 */
5885 	if ((byte2 & SWS_NDOB) == 0 &&
5886 	    (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5887 		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5888 		ctsio->kern_data_len = len;
5889 		ctsio->kern_total_len = len;
5890 		ctsio->kern_data_resid = 0;
5891 		ctsio->kern_rel_offset = 0;
5892 		ctsio->kern_sg_entries = 0;
5893 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5894 		ctsio->be_move_done = ctl_config_move_done;
5895 		ctl_datamove((union ctl_io *)ctsio);
5896 
5897 		return (CTL_RETVAL_COMPLETE);
5898 	}
5899 
5900 	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5901 	lbalen->lba = lba;
5902 	lbalen->len = num_blocks;
5903 	lbalen->flags = byte2;
5904 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5905 
5906 	return (retval);
5907 }
5908 
5909 int
5910 ctl_unmap(struct ctl_scsiio *ctsio)
5911 {
5912 	struct ctl_lun *lun;
5913 	struct scsi_unmap *cdb;
5914 	struct ctl_ptr_len_flags *ptrlen;
5915 	struct scsi_unmap_header *hdr;
5916 	struct scsi_unmap_desc *buf, *end, *endnz, *range;
5917 	uint64_t lba;
5918 	uint32_t num_blocks;
5919 	int len, retval;
5920 	uint8_t byte2;
5921 
5922 	retval = CTL_RETVAL_COMPLETE;
5923 
5924 	CTL_DEBUG_PRINT(("ctl_unmap\n"));
5925 
5926 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5927 	cdb = (struct scsi_unmap *)ctsio->cdb;
5928 
5929 	len = scsi_2btoul(cdb->length);
5930 	byte2 = cdb->byte2;
5931 
5932 	/*
5933 	 * If we've got a kernel request that hasn't been malloced yet,
5934 	 * malloc it and tell the caller the data buffer is here.
5935 	 */
5936 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5937 		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5938 		ctsio->kern_data_len = len;
5939 		ctsio->kern_total_len = len;
5940 		ctsio->kern_data_resid = 0;
5941 		ctsio->kern_rel_offset = 0;
5942 		ctsio->kern_sg_entries = 0;
5943 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5944 		ctsio->be_move_done = ctl_config_move_done;
5945 		ctl_datamove((union ctl_io *)ctsio);
5946 
5947 		return (CTL_RETVAL_COMPLETE);
5948 	}
5949 
5950 	len = ctsio->kern_total_len - ctsio->kern_data_resid;
5951 	hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
5952 	if (len < sizeof (*hdr) ||
5953 	    len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
5954 	    len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
5955 	    scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
5956 		ctl_set_invalid_field(ctsio,
5957 				      /*sks_valid*/ 0,
5958 				      /*command*/ 0,
5959 				      /*field*/ 0,
5960 				      /*bit_valid*/ 0,
5961 				      /*bit*/ 0);
5962 		goto done;
5963 	}
5964 	len = scsi_2btoul(hdr->desc_length);
5965 	buf = (struct scsi_unmap_desc *)(hdr + 1);
5966 	end = buf + len / sizeof(*buf);
5967 
5968 	endnz = buf;
5969 	for (range = buf; range < end; range++) {
5970 		lba = scsi_8btou64(range->lba);
5971 		num_blocks = scsi_4btoul(range->length);
5972 		if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5973 		 || ((lba + num_blocks) < lba)) {
5974 			ctl_set_lba_out_of_range(ctsio);
5975 			ctl_done((union ctl_io *)ctsio);
5976 			return (CTL_RETVAL_COMPLETE);
5977 		}
5978 		if (num_blocks != 0)
5979 			endnz = range + 1;
5980 	}
5981 
5982 	/*
5983 	 * Block backend can not handle zero last range.
5984 	 * Filter it out and return if there is nothing left.
5985 	 */
5986 	len = (uint8_t *)endnz - (uint8_t *)buf;
5987 	if (len == 0) {
5988 		ctl_set_success(ctsio);
5989 		goto done;
5990 	}
5991 
5992 	mtx_lock(&lun->lun_lock);
5993 	ptrlen = (struct ctl_ptr_len_flags *)
5994 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5995 	ptrlen->ptr = (void *)buf;
5996 	ptrlen->len = len;
5997 	ptrlen->flags = byte2;
5998 	ctl_check_blocked(lun);
5999 	mtx_unlock(&lun->lun_lock);
6000 
6001 	retval = lun->backend->config_write((union ctl_io *)ctsio);
6002 	return (retval);
6003 
6004 done:
6005 	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
6006 		free(ctsio->kern_data_ptr, M_CTL);
6007 		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
6008 	}
6009 	ctl_done((union ctl_io *)ctsio);
6010 	return (CTL_RETVAL_COMPLETE);
6011 }
6012 
6013 /*
6014  * Note that this function currently doesn't actually do anything inside
6015  * CTL to enforce things if the DQue bit is turned on.
6016  *
6017  * Also note that this function can't be used in the default case, because
6018  * the DQue bit isn't set in the changeable mask for the control mode page
6019  * anyway.  This is just here as an example for how to implement a page
6020  * handler, and a placeholder in case we want to allow the user to turn
6021  * tagged queueing on and off.
6022  *
6023  * The D_SENSE bit handling is functional, however, and will turn
6024  * descriptor sense on and off for a given LUN.
6025  */
6026 int
6027 ctl_control_page_handler(struct ctl_scsiio *ctsio,
6028 			 struct ctl_page_index *page_index, uint8_t *page_ptr)
6029 {
6030 	struct scsi_control_page *current_cp, *saved_cp, *user_cp;
6031 	struct ctl_lun *lun;
6032 	int set_ua;
6033 	uint32_t initidx;
6034 
6035 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6036 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6037 	set_ua = 0;
6038 
6039 	user_cp = (struct scsi_control_page *)page_ptr;
6040 	current_cp = (struct scsi_control_page *)
6041 		(page_index->page_data + (page_index->page_len *
6042 		CTL_PAGE_CURRENT));
6043 	saved_cp = (struct scsi_control_page *)
6044 		(page_index->page_data + (page_index->page_len *
6045 		CTL_PAGE_SAVED));
6046 
6047 	mtx_lock(&lun->lun_lock);
6048 	if (((current_cp->rlec & SCP_DSENSE) == 0)
6049 	 && ((user_cp->rlec & SCP_DSENSE) != 0)) {
6050 		/*
6051 		 * Descriptor sense is currently turned off and the user
6052 		 * wants to turn it on.
6053 		 */
6054 		current_cp->rlec |= SCP_DSENSE;
6055 		saved_cp->rlec |= SCP_DSENSE;
6056 		lun->flags |= CTL_LUN_SENSE_DESC;
6057 		set_ua = 1;
6058 	} else if (((current_cp->rlec & SCP_DSENSE) != 0)
6059 		&& ((user_cp->rlec & SCP_DSENSE) == 0)) {
6060 		/*
6061 		 * Descriptor sense is currently turned on, and the user
6062 		 * wants to turn it off.
6063 		 */
6064 		current_cp->rlec &= ~SCP_DSENSE;
6065 		saved_cp->rlec &= ~SCP_DSENSE;
6066 		lun->flags &= ~CTL_LUN_SENSE_DESC;
6067 		set_ua = 1;
6068 	}
6069 	if ((current_cp->queue_flags & SCP_QUEUE_ALG_MASK) !=
6070 	    (user_cp->queue_flags & SCP_QUEUE_ALG_MASK)) {
6071 		current_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
6072 		current_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
6073 		saved_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
6074 		saved_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
6075 		set_ua = 1;
6076 	}
6077 	if ((current_cp->eca_and_aen & SCP_SWP) !=
6078 	    (user_cp->eca_and_aen & SCP_SWP)) {
6079 		current_cp->eca_and_aen &= ~SCP_SWP;
6080 		current_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
6081 		saved_cp->eca_and_aen &= ~SCP_SWP;
6082 		saved_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
6083 		set_ua = 1;
6084 	}
6085 	if (set_ua != 0)
6086 		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
6087 	mtx_unlock(&lun->lun_lock);
6088 
6089 	return (0);
6090 }
6091 
6092 int
6093 ctl_caching_sp_handler(struct ctl_scsiio *ctsio,
6094 		     struct ctl_page_index *page_index, uint8_t *page_ptr)
6095 {
6096 	struct scsi_caching_page *current_cp, *saved_cp, *user_cp;
6097 	struct ctl_lun *lun;
6098 	int set_ua;
6099 	uint32_t initidx;
6100 
6101 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6102 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6103 	set_ua = 0;
6104 
6105 	user_cp = (struct scsi_caching_page *)page_ptr;
6106 	current_cp = (struct scsi_caching_page *)
6107 		(page_index->page_data + (page_index->page_len *
6108 		CTL_PAGE_CURRENT));
6109 	saved_cp = (struct scsi_caching_page *)
6110 		(page_index->page_data + (page_index->page_len *
6111 		CTL_PAGE_SAVED));
6112 
6113 	mtx_lock(&lun->lun_lock);
6114 	if ((current_cp->flags1 & (SCP_WCE | SCP_RCD)) !=
6115 	    (user_cp->flags1 & (SCP_WCE | SCP_RCD))) {
6116 		current_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6117 		current_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6118 		saved_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6119 		saved_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6120 		set_ua = 1;
6121 	}
6122 	if (set_ua != 0)
6123 		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
6124 	mtx_unlock(&lun->lun_lock);
6125 
6126 	return (0);
6127 }
6128 
6129 int
6130 ctl_debugconf_sp_select_handler(struct ctl_scsiio *ctsio,
6131 				struct ctl_page_index *page_index,
6132 				uint8_t *page_ptr)
6133 {
6134 	uint8_t *c;
6135 	int i;
6136 
6137 	c = ((struct copan_debugconf_subpage *)page_ptr)->ctl_time_io_secs;
6138 	ctl_time_io_secs =
6139 		(c[0] << 8) |
6140 		(c[1] << 0) |
6141 		0;
6142 	CTL_DEBUG_PRINT(("set ctl_time_io_secs to %d\n", ctl_time_io_secs));
6143 	printf("set ctl_time_io_secs to %d\n", ctl_time_io_secs);
6144 	printf("page data:");
6145 	for (i=0; i<8; i++)
6146 		printf(" %.2x",page_ptr[i]);
6147 	printf("\n");
6148 	return (0);
6149 }
6150 
6151 int
6152 ctl_debugconf_sp_sense_handler(struct ctl_scsiio *ctsio,
6153 			       struct ctl_page_index *page_index,
6154 			       int pc)
6155 {
6156 	struct copan_debugconf_subpage *page;
6157 
6158 	page = (struct copan_debugconf_subpage *)page_index->page_data +
6159 		(page_index->page_len * pc);
6160 
6161 	switch (pc) {
6162 	case SMS_PAGE_CTRL_CHANGEABLE >> 6:
6163 	case SMS_PAGE_CTRL_DEFAULT >> 6:
6164 	case SMS_PAGE_CTRL_SAVED >> 6:
6165 		/*
6166 		 * We don't update the changable or default bits for this page.
6167 		 */
6168 		break;
6169 	case SMS_PAGE_CTRL_CURRENT >> 6:
6170 		page->ctl_time_io_secs[0] = ctl_time_io_secs >> 8;
6171 		page->ctl_time_io_secs[1] = ctl_time_io_secs >> 0;
6172 		break;
6173 	default:
6174 #ifdef NEEDTOPORT
6175 		EPRINT(0, "Invalid PC %d!!", pc);
6176 #endif /* NEEDTOPORT */
6177 		break;
6178 	}
6179 	return (0);
6180 }
6181 
6182 
6183 static int
6184 ctl_do_mode_select(union ctl_io *io)
6185 {
6186 	struct scsi_mode_page_header *page_header;
6187 	struct ctl_page_index *page_index;
6188 	struct ctl_scsiio *ctsio;
6189 	int control_dev, page_len;
6190 	int page_len_offset, page_len_size;
6191 	union ctl_modepage_info *modepage_info;
6192 	struct ctl_lun *lun;
6193 	int *len_left, *len_used;
6194 	int retval, i;
6195 
6196 	ctsio = &io->scsiio;
6197 	page_index = NULL;
6198 	page_len = 0;
6199 	retval = CTL_RETVAL_COMPLETE;
6200 
6201 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6202 
6203 	if (lun->be_lun->lun_type != T_DIRECT)
6204 		control_dev = 1;
6205 	else
6206 		control_dev = 0;
6207 
6208 	modepage_info = (union ctl_modepage_info *)
6209 		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6210 	len_left = &modepage_info->header.len_left;
6211 	len_used = &modepage_info->header.len_used;
6212 
6213 do_next_page:
6214 
6215 	page_header = (struct scsi_mode_page_header *)
6216 		(ctsio->kern_data_ptr + *len_used);
6217 
6218 	if (*len_left == 0) {
6219 		free(ctsio->kern_data_ptr, M_CTL);
6220 		ctl_set_success(ctsio);
6221 		ctl_done((union ctl_io *)ctsio);
6222 		return (CTL_RETVAL_COMPLETE);
6223 	} else if (*len_left < sizeof(struct scsi_mode_page_header)) {
6224 
6225 		free(ctsio->kern_data_ptr, M_CTL);
6226 		ctl_set_param_len_error(ctsio);
6227 		ctl_done((union ctl_io *)ctsio);
6228 		return (CTL_RETVAL_COMPLETE);
6229 
6230 	} else if ((page_header->page_code & SMPH_SPF)
6231 		&& (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
6232 
6233 		free(ctsio->kern_data_ptr, M_CTL);
6234 		ctl_set_param_len_error(ctsio);
6235 		ctl_done((union ctl_io *)ctsio);
6236 		return (CTL_RETVAL_COMPLETE);
6237 	}
6238 
6239 
6240 	/*
6241 	 * XXX KDM should we do something with the block descriptor?
6242 	 */
6243 	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6244 
6245 		if ((control_dev != 0)
6246 		 && (lun->mode_pages.index[i].page_flags &
6247 		     CTL_PAGE_FLAG_DISK_ONLY))
6248 			continue;
6249 
6250 		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
6251 		    (page_header->page_code & SMPH_PC_MASK))
6252 			continue;
6253 
6254 		/*
6255 		 * If neither page has a subpage code, then we've got a
6256 		 * match.
6257 		 */
6258 		if (((lun->mode_pages.index[i].page_code & SMPH_SPF) == 0)
6259 		 && ((page_header->page_code & SMPH_SPF) == 0)) {
6260 			page_index = &lun->mode_pages.index[i];
6261 			page_len = page_header->page_length;
6262 			break;
6263 		}
6264 
6265 		/*
6266 		 * If both pages have subpages, then the subpage numbers
6267 		 * have to match.
6268 		 */
6269 		if ((lun->mode_pages.index[i].page_code & SMPH_SPF)
6270 		  && (page_header->page_code & SMPH_SPF)) {
6271 			struct scsi_mode_page_header_sp *sph;
6272 
6273 			sph = (struct scsi_mode_page_header_sp *)page_header;
6274 
6275 			if (lun->mode_pages.index[i].subpage ==
6276 			    sph->subpage) {
6277 				page_index = &lun->mode_pages.index[i];
6278 				page_len = scsi_2btoul(sph->page_length);
6279 				break;
6280 			}
6281 		}
6282 	}
6283 
6284 	/*
6285 	 * If we couldn't find the page, or if we don't have a mode select
6286 	 * handler for it, send back an error to the user.
6287 	 */
6288 	if ((page_index == NULL)
6289 	 || (page_index->select_handler == NULL)) {
6290 		ctl_set_invalid_field(ctsio,
6291 				      /*sks_valid*/ 1,
6292 				      /*command*/ 0,
6293 				      /*field*/ *len_used,
6294 				      /*bit_valid*/ 0,
6295 				      /*bit*/ 0);
6296 		free(ctsio->kern_data_ptr, M_CTL);
6297 		ctl_done((union ctl_io *)ctsio);
6298 		return (CTL_RETVAL_COMPLETE);
6299 	}
6300 
6301 	if (page_index->page_code & SMPH_SPF) {
6302 		page_len_offset = 2;
6303 		page_len_size = 2;
6304 	} else {
6305 		page_len_size = 1;
6306 		page_len_offset = 1;
6307 	}
6308 
6309 	/*
6310 	 * If the length the initiator gives us isn't the one we specify in
6311 	 * the mode page header, or if they didn't specify enough data in
6312 	 * the CDB to avoid truncating this page, kick out the request.
6313 	 */
6314 	if ((page_len != (page_index->page_len - page_len_offset -
6315 			  page_len_size))
6316 	 || (*len_left < page_index->page_len)) {
6317 
6318 
6319 		ctl_set_invalid_field(ctsio,
6320 				      /*sks_valid*/ 1,
6321 				      /*command*/ 0,
6322 				      /*field*/ *len_used + page_len_offset,
6323 				      /*bit_valid*/ 0,
6324 				      /*bit*/ 0);
6325 		free(ctsio->kern_data_ptr, M_CTL);
6326 		ctl_done((union ctl_io *)ctsio);
6327 		return (CTL_RETVAL_COMPLETE);
6328 	}
6329 
6330 	/*
6331 	 * Run through the mode page, checking to make sure that the bits
6332 	 * the user changed are actually legal for him to change.
6333 	 */
6334 	for (i = 0; i < page_index->page_len; i++) {
6335 		uint8_t *user_byte, *change_mask, *current_byte;
6336 		int bad_bit;
6337 		int j;
6338 
6339 		user_byte = (uint8_t *)page_header + i;
6340 		change_mask = page_index->page_data +
6341 			      (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6342 		current_byte = page_index->page_data +
6343 			       (page_index->page_len * CTL_PAGE_CURRENT) + i;
6344 
6345 		/*
6346 		 * Check to see whether the user set any bits in this byte
6347 		 * that he is not allowed to set.
6348 		 */
6349 		if ((*user_byte & ~(*change_mask)) ==
6350 		    (*current_byte & ~(*change_mask)))
6351 			continue;
6352 
6353 		/*
6354 		 * Go through bit by bit to determine which one is illegal.
6355 		 */
6356 		bad_bit = 0;
6357 		for (j = 7; j >= 0; j--) {
6358 			if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6359 			    (((1 << i) & ~(*change_mask)) & *current_byte)) {
6360 				bad_bit = i;
6361 				break;
6362 			}
6363 		}
6364 		ctl_set_invalid_field(ctsio,
6365 				      /*sks_valid*/ 1,
6366 				      /*command*/ 0,
6367 				      /*field*/ *len_used + i,
6368 				      /*bit_valid*/ 1,
6369 				      /*bit*/ bad_bit);
6370 		free(ctsio->kern_data_ptr, M_CTL);
6371 		ctl_done((union ctl_io *)ctsio);
6372 		return (CTL_RETVAL_COMPLETE);
6373 	}
6374 
6375 	/*
6376 	 * Decrement these before we call the page handler, since we may
6377 	 * end up getting called back one way or another before the handler
6378 	 * returns to this context.
6379 	 */
6380 	*len_left -= page_index->page_len;
6381 	*len_used += page_index->page_len;
6382 
6383 	retval = page_index->select_handler(ctsio, page_index,
6384 					    (uint8_t *)page_header);
6385 
6386 	/*
6387 	 * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6388 	 * wait until this queued command completes to finish processing
6389 	 * the mode page.  If it returns anything other than
6390 	 * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6391 	 * already set the sense information, freed the data pointer, and
6392 	 * completed the io for us.
6393 	 */
6394 	if (retval != CTL_RETVAL_COMPLETE)
6395 		goto bailout_no_done;
6396 
6397 	/*
6398 	 * If the initiator sent us more than one page, parse the next one.
6399 	 */
6400 	if (*len_left > 0)
6401 		goto do_next_page;
6402 
6403 	ctl_set_success(ctsio);
6404 	free(ctsio->kern_data_ptr, M_CTL);
6405 	ctl_done((union ctl_io *)ctsio);
6406 
6407 bailout_no_done:
6408 
6409 	return (CTL_RETVAL_COMPLETE);
6410 
6411 }
6412 
6413 int
6414 ctl_mode_select(struct ctl_scsiio *ctsio)
6415 {
6416 	int param_len, pf, sp;
6417 	int header_size, bd_len;
6418 	int len_left, len_used;
6419 	struct ctl_page_index *page_index;
6420 	struct ctl_lun *lun;
6421 	int control_dev, page_len;
6422 	union ctl_modepage_info *modepage_info;
6423 	int retval;
6424 
6425 	pf = 0;
6426 	sp = 0;
6427 	page_len = 0;
6428 	len_used = 0;
6429 	len_left = 0;
6430 	retval = 0;
6431 	bd_len = 0;
6432 	page_index = NULL;
6433 
6434 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6435 
6436 	if (lun->be_lun->lun_type != T_DIRECT)
6437 		control_dev = 1;
6438 	else
6439 		control_dev = 0;
6440 
6441 	switch (ctsio->cdb[0]) {
6442 	case MODE_SELECT_6: {
6443 		struct scsi_mode_select_6 *cdb;
6444 
6445 		cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6446 
6447 		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6448 		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6449 
6450 		param_len = cdb->length;
6451 		header_size = sizeof(struct scsi_mode_header_6);
6452 		break;
6453 	}
6454 	case MODE_SELECT_10: {
6455 		struct scsi_mode_select_10 *cdb;
6456 
6457 		cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6458 
6459 		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6460 		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6461 
6462 		param_len = scsi_2btoul(cdb->length);
6463 		header_size = sizeof(struct scsi_mode_header_10);
6464 		break;
6465 	}
6466 	default:
6467 		ctl_set_invalid_opcode(ctsio);
6468 		ctl_done((union ctl_io *)ctsio);
6469 		return (CTL_RETVAL_COMPLETE);
6470 		break; /* NOTREACHED */
6471 	}
6472 
6473 	/*
6474 	 * From SPC-3:
6475 	 * "A parameter list length of zero indicates that the Data-Out Buffer
6476 	 * shall be empty. This condition shall not be considered as an error."
6477 	 */
6478 	if (param_len == 0) {
6479 		ctl_set_success(ctsio);
6480 		ctl_done((union ctl_io *)ctsio);
6481 		return (CTL_RETVAL_COMPLETE);
6482 	}
6483 
6484 	/*
6485 	 * Since we'll hit this the first time through, prior to
6486 	 * allocation, we don't need to free a data buffer here.
6487 	 */
6488 	if (param_len < header_size) {
6489 		ctl_set_param_len_error(ctsio);
6490 		ctl_done((union ctl_io *)ctsio);
6491 		return (CTL_RETVAL_COMPLETE);
6492 	}
6493 
6494 	/*
6495 	 * Allocate the data buffer and grab the user's data.  In theory,
6496 	 * we shouldn't have to sanity check the parameter list length here
6497 	 * because the maximum size is 64K.  We should be able to malloc
6498 	 * that much without too many problems.
6499 	 */
6500 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6501 		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6502 		ctsio->kern_data_len = param_len;
6503 		ctsio->kern_total_len = param_len;
6504 		ctsio->kern_data_resid = 0;
6505 		ctsio->kern_rel_offset = 0;
6506 		ctsio->kern_sg_entries = 0;
6507 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6508 		ctsio->be_move_done = ctl_config_move_done;
6509 		ctl_datamove((union ctl_io *)ctsio);
6510 
6511 		return (CTL_RETVAL_COMPLETE);
6512 	}
6513 
6514 	switch (ctsio->cdb[0]) {
6515 	case MODE_SELECT_6: {
6516 		struct scsi_mode_header_6 *mh6;
6517 
6518 		mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6519 		bd_len = mh6->blk_desc_len;
6520 		break;
6521 	}
6522 	case MODE_SELECT_10: {
6523 		struct scsi_mode_header_10 *mh10;
6524 
6525 		mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6526 		bd_len = scsi_2btoul(mh10->blk_desc_len);
6527 		break;
6528 	}
6529 	default:
6530 		panic("Invalid CDB type %#x", ctsio->cdb[0]);
6531 		break;
6532 	}
6533 
6534 	if (param_len < (header_size + bd_len)) {
6535 		free(ctsio->kern_data_ptr, M_CTL);
6536 		ctl_set_param_len_error(ctsio);
6537 		ctl_done((union ctl_io *)ctsio);
6538 		return (CTL_RETVAL_COMPLETE);
6539 	}
6540 
6541 	/*
6542 	 * Set the IO_CONT flag, so that if this I/O gets passed to
6543 	 * ctl_config_write_done(), it'll get passed back to
6544 	 * ctl_do_mode_select() for further processing, or completion if
6545 	 * we're all done.
6546 	 */
6547 	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6548 	ctsio->io_cont = ctl_do_mode_select;
6549 
6550 	modepage_info = (union ctl_modepage_info *)
6551 		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6552 
6553 	memset(modepage_info, 0, sizeof(*modepage_info));
6554 
6555 	len_left = param_len - header_size - bd_len;
6556 	len_used = header_size + bd_len;
6557 
6558 	modepage_info->header.len_left = len_left;
6559 	modepage_info->header.len_used = len_used;
6560 
6561 	return (ctl_do_mode_select((union ctl_io *)ctsio));
6562 }
6563 
6564 int
6565 ctl_mode_sense(struct ctl_scsiio *ctsio)
6566 {
6567 	struct ctl_lun *lun;
6568 	int pc, page_code, dbd, llba, subpage;
6569 	int alloc_len, page_len, header_len, total_len;
6570 	struct scsi_mode_block_descr *block_desc;
6571 	struct ctl_page_index *page_index;
6572 	int control_dev;
6573 
6574 	dbd = 0;
6575 	llba = 0;
6576 	block_desc = NULL;
6577 	page_index = NULL;
6578 
6579 	CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6580 
6581 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6582 
6583 	if (lun->be_lun->lun_type != T_DIRECT)
6584 		control_dev = 1;
6585 	else
6586 		control_dev = 0;
6587 
6588 	switch (ctsio->cdb[0]) {
6589 	case MODE_SENSE_6: {
6590 		struct scsi_mode_sense_6 *cdb;
6591 
6592 		cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6593 
6594 		header_len = sizeof(struct scsi_mode_hdr_6);
6595 		if (cdb->byte2 & SMS_DBD)
6596 			dbd = 1;
6597 		else
6598 			header_len += sizeof(struct scsi_mode_block_descr);
6599 
6600 		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6601 		page_code = cdb->page & SMS_PAGE_CODE;
6602 		subpage = cdb->subpage;
6603 		alloc_len = cdb->length;
6604 		break;
6605 	}
6606 	case MODE_SENSE_10: {
6607 		struct scsi_mode_sense_10 *cdb;
6608 
6609 		cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6610 
6611 		header_len = sizeof(struct scsi_mode_hdr_10);
6612 
6613 		if (cdb->byte2 & SMS_DBD)
6614 			dbd = 1;
6615 		else
6616 			header_len += sizeof(struct scsi_mode_block_descr);
6617 		if (cdb->byte2 & SMS10_LLBAA)
6618 			llba = 1;
6619 		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6620 		page_code = cdb->page & SMS_PAGE_CODE;
6621 		subpage = cdb->subpage;
6622 		alloc_len = scsi_2btoul(cdb->length);
6623 		break;
6624 	}
6625 	default:
6626 		ctl_set_invalid_opcode(ctsio);
6627 		ctl_done((union ctl_io *)ctsio);
6628 		return (CTL_RETVAL_COMPLETE);
6629 		break; /* NOTREACHED */
6630 	}
6631 
6632 	/*
6633 	 * We have to make a first pass through to calculate the size of
6634 	 * the pages that match the user's query.  Then we allocate enough
6635 	 * memory to hold it, and actually copy the data into the buffer.
6636 	 */
6637 	switch (page_code) {
6638 	case SMS_ALL_PAGES_PAGE: {
6639 		int i;
6640 
6641 		page_len = 0;
6642 
6643 		/*
6644 		 * At the moment, values other than 0 and 0xff here are
6645 		 * reserved according to SPC-3.
6646 		 */
6647 		if ((subpage != SMS_SUBPAGE_PAGE_0)
6648 		 && (subpage != SMS_SUBPAGE_ALL)) {
6649 			ctl_set_invalid_field(ctsio,
6650 					      /*sks_valid*/ 1,
6651 					      /*command*/ 1,
6652 					      /*field*/ 3,
6653 					      /*bit_valid*/ 0,
6654 					      /*bit*/ 0);
6655 			ctl_done((union ctl_io *)ctsio);
6656 			return (CTL_RETVAL_COMPLETE);
6657 		}
6658 
6659 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6660 			if ((control_dev != 0)
6661 			 && (lun->mode_pages.index[i].page_flags &
6662 			     CTL_PAGE_FLAG_DISK_ONLY))
6663 				continue;
6664 
6665 			/*
6666 			 * We don't use this subpage if the user didn't
6667 			 * request all subpages.
6668 			 */
6669 			if ((lun->mode_pages.index[i].subpage != 0)
6670 			 && (subpage == SMS_SUBPAGE_PAGE_0))
6671 				continue;
6672 
6673 #if 0
6674 			printf("found page %#x len %d\n",
6675 			       lun->mode_pages.index[i].page_code &
6676 			       SMPH_PC_MASK,
6677 			       lun->mode_pages.index[i].page_len);
6678 #endif
6679 			page_len += lun->mode_pages.index[i].page_len;
6680 		}
6681 		break;
6682 	}
6683 	default: {
6684 		int i;
6685 
6686 		page_len = 0;
6687 
6688 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6689 			/* Look for the right page code */
6690 			if ((lun->mode_pages.index[i].page_code &
6691 			     SMPH_PC_MASK) != page_code)
6692 				continue;
6693 
6694 			/* Look for the right subpage or the subpage wildcard*/
6695 			if ((lun->mode_pages.index[i].subpage != subpage)
6696 			 && (subpage != SMS_SUBPAGE_ALL))
6697 				continue;
6698 
6699 			/* Make sure the page is supported for this dev type */
6700 			if ((control_dev != 0)
6701 			 && (lun->mode_pages.index[i].page_flags &
6702 			     CTL_PAGE_FLAG_DISK_ONLY))
6703 				continue;
6704 
6705 #if 0
6706 			printf("found page %#x len %d\n",
6707 			       lun->mode_pages.index[i].page_code &
6708 			       SMPH_PC_MASK,
6709 			       lun->mode_pages.index[i].page_len);
6710 #endif
6711 
6712 			page_len += lun->mode_pages.index[i].page_len;
6713 		}
6714 
6715 		if (page_len == 0) {
6716 			ctl_set_invalid_field(ctsio,
6717 					      /*sks_valid*/ 1,
6718 					      /*command*/ 1,
6719 					      /*field*/ 2,
6720 					      /*bit_valid*/ 1,
6721 					      /*bit*/ 5);
6722 			ctl_done((union ctl_io *)ctsio);
6723 			return (CTL_RETVAL_COMPLETE);
6724 		}
6725 		break;
6726 	}
6727 	}
6728 
6729 	total_len = header_len + page_len;
6730 #if 0
6731 	printf("header_len = %d, page_len = %d, total_len = %d\n",
6732 	       header_len, page_len, total_len);
6733 #endif
6734 
6735 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6736 	ctsio->kern_sg_entries = 0;
6737 	ctsio->kern_data_resid = 0;
6738 	ctsio->kern_rel_offset = 0;
6739 	if (total_len < alloc_len) {
6740 		ctsio->residual = alloc_len - total_len;
6741 		ctsio->kern_data_len = total_len;
6742 		ctsio->kern_total_len = total_len;
6743 	} else {
6744 		ctsio->residual = 0;
6745 		ctsio->kern_data_len = alloc_len;
6746 		ctsio->kern_total_len = alloc_len;
6747 	}
6748 
6749 	switch (ctsio->cdb[0]) {
6750 	case MODE_SENSE_6: {
6751 		struct scsi_mode_hdr_6 *header;
6752 
6753 		header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6754 
6755 		header->datalen = MIN(total_len - 1, 254);
6756 		if (control_dev == 0) {
6757 			header->dev_specific = 0x10; /* DPOFUA */
6758 			if ((lun->flags & CTL_LUN_READONLY) ||
6759 			    (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6760 			    .eca_and_aen & SCP_SWP) != 0)
6761 				    header->dev_specific |= 0x80; /* WP */
6762 		}
6763 		if (dbd)
6764 			header->block_descr_len = 0;
6765 		else
6766 			header->block_descr_len =
6767 				sizeof(struct scsi_mode_block_descr);
6768 		block_desc = (struct scsi_mode_block_descr *)&header[1];
6769 		break;
6770 	}
6771 	case MODE_SENSE_10: {
6772 		struct scsi_mode_hdr_10 *header;
6773 		int datalen;
6774 
6775 		header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6776 
6777 		datalen = MIN(total_len - 2, 65533);
6778 		scsi_ulto2b(datalen, header->datalen);
6779 		if (control_dev == 0) {
6780 			header->dev_specific = 0x10; /* DPOFUA */
6781 			if ((lun->flags & CTL_LUN_READONLY) ||
6782 			    (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6783 			    .eca_and_aen & SCP_SWP) != 0)
6784 				    header->dev_specific |= 0x80; /* WP */
6785 		}
6786 		if (dbd)
6787 			scsi_ulto2b(0, header->block_descr_len);
6788 		else
6789 			scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
6790 				    header->block_descr_len);
6791 		block_desc = (struct scsi_mode_block_descr *)&header[1];
6792 		break;
6793 	}
6794 	default:
6795 		panic("invalid CDB type %#x", ctsio->cdb[0]);
6796 		break; /* NOTREACHED */
6797 	}
6798 
6799 	/*
6800 	 * If we've got a disk, use its blocksize in the block
6801 	 * descriptor.  Otherwise, just set it to 0.
6802 	 */
6803 	if (dbd == 0) {
6804 		if (control_dev == 0)
6805 			scsi_ulto3b(lun->be_lun->blocksize,
6806 				    block_desc->block_len);
6807 		else
6808 			scsi_ulto3b(0, block_desc->block_len);
6809 	}
6810 
6811 	switch (page_code) {
6812 	case SMS_ALL_PAGES_PAGE: {
6813 		int i, data_used;
6814 
6815 		data_used = header_len;
6816 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6817 			struct ctl_page_index *page_index;
6818 
6819 			page_index = &lun->mode_pages.index[i];
6820 
6821 			if ((control_dev != 0)
6822 			 && (page_index->page_flags &
6823 			    CTL_PAGE_FLAG_DISK_ONLY))
6824 				continue;
6825 
6826 			/*
6827 			 * We don't use this subpage if the user didn't
6828 			 * request all subpages.  We already checked (above)
6829 			 * to make sure the user only specified a subpage
6830 			 * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
6831 			 */
6832 			if ((page_index->subpage != 0)
6833 			 && (subpage == SMS_SUBPAGE_PAGE_0))
6834 				continue;
6835 
6836 			/*
6837 			 * Call the handler, if it exists, to update the
6838 			 * page to the latest values.
6839 			 */
6840 			if (page_index->sense_handler != NULL)
6841 				page_index->sense_handler(ctsio, page_index,pc);
6842 
6843 			memcpy(ctsio->kern_data_ptr + data_used,
6844 			       page_index->page_data +
6845 			       (page_index->page_len * pc),
6846 			       page_index->page_len);
6847 			data_used += page_index->page_len;
6848 		}
6849 		break;
6850 	}
6851 	default: {
6852 		int i, data_used;
6853 
6854 		data_used = header_len;
6855 
6856 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6857 			struct ctl_page_index *page_index;
6858 
6859 			page_index = &lun->mode_pages.index[i];
6860 
6861 			/* Look for the right page code */
6862 			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6863 				continue;
6864 
6865 			/* Look for the right subpage or the subpage wildcard*/
6866 			if ((page_index->subpage != subpage)
6867 			 && (subpage != SMS_SUBPAGE_ALL))
6868 				continue;
6869 
6870 			/* Make sure the page is supported for this dev type */
6871 			if ((control_dev != 0)
6872 			 && (page_index->page_flags &
6873 			     CTL_PAGE_FLAG_DISK_ONLY))
6874 				continue;
6875 
6876 			/*
6877 			 * Call the handler, if it exists, to update the
6878 			 * page to the latest values.
6879 			 */
6880 			if (page_index->sense_handler != NULL)
6881 				page_index->sense_handler(ctsio, page_index,pc);
6882 
6883 			memcpy(ctsio->kern_data_ptr + data_used,
6884 			       page_index->page_data +
6885 			       (page_index->page_len * pc),
6886 			       page_index->page_len);
6887 			data_used += page_index->page_len;
6888 		}
6889 		break;
6890 	}
6891 	}
6892 
6893 	ctl_set_success(ctsio);
6894 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6895 	ctsio->be_move_done = ctl_config_move_done;
6896 	ctl_datamove((union ctl_io *)ctsio);
6897 	return (CTL_RETVAL_COMPLETE);
6898 }
6899 
6900 int
6901 ctl_lbp_log_sense_handler(struct ctl_scsiio *ctsio,
6902 			       struct ctl_page_index *page_index,
6903 			       int pc)
6904 {
6905 	struct ctl_lun *lun;
6906 	struct scsi_log_param_header *phdr;
6907 	uint8_t *data;
6908 	uint64_t val;
6909 
6910 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6911 	data = page_index->page_data;
6912 
6913 	if (lun->backend->lun_attr != NULL &&
6914 	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksavail"))
6915 	     != UINT64_MAX) {
6916 		phdr = (struct scsi_log_param_header *)data;
6917 		scsi_ulto2b(0x0001, phdr->param_code);
6918 		phdr->param_control = SLP_LBIN | SLP_LP;
6919 		phdr->param_len = 8;
6920 		data = (uint8_t *)(phdr + 1);
6921 		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6922 		data[4] = 0x02; /* per-pool */
6923 		data += phdr->param_len;
6924 	}
6925 
6926 	if (lun->backend->lun_attr != NULL &&
6927 	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksused"))
6928 	     != UINT64_MAX) {
6929 		phdr = (struct scsi_log_param_header *)data;
6930 		scsi_ulto2b(0x0002, phdr->param_code);
6931 		phdr->param_control = SLP_LBIN | SLP_LP;
6932 		phdr->param_len = 8;
6933 		data = (uint8_t *)(phdr + 1);
6934 		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6935 		data[4] = 0x01; /* per-LUN */
6936 		data += phdr->param_len;
6937 	}
6938 
6939 	if (lun->backend->lun_attr != NULL &&
6940 	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksavail"))
6941 	     != UINT64_MAX) {
6942 		phdr = (struct scsi_log_param_header *)data;
6943 		scsi_ulto2b(0x00f1, phdr->param_code);
6944 		phdr->param_control = SLP_LBIN | SLP_LP;
6945 		phdr->param_len = 8;
6946 		data = (uint8_t *)(phdr + 1);
6947 		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6948 		data[4] = 0x02; /* per-pool */
6949 		data += phdr->param_len;
6950 	}
6951 
6952 	if (lun->backend->lun_attr != NULL &&
6953 	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksused"))
6954 	     != UINT64_MAX) {
6955 		phdr = (struct scsi_log_param_header *)data;
6956 		scsi_ulto2b(0x00f2, phdr->param_code);
6957 		phdr->param_control = SLP_LBIN | SLP_LP;
6958 		phdr->param_len = 8;
6959 		data = (uint8_t *)(phdr + 1);
6960 		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6961 		data[4] = 0x02; /* per-pool */
6962 		data += phdr->param_len;
6963 	}
6964 
6965 	page_index->page_len = data - page_index->page_data;
6966 	return (0);
6967 }
6968 
6969 int
6970 ctl_log_sense(struct ctl_scsiio *ctsio)
6971 {
6972 	struct ctl_lun *lun;
6973 	int i, pc, page_code, subpage;
6974 	int alloc_len, total_len;
6975 	struct ctl_page_index *page_index;
6976 	struct scsi_log_sense *cdb;
6977 	struct scsi_log_header *header;
6978 
6979 	CTL_DEBUG_PRINT(("ctl_log_sense\n"));
6980 
6981 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6982 	cdb = (struct scsi_log_sense *)ctsio->cdb;
6983 	pc = (cdb->page & SLS_PAGE_CTRL_MASK) >> 6;
6984 	page_code = cdb->page & SLS_PAGE_CODE;
6985 	subpage = cdb->subpage;
6986 	alloc_len = scsi_2btoul(cdb->length);
6987 
6988 	page_index = NULL;
6989 	for (i = 0; i < CTL_NUM_LOG_PAGES; i++) {
6990 		page_index = &lun->log_pages.index[i];
6991 
6992 		/* Look for the right page code */
6993 		if ((page_index->page_code & SL_PAGE_CODE) != page_code)
6994 			continue;
6995 
6996 		/* Look for the right subpage or the subpage wildcard*/
6997 		if (page_index->subpage != subpage)
6998 			continue;
6999 
7000 		break;
7001 	}
7002 	if (i >= CTL_NUM_LOG_PAGES) {
7003 		ctl_set_invalid_field(ctsio,
7004 				      /*sks_valid*/ 1,
7005 				      /*command*/ 1,
7006 				      /*field*/ 2,
7007 				      /*bit_valid*/ 0,
7008 				      /*bit*/ 0);
7009 		ctl_done((union ctl_io *)ctsio);
7010 		return (CTL_RETVAL_COMPLETE);
7011 	}
7012 
7013 	total_len = sizeof(struct scsi_log_header) + page_index->page_len;
7014 
7015 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7016 	ctsio->kern_sg_entries = 0;
7017 	ctsio->kern_data_resid = 0;
7018 	ctsio->kern_rel_offset = 0;
7019 	if (total_len < alloc_len) {
7020 		ctsio->residual = alloc_len - total_len;
7021 		ctsio->kern_data_len = total_len;
7022 		ctsio->kern_total_len = total_len;
7023 	} else {
7024 		ctsio->residual = 0;
7025 		ctsio->kern_data_len = alloc_len;
7026 		ctsio->kern_total_len = alloc_len;
7027 	}
7028 
7029 	header = (struct scsi_log_header *)ctsio->kern_data_ptr;
7030 	header->page = page_index->page_code;
7031 	if (page_index->subpage) {
7032 		header->page |= SL_SPF;
7033 		header->subpage = page_index->subpage;
7034 	}
7035 	scsi_ulto2b(page_index->page_len, header->datalen);
7036 
7037 	/*
7038 	 * Call the handler, if it exists, to update the
7039 	 * page to the latest values.
7040 	 */
7041 	if (page_index->sense_handler != NULL)
7042 		page_index->sense_handler(ctsio, page_index, pc);
7043 
7044 	memcpy(header + 1, page_index->page_data, page_index->page_len);
7045 
7046 	ctl_set_success(ctsio);
7047 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7048 	ctsio->be_move_done = ctl_config_move_done;
7049 	ctl_datamove((union ctl_io *)ctsio);
7050 	return (CTL_RETVAL_COMPLETE);
7051 }
7052 
7053 int
7054 ctl_read_capacity(struct ctl_scsiio *ctsio)
7055 {
7056 	struct scsi_read_capacity *cdb;
7057 	struct scsi_read_capacity_data *data;
7058 	struct ctl_lun *lun;
7059 	uint32_t lba;
7060 
7061 	CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
7062 
7063 	cdb = (struct scsi_read_capacity *)ctsio->cdb;
7064 
7065 	lba = scsi_4btoul(cdb->addr);
7066 	if (((cdb->pmi & SRC_PMI) == 0)
7067 	 && (lba != 0)) {
7068 		ctl_set_invalid_field(/*ctsio*/ ctsio,
7069 				      /*sks_valid*/ 1,
7070 				      /*command*/ 1,
7071 				      /*field*/ 2,
7072 				      /*bit_valid*/ 0,
7073 				      /*bit*/ 0);
7074 		ctl_done((union ctl_io *)ctsio);
7075 		return (CTL_RETVAL_COMPLETE);
7076 	}
7077 
7078 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7079 
7080 	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7081 	data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
7082 	ctsio->residual = 0;
7083 	ctsio->kern_data_len = sizeof(*data);
7084 	ctsio->kern_total_len = sizeof(*data);
7085 	ctsio->kern_data_resid = 0;
7086 	ctsio->kern_rel_offset = 0;
7087 	ctsio->kern_sg_entries = 0;
7088 
7089 	/*
7090 	 * If the maximum LBA is greater than 0xfffffffe, the user must
7091 	 * issue a SERVICE ACTION IN (16) command, with the read capacity
7092 	 * serivce action set.
7093 	 */
7094 	if (lun->be_lun->maxlba > 0xfffffffe)
7095 		scsi_ulto4b(0xffffffff, data->addr);
7096 	else
7097 		scsi_ulto4b(lun->be_lun->maxlba, data->addr);
7098 
7099 	/*
7100 	 * XXX KDM this may not be 512 bytes...
7101 	 */
7102 	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7103 
7104 	ctl_set_success(ctsio);
7105 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7106 	ctsio->be_move_done = ctl_config_move_done;
7107 	ctl_datamove((union ctl_io *)ctsio);
7108 	return (CTL_RETVAL_COMPLETE);
7109 }
7110 
7111 int
7112 ctl_read_capacity_16(struct ctl_scsiio *ctsio)
7113 {
7114 	struct scsi_read_capacity_16 *cdb;
7115 	struct scsi_read_capacity_data_long *data;
7116 	struct ctl_lun *lun;
7117 	uint64_t lba;
7118 	uint32_t alloc_len;
7119 
7120 	CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
7121 
7122 	cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
7123 
7124 	alloc_len = scsi_4btoul(cdb->alloc_len);
7125 	lba = scsi_8btou64(cdb->addr);
7126 
7127 	if ((cdb->reladr & SRC16_PMI)
7128 	 && (lba != 0)) {
7129 		ctl_set_invalid_field(/*ctsio*/ ctsio,
7130 				      /*sks_valid*/ 1,
7131 				      /*command*/ 1,
7132 				      /*field*/ 2,
7133 				      /*bit_valid*/ 0,
7134 				      /*bit*/ 0);
7135 		ctl_done((union ctl_io *)ctsio);
7136 		return (CTL_RETVAL_COMPLETE);
7137 	}
7138 
7139 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7140 
7141 	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7142 	data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
7143 
7144 	if (sizeof(*data) < alloc_len) {
7145 		ctsio->residual = alloc_len - sizeof(*data);
7146 		ctsio->kern_data_len = sizeof(*data);
7147 		ctsio->kern_total_len = sizeof(*data);
7148 	} else {
7149 		ctsio->residual = 0;
7150 		ctsio->kern_data_len = alloc_len;
7151 		ctsio->kern_total_len = alloc_len;
7152 	}
7153 	ctsio->kern_data_resid = 0;
7154 	ctsio->kern_rel_offset = 0;
7155 	ctsio->kern_sg_entries = 0;
7156 
7157 	scsi_u64to8b(lun->be_lun->maxlba, data->addr);
7158 	/* XXX KDM this may not be 512 bytes... */
7159 	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7160 	data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
7161 	scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
7162 	if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
7163 		data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
7164 
7165 	ctl_set_success(ctsio);
7166 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7167 	ctsio->be_move_done = ctl_config_move_done;
7168 	ctl_datamove((union ctl_io *)ctsio);
7169 	return (CTL_RETVAL_COMPLETE);
7170 }
7171 
7172 int
7173 ctl_get_lba_status(struct ctl_scsiio *ctsio)
7174 {
7175 	struct scsi_get_lba_status *cdb;
7176 	struct scsi_get_lba_status_data *data;
7177 	struct ctl_lun *lun;
7178 	struct ctl_lba_len_flags *lbalen;
7179 	uint64_t lba;
7180 	uint32_t alloc_len, total_len;
7181 	int retval;
7182 
7183 	CTL_DEBUG_PRINT(("ctl_get_lba_status\n"));
7184 
7185 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7186 	cdb = (struct scsi_get_lba_status *)ctsio->cdb;
7187 	lba = scsi_8btou64(cdb->addr);
7188 	alloc_len = scsi_4btoul(cdb->alloc_len);
7189 
7190 	if (lba > lun->be_lun->maxlba) {
7191 		ctl_set_lba_out_of_range(ctsio);
7192 		ctl_done((union ctl_io *)ctsio);
7193 		return (CTL_RETVAL_COMPLETE);
7194 	}
7195 
7196 	total_len = sizeof(*data) + sizeof(data->descr[0]);
7197 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7198 	data = (struct scsi_get_lba_status_data *)ctsio->kern_data_ptr;
7199 
7200 	if (total_len < alloc_len) {
7201 		ctsio->residual = alloc_len - total_len;
7202 		ctsio->kern_data_len = total_len;
7203 		ctsio->kern_total_len = total_len;
7204 	} else {
7205 		ctsio->residual = 0;
7206 		ctsio->kern_data_len = alloc_len;
7207 		ctsio->kern_total_len = alloc_len;
7208 	}
7209 	ctsio->kern_data_resid = 0;
7210 	ctsio->kern_rel_offset = 0;
7211 	ctsio->kern_sg_entries = 0;
7212 
7213 	/* Fill dummy data in case backend can't tell anything. */
7214 	scsi_ulto4b(4 + sizeof(data->descr[0]), data->length);
7215 	scsi_u64to8b(lba, data->descr[0].addr);
7216 	scsi_ulto4b(MIN(UINT32_MAX, lun->be_lun->maxlba + 1 - lba),
7217 	    data->descr[0].length);
7218 	data->descr[0].status = 0; /* Mapped or unknown. */
7219 
7220 	ctl_set_success(ctsio);
7221 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7222 	ctsio->be_move_done = ctl_config_move_done;
7223 
7224 	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
7225 	lbalen->lba = lba;
7226 	lbalen->len = total_len;
7227 	lbalen->flags = 0;
7228 	retval = lun->backend->config_read((union ctl_io *)ctsio);
7229 	return (CTL_RETVAL_COMPLETE);
7230 }
7231 
7232 int
7233 ctl_read_defect(struct ctl_scsiio *ctsio)
7234 {
7235 	struct scsi_read_defect_data_10 *ccb10;
7236 	struct scsi_read_defect_data_12 *ccb12;
7237 	struct scsi_read_defect_data_hdr_10 *data10;
7238 	struct scsi_read_defect_data_hdr_12 *data12;
7239 	uint32_t alloc_len, data_len;
7240 	uint8_t format;
7241 
7242 	CTL_DEBUG_PRINT(("ctl_read_defect\n"));
7243 
7244 	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7245 		ccb10 = (struct scsi_read_defect_data_10 *)&ctsio->cdb;
7246 		format = ccb10->format;
7247 		alloc_len = scsi_2btoul(ccb10->alloc_length);
7248 		data_len = sizeof(*data10);
7249 	} else {
7250 		ccb12 = (struct scsi_read_defect_data_12 *)&ctsio->cdb;
7251 		format = ccb12->format;
7252 		alloc_len = scsi_4btoul(ccb12->alloc_length);
7253 		data_len = sizeof(*data12);
7254 	}
7255 	if (alloc_len == 0) {
7256 		ctl_set_success(ctsio);
7257 		ctl_done((union ctl_io *)ctsio);
7258 		return (CTL_RETVAL_COMPLETE);
7259 	}
7260 
7261 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
7262 	if (data_len < alloc_len) {
7263 		ctsio->residual = alloc_len - data_len;
7264 		ctsio->kern_data_len = data_len;
7265 		ctsio->kern_total_len = data_len;
7266 	} else {
7267 		ctsio->residual = 0;
7268 		ctsio->kern_data_len = alloc_len;
7269 		ctsio->kern_total_len = alloc_len;
7270 	}
7271 	ctsio->kern_data_resid = 0;
7272 	ctsio->kern_rel_offset = 0;
7273 	ctsio->kern_sg_entries = 0;
7274 
7275 	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7276 		data10 = (struct scsi_read_defect_data_hdr_10 *)
7277 		    ctsio->kern_data_ptr;
7278 		data10->format = format;
7279 		scsi_ulto2b(0, data10->length);
7280 	} else {
7281 		data12 = (struct scsi_read_defect_data_hdr_12 *)
7282 		    ctsio->kern_data_ptr;
7283 		data12->format = format;
7284 		scsi_ulto2b(0, data12->generation);
7285 		scsi_ulto4b(0, data12->length);
7286 	}
7287 
7288 	ctl_set_success(ctsio);
7289 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7290 	ctsio->be_move_done = ctl_config_move_done;
7291 	ctl_datamove((union ctl_io *)ctsio);
7292 	return (CTL_RETVAL_COMPLETE);
7293 }
7294 
7295 int
7296 ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7297 {
7298 	struct scsi_maintenance_in *cdb;
7299 	int retval;
7300 	int alloc_len, ext, total_len = 0, g, p, pc, pg, gs, os;
7301 	int num_target_port_groups, num_target_ports;
7302 	struct ctl_lun *lun;
7303 	struct ctl_softc *softc;
7304 	struct ctl_port *port;
7305 	struct scsi_target_group_data *rtg_ptr;
7306 	struct scsi_target_group_data_extended *rtg_ext_ptr;
7307 	struct scsi_target_port_group_descriptor *tpg_desc;
7308 
7309 	CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7310 
7311 	cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7312 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7313 	softc = lun->ctl_softc;
7314 
7315 	retval = CTL_RETVAL_COMPLETE;
7316 
7317 	switch (cdb->byte2 & STG_PDF_MASK) {
7318 	case STG_PDF_LENGTH:
7319 		ext = 0;
7320 		break;
7321 	case STG_PDF_EXTENDED:
7322 		ext = 1;
7323 		break;
7324 	default:
7325 		ctl_set_invalid_field(/*ctsio*/ ctsio,
7326 				      /*sks_valid*/ 1,
7327 				      /*command*/ 1,
7328 				      /*field*/ 2,
7329 				      /*bit_valid*/ 1,
7330 				      /*bit*/ 5);
7331 		ctl_done((union ctl_io *)ctsio);
7332 		return(retval);
7333 	}
7334 
7335 	if (softc->is_single)
7336 		num_target_port_groups = 1;
7337 	else
7338 		num_target_port_groups = NUM_TARGET_PORT_GROUPS;
7339 	num_target_ports = 0;
7340 	mtx_lock(&softc->ctl_lock);
7341 	STAILQ_FOREACH(port, &softc->port_list, links) {
7342 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7343 			continue;
7344 		if (ctl_map_lun_back(softc, port->targ_port, lun->lun) >=
7345 		    CTL_MAX_LUNS)
7346 			continue;
7347 		num_target_ports++;
7348 	}
7349 	mtx_unlock(&softc->ctl_lock);
7350 
7351 	if (ext)
7352 		total_len = sizeof(struct scsi_target_group_data_extended);
7353 	else
7354 		total_len = sizeof(struct scsi_target_group_data);
7355 	total_len += sizeof(struct scsi_target_port_group_descriptor) *
7356 		num_target_port_groups +
7357 	    sizeof(struct scsi_target_port_descriptor) *
7358 		num_target_ports * num_target_port_groups;
7359 
7360 	alloc_len = scsi_4btoul(cdb->length);
7361 
7362 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7363 
7364 	ctsio->kern_sg_entries = 0;
7365 
7366 	if (total_len < alloc_len) {
7367 		ctsio->residual = alloc_len - total_len;
7368 		ctsio->kern_data_len = total_len;
7369 		ctsio->kern_total_len = total_len;
7370 	} else {
7371 		ctsio->residual = 0;
7372 		ctsio->kern_data_len = alloc_len;
7373 		ctsio->kern_total_len = alloc_len;
7374 	}
7375 	ctsio->kern_data_resid = 0;
7376 	ctsio->kern_rel_offset = 0;
7377 
7378 	if (ext) {
7379 		rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7380 		    ctsio->kern_data_ptr;
7381 		scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7382 		rtg_ext_ptr->format_type = 0x10;
7383 		rtg_ext_ptr->implicit_transition_time = 0;
7384 		tpg_desc = &rtg_ext_ptr->groups[0];
7385 	} else {
7386 		rtg_ptr = (struct scsi_target_group_data *)
7387 		    ctsio->kern_data_ptr;
7388 		scsi_ulto4b(total_len - 4, rtg_ptr->length);
7389 		tpg_desc = &rtg_ptr->groups[0];
7390 	}
7391 
7392 	mtx_lock(&softc->ctl_lock);
7393 	pg = softc->port_offset / CTL_MAX_PORTS;
7394 	if (softc->flags & CTL_FLAG_ACTIVE_SHELF) {
7395 		if (softc->ha_mode == CTL_HA_MODE_ACT_STBY) {
7396 			gs = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7397 			os = TPG_ASYMMETRIC_ACCESS_STANDBY;
7398 		} else if (lun->flags & CTL_LUN_PRIMARY_SC) {
7399 			gs = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7400 			os = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7401 		} else {
7402 			gs = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7403 			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7404 		}
7405 	} else {
7406 		gs = TPG_ASYMMETRIC_ACCESS_STANDBY;
7407 		os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7408 	}
7409 	for (g = 0; g < num_target_port_groups; g++) {
7410 		tpg_desc->pref_state = (g == pg) ? gs : os;
7411 		tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP;
7412 		scsi_ulto2b(g + 1, tpg_desc->target_port_group);
7413 		tpg_desc->status = TPG_IMPLICIT;
7414 		pc = 0;
7415 		STAILQ_FOREACH(port, &softc->port_list, links) {
7416 			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7417 				continue;
7418 			if (ctl_map_lun_back(softc, port->targ_port, lun->lun)
7419 			    >= CTL_MAX_LUNS)
7420 				continue;
7421 			p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
7422 			scsi_ulto2b(p, tpg_desc->descriptors[pc].
7423 			    relative_target_port_identifier);
7424 			pc++;
7425 		}
7426 		tpg_desc->target_port_count = pc;
7427 		tpg_desc = (struct scsi_target_port_group_descriptor *)
7428 		    &tpg_desc->descriptors[pc];
7429 	}
7430 	mtx_unlock(&softc->ctl_lock);
7431 
7432 	ctl_set_success(ctsio);
7433 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7434 	ctsio->be_move_done = ctl_config_move_done;
7435 	ctl_datamove((union ctl_io *)ctsio);
7436 	return(retval);
7437 }
7438 
7439 int
7440 ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7441 {
7442 	struct ctl_lun *lun;
7443 	struct scsi_report_supported_opcodes *cdb;
7444 	const struct ctl_cmd_entry *entry, *sentry;
7445 	struct scsi_report_supported_opcodes_all *all;
7446 	struct scsi_report_supported_opcodes_descr *descr;
7447 	struct scsi_report_supported_opcodes_one *one;
7448 	int retval;
7449 	int alloc_len, total_len;
7450 	int opcode, service_action, i, j, num;
7451 
7452 	CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7453 
7454 	cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7455 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7456 
7457 	retval = CTL_RETVAL_COMPLETE;
7458 
7459 	opcode = cdb->requested_opcode;
7460 	service_action = scsi_2btoul(cdb->requested_service_action);
7461 	switch (cdb->options & RSO_OPTIONS_MASK) {
7462 	case RSO_OPTIONS_ALL:
7463 		num = 0;
7464 		for (i = 0; i < 256; i++) {
7465 			entry = &ctl_cmd_table[i];
7466 			if (entry->flags & CTL_CMD_FLAG_SA5) {
7467 				for (j = 0; j < 32; j++) {
7468 					sentry = &((const struct ctl_cmd_entry *)
7469 					    entry->execute)[j];
7470 					if (ctl_cmd_applicable(
7471 					    lun->be_lun->lun_type, sentry))
7472 						num++;
7473 				}
7474 			} else {
7475 				if (ctl_cmd_applicable(lun->be_lun->lun_type,
7476 				    entry))
7477 					num++;
7478 			}
7479 		}
7480 		total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7481 		    num * sizeof(struct scsi_report_supported_opcodes_descr);
7482 		break;
7483 	case RSO_OPTIONS_OC:
7484 		if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7485 			ctl_set_invalid_field(/*ctsio*/ ctsio,
7486 					      /*sks_valid*/ 1,
7487 					      /*command*/ 1,
7488 					      /*field*/ 2,
7489 					      /*bit_valid*/ 1,
7490 					      /*bit*/ 2);
7491 			ctl_done((union ctl_io *)ctsio);
7492 			return (CTL_RETVAL_COMPLETE);
7493 		}
7494 		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7495 		break;
7496 	case RSO_OPTIONS_OC_SA:
7497 		if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7498 		    service_action >= 32) {
7499 			ctl_set_invalid_field(/*ctsio*/ ctsio,
7500 					      /*sks_valid*/ 1,
7501 					      /*command*/ 1,
7502 					      /*field*/ 2,
7503 					      /*bit_valid*/ 1,
7504 					      /*bit*/ 2);
7505 			ctl_done((union ctl_io *)ctsio);
7506 			return (CTL_RETVAL_COMPLETE);
7507 		}
7508 		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7509 		break;
7510 	default:
7511 		ctl_set_invalid_field(/*ctsio*/ ctsio,
7512 				      /*sks_valid*/ 1,
7513 				      /*command*/ 1,
7514 				      /*field*/ 2,
7515 				      /*bit_valid*/ 1,
7516 				      /*bit*/ 2);
7517 		ctl_done((union ctl_io *)ctsio);
7518 		return (CTL_RETVAL_COMPLETE);
7519 	}
7520 
7521 	alloc_len = scsi_4btoul(cdb->length);
7522 
7523 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7524 
7525 	ctsio->kern_sg_entries = 0;
7526 
7527 	if (total_len < alloc_len) {
7528 		ctsio->residual = alloc_len - total_len;
7529 		ctsio->kern_data_len = total_len;
7530 		ctsio->kern_total_len = total_len;
7531 	} else {
7532 		ctsio->residual = 0;
7533 		ctsio->kern_data_len = alloc_len;
7534 		ctsio->kern_total_len = alloc_len;
7535 	}
7536 	ctsio->kern_data_resid = 0;
7537 	ctsio->kern_rel_offset = 0;
7538 
7539 	switch (cdb->options & RSO_OPTIONS_MASK) {
7540 	case RSO_OPTIONS_ALL:
7541 		all = (struct scsi_report_supported_opcodes_all *)
7542 		    ctsio->kern_data_ptr;
7543 		num = 0;
7544 		for (i = 0; i < 256; i++) {
7545 			entry = &ctl_cmd_table[i];
7546 			if (entry->flags & CTL_CMD_FLAG_SA5) {
7547 				for (j = 0; j < 32; j++) {
7548 					sentry = &((const struct ctl_cmd_entry *)
7549 					    entry->execute)[j];
7550 					if (!ctl_cmd_applicable(
7551 					    lun->be_lun->lun_type, sentry))
7552 						continue;
7553 					descr = &all->descr[num++];
7554 					descr->opcode = i;
7555 					scsi_ulto2b(j, descr->service_action);
7556 					descr->flags = RSO_SERVACTV;
7557 					scsi_ulto2b(sentry->length,
7558 					    descr->cdb_length);
7559 				}
7560 			} else {
7561 				if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7562 				    entry))
7563 					continue;
7564 				descr = &all->descr[num++];
7565 				descr->opcode = i;
7566 				scsi_ulto2b(0, descr->service_action);
7567 				descr->flags = 0;
7568 				scsi_ulto2b(entry->length, descr->cdb_length);
7569 			}
7570 		}
7571 		scsi_ulto4b(
7572 		    num * sizeof(struct scsi_report_supported_opcodes_descr),
7573 		    all->length);
7574 		break;
7575 	case RSO_OPTIONS_OC:
7576 		one = (struct scsi_report_supported_opcodes_one *)
7577 		    ctsio->kern_data_ptr;
7578 		entry = &ctl_cmd_table[opcode];
7579 		goto fill_one;
7580 	case RSO_OPTIONS_OC_SA:
7581 		one = (struct scsi_report_supported_opcodes_one *)
7582 		    ctsio->kern_data_ptr;
7583 		entry = &ctl_cmd_table[opcode];
7584 		entry = &((const struct ctl_cmd_entry *)
7585 		    entry->execute)[service_action];
7586 fill_one:
7587 		if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7588 			one->support = 3;
7589 			scsi_ulto2b(entry->length, one->cdb_length);
7590 			one->cdb_usage[0] = opcode;
7591 			memcpy(&one->cdb_usage[1], entry->usage,
7592 			    entry->length - 1);
7593 		} else
7594 			one->support = 1;
7595 		break;
7596 	}
7597 
7598 	ctl_set_success(ctsio);
7599 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7600 	ctsio->be_move_done = ctl_config_move_done;
7601 	ctl_datamove((union ctl_io *)ctsio);
7602 	return(retval);
7603 }
7604 
7605 int
7606 ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7607 {
7608 	struct scsi_report_supported_tmf *cdb;
7609 	struct scsi_report_supported_tmf_data *data;
7610 	int retval;
7611 	int alloc_len, total_len;
7612 
7613 	CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7614 
7615 	cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7616 
7617 	retval = CTL_RETVAL_COMPLETE;
7618 
7619 	total_len = sizeof(struct scsi_report_supported_tmf_data);
7620 	alloc_len = scsi_4btoul(cdb->length);
7621 
7622 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7623 
7624 	ctsio->kern_sg_entries = 0;
7625 
7626 	if (total_len < alloc_len) {
7627 		ctsio->residual = alloc_len - total_len;
7628 		ctsio->kern_data_len = total_len;
7629 		ctsio->kern_total_len = total_len;
7630 	} else {
7631 		ctsio->residual = 0;
7632 		ctsio->kern_data_len = alloc_len;
7633 		ctsio->kern_total_len = alloc_len;
7634 	}
7635 	ctsio->kern_data_resid = 0;
7636 	ctsio->kern_rel_offset = 0;
7637 
7638 	data = (struct scsi_report_supported_tmf_data *)ctsio->kern_data_ptr;
7639 	data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_TRS;
7640 	data->byte2 |= RST_ITNRS;
7641 
7642 	ctl_set_success(ctsio);
7643 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7644 	ctsio->be_move_done = ctl_config_move_done;
7645 	ctl_datamove((union ctl_io *)ctsio);
7646 	return (retval);
7647 }
7648 
7649 int
7650 ctl_report_timestamp(struct ctl_scsiio *ctsio)
7651 {
7652 	struct scsi_report_timestamp *cdb;
7653 	struct scsi_report_timestamp_data *data;
7654 	struct timeval tv;
7655 	int64_t timestamp;
7656 	int retval;
7657 	int alloc_len, total_len;
7658 
7659 	CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7660 
7661 	cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7662 
7663 	retval = CTL_RETVAL_COMPLETE;
7664 
7665 	total_len = sizeof(struct scsi_report_timestamp_data);
7666 	alloc_len = scsi_4btoul(cdb->length);
7667 
7668 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7669 
7670 	ctsio->kern_sg_entries = 0;
7671 
7672 	if (total_len < alloc_len) {
7673 		ctsio->residual = alloc_len - total_len;
7674 		ctsio->kern_data_len = total_len;
7675 		ctsio->kern_total_len = total_len;
7676 	} else {
7677 		ctsio->residual = 0;
7678 		ctsio->kern_data_len = alloc_len;
7679 		ctsio->kern_total_len = alloc_len;
7680 	}
7681 	ctsio->kern_data_resid = 0;
7682 	ctsio->kern_rel_offset = 0;
7683 
7684 	data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7685 	scsi_ulto2b(sizeof(*data) - 2, data->length);
7686 	data->origin = RTS_ORIG_OUTSIDE;
7687 	getmicrotime(&tv);
7688 	timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7689 	scsi_ulto4b(timestamp >> 16, data->timestamp);
7690 	scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7691 
7692 	ctl_set_success(ctsio);
7693 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7694 	ctsio->be_move_done = ctl_config_move_done;
7695 	ctl_datamove((union ctl_io *)ctsio);
7696 	return (retval);
7697 }
7698 
7699 int
7700 ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7701 {
7702 	struct scsi_per_res_in *cdb;
7703 	int alloc_len, total_len = 0;
7704 	/* struct scsi_per_res_in_rsrv in_data; */
7705 	struct ctl_lun *lun;
7706 	struct ctl_softc *softc;
7707 	uint64_t key;
7708 
7709 	CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7710 
7711 	cdb = (struct scsi_per_res_in *)ctsio->cdb;
7712 
7713 	alloc_len = scsi_2btoul(cdb->length);
7714 
7715 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7716 	softc = lun->ctl_softc;
7717 
7718 retry:
7719 	mtx_lock(&lun->lun_lock);
7720 	switch (cdb->action) {
7721 	case SPRI_RK: /* read keys */
7722 		total_len = sizeof(struct scsi_per_res_in_keys) +
7723 			lun->pr_key_count *
7724 			sizeof(struct scsi_per_res_key);
7725 		break;
7726 	case SPRI_RR: /* read reservation */
7727 		if (lun->flags & CTL_LUN_PR_RESERVED)
7728 			total_len = sizeof(struct scsi_per_res_in_rsrv);
7729 		else
7730 			total_len = sizeof(struct scsi_per_res_in_header);
7731 		break;
7732 	case SPRI_RC: /* report capabilities */
7733 		total_len = sizeof(struct scsi_per_res_cap);
7734 		break;
7735 	case SPRI_RS: /* read full status */
7736 		total_len = sizeof(struct scsi_per_res_in_header) +
7737 		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7738 		    lun->pr_key_count;
7739 		break;
7740 	default:
7741 		panic("Invalid PR type %x", cdb->action);
7742 	}
7743 	mtx_unlock(&lun->lun_lock);
7744 
7745 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7746 
7747 	if (total_len < alloc_len) {
7748 		ctsio->residual = alloc_len - total_len;
7749 		ctsio->kern_data_len = total_len;
7750 		ctsio->kern_total_len = total_len;
7751 	} else {
7752 		ctsio->residual = 0;
7753 		ctsio->kern_data_len = alloc_len;
7754 		ctsio->kern_total_len = alloc_len;
7755 	}
7756 
7757 	ctsio->kern_data_resid = 0;
7758 	ctsio->kern_rel_offset = 0;
7759 	ctsio->kern_sg_entries = 0;
7760 
7761 	mtx_lock(&lun->lun_lock);
7762 	switch (cdb->action) {
7763 	case SPRI_RK: { // read keys
7764         struct scsi_per_res_in_keys *res_keys;
7765 		int i, key_count;
7766 
7767 		res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7768 
7769 		/*
7770 		 * We had to drop the lock to allocate our buffer, which
7771 		 * leaves time for someone to come in with another
7772 		 * persistent reservation.  (That is unlikely, though,
7773 		 * since this should be the only persistent reservation
7774 		 * command active right now.)
7775 		 */
7776 		if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7777 		    (lun->pr_key_count *
7778 		     sizeof(struct scsi_per_res_key)))){
7779 			mtx_unlock(&lun->lun_lock);
7780 			free(ctsio->kern_data_ptr, M_CTL);
7781 			printf("%s: reservation length changed, retrying\n",
7782 			       __func__);
7783 			goto retry;
7784 		}
7785 
7786 		scsi_ulto4b(lun->PRGeneration, res_keys->header.generation);
7787 
7788 		scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7789 			     lun->pr_key_count, res_keys->header.length);
7790 
7791 		for (i = 0, key_count = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7792 			if ((key = ctl_get_prkey(lun, i)) == 0)
7793 				continue;
7794 
7795 			/*
7796 			 * We used lun->pr_key_count to calculate the
7797 			 * size to allocate.  If it turns out the number of
7798 			 * initiators with the registered flag set is
7799 			 * larger than that (i.e. they haven't been kept in
7800 			 * sync), we've got a problem.
7801 			 */
7802 			if (key_count >= lun->pr_key_count) {
7803 #ifdef NEEDTOPORT
7804 				csevent_log(CSC_CTL | CSC_SHELF_SW |
7805 					    CTL_PR_ERROR,
7806 					    csevent_LogType_Fault,
7807 					    csevent_AlertLevel_Yellow,
7808 					    csevent_FRU_ShelfController,
7809 					    csevent_FRU_Firmware,
7810 				        csevent_FRU_Unknown,
7811 					    "registered keys %d >= key "
7812 					    "count %d", key_count,
7813 					    lun->pr_key_count);
7814 #endif
7815 				key_count++;
7816 				continue;
7817 			}
7818 			scsi_u64to8b(key, res_keys->keys[key_count].key);
7819 			key_count++;
7820 		}
7821 		break;
7822 	}
7823 	case SPRI_RR: { // read reservation
7824 		struct scsi_per_res_in_rsrv *res;
7825 		int tmp_len, header_only;
7826 
7827 		res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7828 
7829 		scsi_ulto4b(lun->PRGeneration, res->header.generation);
7830 
7831 		if (lun->flags & CTL_LUN_PR_RESERVED)
7832 		{
7833 			tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7834 			scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7835 				    res->header.length);
7836 			header_only = 0;
7837 		} else {
7838 			tmp_len = sizeof(struct scsi_per_res_in_header);
7839 			scsi_ulto4b(0, res->header.length);
7840 			header_only = 1;
7841 		}
7842 
7843 		/*
7844 		 * We had to drop the lock to allocate our buffer, which
7845 		 * leaves time for someone to come in with another
7846 		 * persistent reservation.  (That is unlikely, though,
7847 		 * since this should be the only persistent reservation
7848 		 * command active right now.)
7849 		 */
7850 		if (tmp_len != total_len) {
7851 			mtx_unlock(&lun->lun_lock);
7852 			free(ctsio->kern_data_ptr, M_CTL);
7853 			printf("%s: reservation status changed, retrying\n",
7854 			       __func__);
7855 			goto retry;
7856 		}
7857 
7858 		/*
7859 		 * No reservation held, so we're done.
7860 		 */
7861 		if (header_only != 0)
7862 			break;
7863 
7864 		/*
7865 		 * If the registration is an All Registrants type, the key
7866 		 * is 0, since it doesn't really matter.
7867 		 */
7868 		if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7869 			scsi_u64to8b(ctl_get_prkey(lun, lun->pr_res_idx),
7870 			    res->data.reservation);
7871 		}
7872 		res->data.scopetype = lun->res_type;
7873 		break;
7874 	}
7875 	case SPRI_RC:     //report capabilities
7876 	{
7877 		struct scsi_per_res_cap *res_cap;
7878 		uint16_t type_mask;
7879 
7880 		res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7881 		scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7882 		res_cap->flags2 |= SPRI_TMV | SPRI_ALLOW_5;
7883 		type_mask = SPRI_TM_WR_EX_AR |
7884 			    SPRI_TM_EX_AC_RO |
7885 			    SPRI_TM_WR_EX_RO |
7886 			    SPRI_TM_EX_AC |
7887 			    SPRI_TM_WR_EX |
7888 			    SPRI_TM_EX_AC_AR;
7889 		scsi_ulto2b(type_mask, res_cap->type_mask);
7890 		break;
7891 	}
7892 	case SPRI_RS: { // read full status
7893 		struct scsi_per_res_in_full *res_status;
7894 		struct scsi_per_res_in_full_desc *res_desc;
7895 		struct ctl_port *port;
7896 		int i, len;
7897 
7898 		res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7899 
7900 		/*
7901 		 * We had to drop the lock to allocate our buffer, which
7902 		 * leaves time for someone to come in with another
7903 		 * persistent reservation.  (That is unlikely, though,
7904 		 * since this should be the only persistent reservation
7905 		 * command active right now.)
7906 		 */
7907 		if (total_len < (sizeof(struct scsi_per_res_in_header) +
7908 		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7909 		     lun->pr_key_count)){
7910 			mtx_unlock(&lun->lun_lock);
7911 			free(ctsio->kern_data_ptr, M_CTL);
7912 			printf("%s: reservation length changed, retrying\n",
7913 			       __func__);
7914 			goto retry;
7915 		}
7916 
7917 		scsi_ulto4b(lun->PRGeneration, res_status->header.generation);
7918 
7919 		res_desc = &res_status->desc[0];
7920 		for (i = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7921 			if ((key = ctl_get_prkey(lun, i)) == 0)
7922 				continue;
7923 
7924 			scsi_u64to8b(key, res_desc->res_key.key);
7925 			if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7926 			    (lun->pr_res_idx == i ||
7927 			     lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7928 				res_desc->flags = SPRI_FULL_R_HOLDER;
7929 				res_desc->scopetype = lun->res_type;
7930 			}
7931 			scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7932 			    res_desc->rel_trgt_port_id);
7933 			len = 0;
7934 			port = softc->ctl_ports[
7935 			    ctl_port_idx(i / CTL_MAX_INIT_PER_PORT)];
7936 			if (port != NULL)
7937 				len = ctl_create_iid(port,
7938 				    i % CTL_MAX_INIT_PER_PORT,
7939 				    res_desc->transport_id);
7940 			scsi_ulto4b(len, res_desc->additional_length);
7941 			res_desc = (struct scsi_per_res_in_full_desc *)
7942 			    &res_desc->transport_id[len];
7943 		}
7944 		scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7945 		    res_status->header.length);
7946 		break;
7947 	}
7948 	default:
7949 		/*
7950 		 * This is a bug, because we just checked for this above,
7951 		 * and should have returned an error.
7952 		 */
7953 		panic("Invalid PR type %x", cdb->action);
7954 		break; /* NOTREACHED */
7955 	}
7956 	mtx_unlock(&lun->lun_lock);
7957 
7958 	ctl_set_success(ctsio);
7959 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7960 	ctsio->be_move_done = ctl_config_move_done;
7961 	ctl_datamove((union ctl_io *)ctsio);
7962 	return (CTL_RETVAL_COMPLETE);
7963 }
7964 
7965 static void
7966 ctl_est_res_ua(struct ctl_lun *lun, uint32_t residx, ctl_ua_type ua)
7967 {
7968 	int off = lun->ctl_softc->persis_offset;
7969 
7970 	if (residx >= off && residx < off + CTL_MAX_INITIATORS)
7971 		ctl_est_ua(lun, residx - off, ua);
7972 }
7973 
7974 /*
7975  * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
7976  * it should return.
7977  */
7978 static int
7979 ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
7980 		uint64_t sa_res_key, uint8_t type, uint32_t residx,
7981 		struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
7982 		struct scsi_per_res_out_parms* param)
7983 {
7984 	union ctl_ha_msg persis_io;
7985 	int retval, i;
7986 	int isc_retval;
7987 
7988 	retval = 0;
7989 
7990 	mtx_lock(&lun->lun_lock);
7991 	if (sa_res_key == 0) {
7992 		if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
7993 			/* validate scope and type */
7994 			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7995 			     SPR_LU_SCOPE) {
7996 				mtx_unlock(&lun->lun_lock);
7997 				ctl_set_invalid_field(/*ctsio*/ ctsio,
7998 						      /*sks_valid*/ 1,
7999 						      /*command*/ 1,
8000 						      /*field*/ 2,
8001 						      /*bit_valid*/ 1,
8002 						      /*bit*/ 4);
8003 				ctl_done((union ctl_io *)ctsio);
8004 				return (1);
8005 			}
8006 
8007 		        if (type>8 || type==2 || type==4 || type==0) {
8008 				mtx_unlock(&lun->lun_lock);
8009 				ctl_set_invalid_field(/*ctsio*/ ctsio,
8010        	           				      /*sks_valid*/ 1,
8011 						      /*command*/ 1,
8012 						      /*field*/ 2,
8013 						      /*bit_valid*/ 1,
8014 						      /*bit*/ 0);
8015 				ctl_done((union ctl_io *)ctsio);
8016 				return (1);
8017 		        }
8018 
8019 			/*
8020 			 * Unregister everybody else and build UA for
8021 			 * them
8022 			 */
8023 			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8024 				if (i == residx || ctl_get_prkey(lun, i) == 0)
8025 					continue;
8026 
8027 				ctl_clr_prkey(lun, i);
8028 				ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8029 			}
8030 			lun->pr_key_count = 1;
8031 			lun->res_type = type;
8032 			if (lun->res_type != SPR_TYPE_WR_EX_AR
8033 			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8034 				lun->pr_res_idx = residx;
8035 
8036 			/* send msg to other side */
8037 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8038 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8039 			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8040 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8041 			persis_io.pr.pr_info.res_type = type;
8042 			memcpy(persis_io.pr.pr_info.sa_res_key,
8043 			       param->serv_act_res_key,
8044 			       sizeof(param->serv_act_res_key));
8045 			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8046 			     &persis_io, sizeof(persis_io), 0)) >
8047 			     CTL_HA_STATUS_SUCCESS) {
8048 				printf("CTL:Persis Out error returned "
8049 				       "from ctl_ha_msg_send %d\n",
8050 				       isc_retval);
8051 			}
8052 		} else {
8053 			/* not all registrants */
8054 			mtx_unlock(&lun->lun_lock);
8055 			free(ctsio->kern_data_ptr, M_CTL);
8056 			ctl_set_invalid_field(ctsio,
8057 					      /*sks_valid*/ 1,
8058 					      /*command*/ 0,
8059 					      /*field*/ 8,
8060 					      /*bit_valid*/ 0,
8061 					      /*bit*/ 0);
8062 			ctl_done((union ctl_io *)ctsio);
8063 			return (1);
8064 		}
8065 	} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8066 		|| !(lun->flags & CTL_LUN_PR_RESERVED)) {
8067 		int found = 0;
8068 
8069 		if (res_key == sa_res_key) {
8070 			/* special case */
8071 			/*
8072 			 * The spec implies this is not good but doesn't
8073 			 * say what to do. There are two choices either
8074 			 * generate a res conflict or check condition
8075 			 * with illegal field in parameter data. Since
8076 			 * that is what is done when the sa_res_key is
8077 			 * zero I'll take that approach since this has
8078 			 * to do with the sa_res_key.
8079 			 */
8080 			mtx_unlock(&lun->lun_lock);
8081 			free(ctsio->kern_data_ptr, M_CTL);
8082 			ctl_set_invalid_field(ctsio,
8083 					      /*sks_valid*/ 1,
8084 					      /*command*/ 0,
8085 					      /*field*/ 8,
8086 					      /*bit_valid*/ 0,
8087 					      /*bit*/ 0);
8088 			ctl_done((union ctl_io *)ctsio);
8089 			return (1);
8090 		}
8091 
8092 		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8093 			if (ctl_get_prkey(lun, i) != sa_res_key)
8094 				continue;
8095 
8096 			found = 1;
8097 			ctl_clr_prkey(lun, i);
8098 			lun->pr_key_count--;
8099 			ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8100 		}
8101 		if (!found) {
8102 			mtx_unlock(&lun->lun_lock);
8103 			free(ctsio->kern_data_ptr, M_CTL);
8104 			ctl_set_reservation_conflict(ctsio);
8105 			ctl_done((union ctl_io *)ctsio);
8106 			return (CTL_RETVAL_COMPLETE);
8107 		}
8108 		/* send msg to other side */
8109 		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8110 		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8111 		persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8112 		persis_io.pr.pr_info.residx = lun->pr_res_idx;
8113 		persis_io.pr.pr_info.res_type = type;
8114 		memcpy(persis_io.pr.pr_info.sa_res_key,
8115 		       param->serv_act_res_key,
8116 		       sizeof(param->serv_act_res_key));
8117 		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8118 		     &persis_io, sizeof(persis_io), 0)) >
8119 		     CTL_HA_STATUS_SUCCESS) {
8120 			printf("CTL:Persis Out error returned from "
8121 			       "ctl_ha_msg_send %d\n", isc_retval);
8122 		}
8123 	} else {
8124 		/* Reserved but not all registrants */
8125 		/* sa_res_key is res holder */
8126 		if (sa_res_key == ctl_get_prkey(lun, lun->pr_res_idx)) {
8127 			/* validate scope and type */
8128 			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8129 			     SPR_LU_SCOPE) {
8130 				mtx_unlock(&lun->lun_lock);
8131 				ctl_set_invalid_field(/*ctsio*/ ctsio,
8132 						      /*sks_valid*/ 1,
8133 						      /*command*/ 1,
8134 						      /*field*/ 2,
8135 						      /*bit_valid*/ 1,
8136 						      /*bit*/ 4);
8137 				ctl_done((union ctl_io *)ctsio);
8138 				return (1);
8139 			}
8140 
8141 			if (type>8 || type==2 || type==4 || type==0) {
8142 				mtx_unlock(&lun->lun_lock);
8143 				ctl_set_invalid_field(/*ctsio*/ ctsio,
8144 						      /*sks_valid*/ 1,
8145 						      /*command*/ 1,
8146 						      /*field*/ 2,
8147 						      /*bit_valid*/ 1,
8148 						      /*bit*/ 0);
8149 				ctl_done((union ctl_io *)ctsio);
8150 				return (1);
8151 			}
8152 
8153 			/*
8154 			 * Do the following:
8155 			 * if sa_res_key != res_key remove all
8156 			 * registrants w/sa_res_key and generate UA
8157 			 * for these registrants(Registrations
8158 			 * Preempted) if it wasn't an exclusive
8159 			 * reservation generate UA(Reservations
8160 			 * Preempted) for all other registered nexuses
8161 			 * if the type has changed. Establish the new
8162 			 * reservation and holder. If res_key and
8163 			 * sa_res_key are the same do the above
8164 			 * except don't unregister the res holder.
8165 			 */
8166 
8167 			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8168 				if (i == residx || ctl_get_prkey(lun, i) == 0)
8169 					continue;
8170 
8171 				if (sa_res_key == ctl_get_prkey(lun, i)) {
8172 					ctl_clr_prkey(lun, i);
8173 					lun->pr_key_count--;
8174 					ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8175 				} else if (type != lun->res_type
8176 					&& (lun->res_type == SPR_TYPE_WR_EX_RO
8177 					 || lun->res_type ==SPR_TYPE_EX_AC_RO)){
8178 					ctl_est_res_ua(lun, i, CTL_UA_RES_RELEASE);
8179 				}
8180 			}
8181 			lun->res_type = type;
8182 			if (lun->res_type != SPR_TYPE_WR_EX_AR
8183 			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8184 				lun->pr_res_idx = residx;
8185 			else
8186 				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8187 
8188 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8189 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8190 			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8191 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8192 			persis_io.pr.pr_info.res_type = type;
8193 			memcpy(persis_io.pr.pr_info.sa_res_key,
8194 			       param->serv_act_res_key,
8195 			       sizeof(param->serv_act_res_key));
8196 			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8197 			     &persis_io, sizeof(persis_io), 0)) >
8198 			     CTL_HA_STATUS_SUCCESS) {
8199 				printf("CTL:Persis Out error returned "
8200 				       "from ctl_ha_msg_send %d\n",
8201 				       isc_retval);
8202 			}
8203 		} else {
8204 			/*
8205 			 * sa_res_key is not the res holder just
8206 			 * remove registrants
8207 			 */
8208 			int found=0;
8209 
8210 			for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8211 				if (sa_res_key != ctl_get_prkey(lun, i))
8212 					continue;
8213 
8214 				found = 1;
8215 				ctl_clr_prkey(lun, i);
8216 				lun->pr_key_count--;
8217 				ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8218 			}
8219 
8220 			if (!found) {
8221 				mtx_unlock(&lun->lun_lock);
8222 				free(ctsio->kern_data_ptr, M_CTL);
8223 				ctl_set_reservation_conflict(ctsio);
8224 				ctl_done((union ctl_io *)ctsio);
8225 		        	return (1);
8226 			}
8227 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8228 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8229 			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8230 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8231 			persis_io.pr.pr_info.res_type = type;
8232 			memcpy(persis_io.pr.pr_info.sa_res_key,
8233 			       param->serv_act_res_key,
8234 			       sizeof(param->serv_act_res_key));
8235 			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8236 			     &persis_io, sizeof(persis_io), 0)) >
8237 			     CTL_HA_STATUS_SUCCESS) {
8238 				printf("CTL:Persis Out error returned "
8239 				       "from ctl_ha_msg_send %d\n",
8240 				isc_retval);
8241 			}
8242 		}
8243 	}
8244 
8245 	lun->PRGeneration++;
8246 	mtx_unlock(&lun->lun_lock);
8247 
8248 	return (retval);
8249 }
8250 
8251 static void
8252 ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8253 {
8254 	uint64_t sa_res_key;
8255 	int i;
8256 
8257 	sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8258 
8259 	if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8260 	 || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8261 	 || sa_res_key != ctl_get_prkey(lun, lun->pr_res_idx)) {
8262 		if (sa_res_key == 0) {
8263 			/*
8264 			 * Unregister everybody else and build UA for
8265 			 * them
8266 			 */
8267 			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8268 				if (i == msg->pr.pr_info.residx ||
8269 				    ctl_get_prkey(lun, i) == 0)
8270 					continue;
8271 
8272 				ctl_clr_prkey(lun, i);
8273 				ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8274 			}
8275 
8276 			lun->pr_key_count = 1;
8277 			lun->res_type = msg->pr.pr_info.res_type;
8278 			if (lun->res_type != SPR_TYPE_WR_EX_AR
8279 			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8280 				lun->pr_res_idx = msg->pr.pr_info.residx;
8281 		} else {
8282 		        for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8283 				if (sa_res_key == ctl_get_prkey(lun, i))
8284 					continue;
8285 
8286 				ctl_clr_prkey(lun, i);
8287 				lun->pr_key_count--;
8288 				ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8289 			}
8290 		}
8291 	} else {
8292 		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8293 			if (i == msg->pr.pr_info.residx ||
8294 			    ctl_get_prkey(lun, i) == 0)
8295 				continue;
8296 
8297 			if (sa_res_key == ctl_get_prkey(lun, i)) {
8298 				ctl_clr_prkey(lun, i);
8299 				lun->pr_key_count--;
8300 				ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8301 			} else if (msg->pr.pr_info.res_type != lun->res_type
8302 				&& (lun->res_type == SPR_TYPE_WR_EX_RO
8303 				 || lun->res_type == SPR_TYPE_EX_AC_RO)) {
8304 				ctl_est_res_ua(lun, i, CTL_UA_RES_RELEASE);
8305 			}
8306 		}
8307 		lun->res_type = msg->pr.pr_info.res_type;
8308 		if (lun->res_type != SPR_TYPE_WR_EX_AR
8309 		 && lun->res_type != SPR_TYPE_EX_AC_AR)
8310 			lun->pr_res_idx = msg->pr.pr_info.residx;
8311 		else
8312 			lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8313 	}
8314 	lun->PRGeneration++;
8315 
8316 }
8317 
8318 
8319 int
8320 ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8321 {
8322 	int retval;
8323 	int isc_retval;
8324 	u_int32_t param_len;
8325 	struct scsi_per_res_out *cdb;
8326 	struct ctl_lun *lun;
8327 	struct scsi_per_res_out_parms* param;
8328 	struct ctl_softc *softc;
8329 	uint32_t residx;
8330 	uint64_t res_key, sa_res_key, key;
8331 	uint8_t type;
8332 	union ctl_ha_msg persis_io;
8333 	int    i;
8334 
8335 	CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8336 
8337 	retval = CTL_RETVAL_COMPLETE;
8338 
8339 	cdb = (struct scsi_per_res_out *)ctsio->cdb;
8340 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8341 	softc = lun->ctl_softc;
8342 
8343 	/*
8344 	 * We only support whole-LUN scope.  The scope & type are ignored for
8345 	 * register, register and ignore existing key and clear.
8346 	 * We sometimes ignore scope and type on preempts too!!
8347 	 * Verify reservation type here as well.
8348 	 */
8349 	type = cdb->scope_type & SPR_TYPE_MASK;
8350 	if ((cdb->action == SPRO_RESERVE)
8351 	 || (cdb->action == SPRO_RELEASE)) {
8352 		if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8353 			ctl_set_invalid_field(/*ctsio*/ ctsio,
8354 					      /*sks_valid*/ 1,
8355 					      /*command*/ 1,
8356 					      /*field*/ 2,
8357 					      /*bit_valid*/ 1,
8358 					      /*bit*/ 4);
8359 			ctl_done((union ctl_io *)ctsio);
8360 			return (CTL_RETVAL_COMPLETE);
8361 		}
8362 
8363 		if (type>8 || type==2 || type==4 || type==0) {
8364 			ctl_set_invalid_field(/*ctsio*/ ctsio,
8365 					      /*sks_valid*/ 1,
8366 					      /*command*/ 1,
8367 					      /*field*/ 2,
8368 					      /*bit_valid*/ 1,
8369 					      /*bit*/ 0);
8370 			ctl_done((union ctl_io *)ctsio);
8371 			return (CTL_RETVAL_COMPLETE);
8372 		}
8373 	}
8374 
8375 	param_len = scsi_4btoul(cdb->length);
8376 
8377 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8378 		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8379 		ctsio->kern_data_len = param_len;
8380 		ctsio->kern_total_len = param_len;
8381 		ctsio->kern_data_resid = 0;
8382 		ctsio->kern_rel_offset = 0;
8383 		ctsio->kern_sg_entries = 0;
8384 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8385 		ctsio->be_move_done = ctl_config_move_done;
8386 		ctl_datamove((union ctl_io *)ctsio);
8387 
8388 		return (CTL_RETVAL_COMPLETE);
8389 	}
8390 
8391 	param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8392 
8393 	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
8394 	res_key = scsi_8btou64(param->res_key.key);
8395 	sa_res_key = scsi_8btou64(param->serv_act_res_key);
8396 
8397 	/*
8398 	 * Validate the reservation key here except for SPRO_REG_IGNO
8399 	 * This must be done for all other service actions
8400 	 */
8401 	if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8402 		mtx_lock(&lun->lun_lock);
8403 		if ((key = ctl_get_prkey(lun, residx)) != 0) {
8404 			if (res_key != key) {
8405 				/*
8406 				 * The current key passed in doesn't match
8407 				 * the one the initiator previously
8408 				 * registered.
8409 				 */
8410 				mtx_unlock(&lun->lun_lock);
8411 				free(ctsio->kern_data_ptr, M_CTL);
8412 				ctl_set_reservation_conflict(ctsio);
8413 				ctl_done((union ctl_io *)ctsio);
8414 				return (CTL_RETVAL_COMPLETE);
8415 			}
8416 		} else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8417 			/*
8418 			 * We are not registered
8419 			 */
8420 			mtx_unlock(&lun->lun_lock);
8421 			free(ctsio->kern_data_ptr, M_CTL);
8422 			ctl_set_reservation_conflict(ctsio);
8423 			ctl_done((union ctl_io *)ctsio);
8424 			return (CTL_RETVAL_COMPLETE);
8425 		} else if (res_key != 0) {
8426 			/*
8427 			 * We are not registered and trying to register but
8428 			 * the register key isn't zero.
8429 			 */
8430 			mtx_unlock(&lun->lun_lock);
8431 			free(ctsio->kern_data_ptr, M_CTL);
8432 			ctl_set_reservation_conflict(ctsio);
8433 			ctl_done((union ctl_io *)ctsio);
8434 			return (CTL_RETVAL_COMPLETE);
8435 		}
8436 		mtx_unlock(&lun->lun_lock);
8437 	}
8438 
8439 	switch (cdb->action & SPRO_ACTION_MASK) {
8440 	case SPRO_REGISTER:
8441 	case SPRO_REG_IGNO: {
8442 
8443 #if 0
8444 		printf("Registration received\n");
8445 #endif
8446 
8447 		/*
8448 		 * We don't support any of these options, as we report in
8449 		 * the read capabilities request (see
8450 		 * ctl_persistent_reserve_in(), above).
8451 		 */
8452 		if ((param->flags & SPR_SPEC_I_PT)
8453 		 || (param->flags & SPR_ALL_TG_PT)
8454 		 || (param->flags & SPR_APTPL)) {
8455 			int bit_ptr;
8456 
8457 			if (param->flags & SPR_APTPL)
8458 				bit_ptr = 0;
8459 			else if (param->flags & SPR_ALL_TG_PT)
8460 				bit_ptr = 2;
8461 			else /* SPR_SPEC_I_PT */
8462 				bit_ptr = 3;
8463 
8464 			free(ctsio->kern_data_ptr, M_CTL);
8465 			ctl_set_invalid_field(ctsio,
8466 					      /*sks_valid*/ 1,
8467 					      /*command*/ 0,
8468 					      /*field*/ 20,
8469 					      /*bit_valid*/ 1,
8470 					      /*bit*/ bit_ptr);
8471 			ctl_done((union ctl_io *)ctsio);
8472 			return (CTL_RETVAL_COMPLETE);
8473 		}
8474 
8475 		mtx_lock(&lun->lun_lock);
8476 
8477 		/*
8478 		 * The initiator wants to clear the
8479 		 * key/unregister.
8480 		 */
8481 		if (sa_res_key == 0) {
8482 			if ((res_key == 0
8483 			  && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8484 			 || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8485 			  && ctl_get_prkey(lun, residx) == 0)) {
8486 				mtx_unlock(&lun->lun_lock);
8487 				goto done;
8488 			}
8489 
8490 			ctl_clr_prkey(lun, residx);
8491 			lun->pr_key_count--;
8492 
8493 			if (residx == lun->pr_res_idx) {
8494 				lun->flags &= ~CTL_LUN_PR_RESERVED;
8495 				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8496 
8497 				if ((lun->res_type == SPR_TYPE_WR_EX_RO
8498 				  || lun->res_type == SPR_TYPE_EX_AC_RO)
8499 				 && lun->pr_key_count) {
8500 					/*
8501 					 * If the reservation is a registrants
8502 					 * only type we need to generate a UA
8503 					 * for other registered inits.  The
8504 					 * sense code should be RESERVATIONS
8505 					 * RELEASED
8506 					 */
8507 
8508 					for (i = 0; i < CTL_MAX_INITIATORS;i++){
8509 						if (ctl_get_prkey(lun, i +
8510 						    softc->persis_offset) == 0)
8511 							continue;
8512 						ctl_est_ua(lun, i,
8513 						    CTL_UA_RES_RELEASE);
8514 					}
8515 				}
8516 				lun->res_type = 0;
8517 			} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8518 				if (lun->pr_key_count==0) {
8519 					lun->flags &= ~CTL_LUN_PR_RESERVED;
8520 					lun->res_type = 0;
8521 					lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8522 				}
8523 			}
8524 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8525 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8526 			persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8527 			persis_io.pr.pr_info.residx = residx;
8528 			if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8529 			     &persis_io, sizeof(persis_io), 0 )) >
8530 			     CTL_HA_STATUS_SUCCESS) {
8531 				printf("CTL:Persis Out error returned from "
8532 				       "ctl_ha_msg_send %d\n", isc_retval);
8533 			}
8534 		} else /* sa_res_key != 0 */ {
8535 
8536 			/*
8537 			 * If we aren't registered currently then increment
8538 			 * the key count and set the registered flag.
8539 			 */
8540 			ctl_alloc_prkey(lun, residx);
8541 			if (ctl_get_prkey(lun, residx) == 0)
8542 				lun->pr_key_count++;
8543 			ctl_set_prkey(lun, residx, sa_res_key);
8544 
8545 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8546 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8547 			persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8548 			persis_io.pr.pr_info.residx = residx;
8549 			memcpy(persis_io.pr.pr_info.sa_res_key,
8550 			       param->serv_act_res_key,
8551 			       sizeof(param->serv_act_res_key));
8552 			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8553 			     &persis_io, sizeof(persis_io), 0)) >
8554 			     CTL_HA_STATUS_SUCCESS) {
8555 				printf("CTL:Persis Out error returned from "
8556 				       "ctl_ha_msg_send %d\n", isc_retval);
8557 			}
8558 		}
8559 		lun->PRGeneration++;
8560 		mtx_unlock(&lun->lun_lock);
8561 
8562 		break;
8563 	}
8564 	case SPRO_RESERVE:
8565 #if 0
8566                 printf("Reserve executed type %d\n", type);
8567 #endif
8568 		mtx_lock(&lun->lun_lock);
8569 		if (lun->flags & CTL_LUN_PR_RESERVED) {
8570 			/*
8571 			 * if this isn't the reservation holder and it's
8572 			 * not a "all registrants" type or if the type is
8573 			 * different then we have a conflict
8574 			 */
8575 			if ((lun->pr_res_idx != residx
8576 			  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8577 			 || lun->res_type != type) {
8578 				mtx_unlock(&lun->lun_lock);
8579 				free(ctsio->kern_data_ptr, M_CTL);
8580 				ctl_set_reservation_conflict(ctsio);
8581 				ctl_done((union ctl_io *)ctsio);
8582 				return (CTL_RETVAL_COMPLETE);
8583 			}
8584 			mtx_unlock(&lun->lun_lock);
8585 		} else /* create a reservation */ {
8586 			/*
8587 			 * If it's not an "all registrants" type record
8588 			 * reservation holder
8589 			 */
8590 			if (type != SPR_TYPE_WR_EX_AR
8591 			 && type != SPR_TYPE_EX_AC_AR)
8592 				lun->pr_res_idx = residx; /* Res holder */
8593 			else
8594 				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8595 
8596 			lun->flags |= CTL_LUN_PR_RESERVED;
8597 			lun->res_type = type;
8598 
8599 			mtx_unlock(&lun->lun_lock);
8600 
8601 			/* send msg to other side */
8602 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8603 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8604 			persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8605 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8606 			persis_io.pr.pr_info.res_type = type;
8607 			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8608 			     &persis_io, sizeof(persis_io), 0)) >
8609 			     CTL_HA_STATUS_SUCCESS) {
8610 				printf("CTL:Persis Out error returned from "
8611 				       "ctl_ha_msg_send %d\n", isc_retval);
8612 			}
8613 		}
8614 		break;
8615 
8616 	case SPRO_RELEASE:
8617 		mtx_lock(&lun->lun_lock);
8618 		if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8619 			/* No reservation exists return good status */
8620 			mtx_unlock(&lun->lun_lock);
8621 			goto done;
8622 		}
8623 		/*
8624 		 * Is this nexus a reservation holder?
8625 		 */
8626 		if (lun->pr_res_idx != residx
8627 		 && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8628 			/*
8629 			 * not a res holder return good status but
8630 			 * do nothing
8631 			 */
8632 			mtx_unlock(&lun->lun_lock);
8633 			goto done;
8634 		}
8635 
8636 		if (lun->res_type != type) {
8637 			mtx_unlock(&lun->lun_lock);
8638 			free(ctsio->kern_data_ptr, M_CTL);
8639 			ctl_set_illegal_pr_release(ctsio);
8640 			ctl_done((union ctl_io *)ctsio);
8641 			return (CTL_RETVAL_COMPLETE);
8642 		}
8643 
8644 		/* okay to release */
8645 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8646 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8647 		lun->res_type = 0;
8648 
8649 		/*
8650 		 * if this isn't an exclusive access
8651 		 * res generate UA for all other
8652 		 * registrants.
8653 		 */
8654 		if (type != SPR_TYPE_EX_AC
8655 		 && type != SPR_TYPE_WR_EX) {
8656 			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8657 				if (i == residx ||
8658 				    ctl_get_prkey(lun,
8659 				     i + softc->persis_offset) == 0)
8660 					continue;
8661 				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8662 			}
8663 		}
8664 		mtx_unlock(&lun->lun_lock);
8665 		/* Send msg to other side */
8666 		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8667 		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8668 		persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8669 		if ((isc_retval=ctl_ha_msg_send( CTL_HA_CHAN_CTL, &persis_io,
8670 		     sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8671 			printf("CTL:Persis Out error returned from "
8672 			       "ctl_ha_msg_send %d\n", isc_retval);
8673 		}
8674 		break;
8675 
8676 	case SPRO_CLEAR:
8677 		/* send msg to other side */
8678 
8679 		mtx_lock(&lun->lun_lock);
8680 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8681 		lun->res_type = 0;
8682 		lun->pr_key_count = 0;
8683 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8684 
8685 		ctl_clr_prkey(lun, residx);
8686 		for (i=0; i < 2*CTL_MAX_INITIATORS; i++)
8687 			if (ctl_get_prkey(lun, i) != 0) {
8688 				ctl_clr_prkey(lun, i);
8689 				ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8690 			}
8691 		lun->PRGeneration++;
8692 		mtx_unlock(&lun->lun_lock);
8693 		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8694 		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8695 		persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8696 		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8697 		     sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8698 			printf("CTL:Persis Out error returned from "
8699 			       "ctl_ha_msg_send %d\n", isc_retval);
8700 		}
8701 		break;
8702 
8703 	case SPRO_PREEMPT:
8704 	case SPRO_PRE_ABO: {
8705 		int nretval;
8706 
8707 		nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8708 					  residx, ctsio, cdb, param);
8709 		if (nretval != 0)
8710 			return (CTL_RETVAL_COMPLETE);
8711 		break;
8712 	}
8713 	default:
8714 		panic("Invalid PR type %x", cdb->action);
8715 	}
8716 
8717 done:
8718 	free(ctsio->kern_data_ptr, M_CTL);
8719 	ctl_set_success(ctsio);
8720 	ctl_done((union ctl_io *)ctsio);
8721 
8722 	return (retval);
8723 }
8724 
8725 /*
8726  * This routine is for handling a message from the other SC pertaining to
8727  * persistent reserve out. All the error checking will have been done
8728  * so only perorming the action need be done here to keep the two
8729  * in sync.
8730  */
8731 static void
8732 ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg)
8733 {
8734 	struct ctl_lun *lun;
8735 	struct ctl_softc *softc;
8736 	int i;
8737 	uint32_t targ_lun;
8738 
8739 	softc = control_softc;
8740 
8741 	targ_lun = msg->hdr.nexus.targ_mapped_lun;
8742 	lun = softc->ctl_luns[targ_lun];
8743 	mtx_lock(&lun->lun_lock);
8744 	switch(msg->pr.pr_info.action) {
8745 	case CTL_PR_REG_KEY:
8746 		ctl_alloc_prkey(lun, msg->pr.pr_info.residx);
8747 		if (ctl_get_prkey(lun, msg->pr.pr_info.residx) == 0)
8748 			lun->pr_key_count++;
8749 		ctl_set_prkey(lun, msg->pr.pr_info.residx,
8750 		    scsi_8btou64(msg->pr.pr_info.sa_res_key));
8751 		lun->PRGeneration++;
8752 		break;
8753 
8754 	case CTL_PR_UNREG_KEY:
8755 		ctl_clr_prkey(lun, msg->pr.pr_info.residx);
8756 		lun->pr_key_count--;
8757 
8758 		/* XXX Need to see if the reservation has been released */
8759 		/* if so do we need to generate UA? */
8760 		if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8761 			lun->flags &= ~CTL_LUN_PR_RESERVED;
8762 			lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8763 
8764 			if ((lun->res_type == SPR_TYPE_WR_EX_RO
8765 			  || lun->res_type == SPR_TYPE_EX_AC_RO)
8766 			 && lun->pr_key_count) {
8767 				/*
8768 				 * If the reservation is a registrants
8769 				 * only type we need to generate a UA
8770 				 * for other registered inits.  The
8771 				 * sense code should be RESERVATIONS
8772 				 * RELEASED
8773 				 */
8774 
8775 				for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8776 					if (ctl_get_prkey(lun, i +
8777 					    softc->persis_offset) == 0)
8778 						continue;
8779 
8780 					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8781 				}
8782 			}
8783 			lun->res_type = 0;
8784 		} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8785 			if (lun->pr_key_count==0) {
8786 				lun->flags &= ~CTL_LUN_PR_RESERVED;
8787 				lun->res_type = 0;
8788 				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8789 			}
8790 		}
8791 		lun->PRGeneration++;
8792 		break;
8793 
8794 	case CTL_PR_RESERVE:
8795 		lun->flags |= CTL_LUN_PR_RESERVED;
8796 		lun->res_type = msg->pr.pr_info.res_type;
8797 		lun->pr_res_idx = msg->pr.pr_info.residx;
8798 
8799 		break;
8800 
8801 	case CTL_PR_RELEASE:
8802 		/*
8803 		 * if this isn't an exclusive access res generate UA for all
8804 		 * other registrants.
8805 		 */
8806 		if (lun->res_type != SPR_TYPE_EX_AC
8807 		 && lun->res_type != SPR_TYPE_WR_EX) {
8808 			for (i = 0; i < CTL_MAX_INITIATORS; i++)
8809 				if (ctl_get_prkey(lun, i + softc->persis_offset) != 0)
8810 					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8811 		}
8812 
8813 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8814 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8815 		lun->res_type = 0;
8816 		break;
8817 
8818 	case CTL_PR_PREEMPT:
8819 		ctl_pro_preempt_other(lun, msg);
8820 		break;
8821 	case CTL_PR_CLEAR:
8822 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8823 		lun->res_type = 0;
8824 		lun->pr_key_count = 0;
8825 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8826 
8827 		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8828 			if (ctl_get_prkey(lun, i) == 0)
8829 				continue;
8830 			ctl_clr_prkey(lun, i);
8831 			ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8832 		}
8833 		lun->PRGeneration++;
8834 		break;
8835 	}
8836 
8837 	mtx_unlock(&lun->lun_lock);
8838 }
8839 
8840 int
8841 ctl_read_write(struct ctl_scsiio *ctsio)
8842 {
8843 	struct ctl_lun *lun;
8844 	struct ctl_lba_len_flags *lbalen;
8845 	uint64_t lba;
8846 	uint32_t num_blocks;
8847 	int flags, retval;
8848 	int isread;
8849 
8850 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8851 
8852 	CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8853 
8854 	flags = 0;
8855 	retval = CTL_RETVAL_COMPLETE;
8856 
8857 	isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8858 	      || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8859 	switch (ctsio->cdb[0]) {
8860 	case READ_6:
8861 	case WRITE_6: {
8862 		struct scsi_rw_6 *cdb;
8863 
8864 		cdb = (struct scsi_rw_6 *)ctsio->cdb;
8865 
8866 		lba = scsi_3btoul(cdb->addr);
8867 		/* only 5 bits are valid in the most significant address byte */
8868 		lba &= 0x1fffff;
8869 		num_blocks = cdb->length;
8870 		/*
8871 		 * This is correct according to SBC-2.
8872 		 */
8873 		if (num_blocks == 0)
8874 			num_blocks = 256;
8875 		break;
8876 	}
8877 	case READ_10:
8878 	case WRITE_10: {
8879 		struct scsi_rw_10 *cdb;
8880 
8881 		cdb = (struct scsi_rw_10 *)ctsio->cdb;
8882 		if (cdb->byte2 & SRW10_FUA)
8883 			flags |= CTL_LLF_FUA;
8884 		if (cdb->byte2 & SRW10_DPO)
8885 			flags |= CTL_LLF_DPO;
8886 		lba = scsi_4btoul(cdb->addr);
8887 		num_blocks = scsi_2btoul(cdb->length);
8888 		break;
8889 	}
8890 	case WRITE_VERIFY_10: {
8891 		struct scsi_write_verify_10 *cdb;
8892 
8893 		cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
8894 		flags |= CTL_LLF_FUA;
8895 		if (cdb->byte2 & SWV_DPO)
8896 			flags |= CTL_LLF_DPO;
8897 		lba = scsi_4btoul(cdb->addr);
8898 		num_blocks = scsi_2btoul(cdb->length);
8899 		break;
8900 	}
8901 	case READ_12:
8902 	case WRITE_12: {
8903 		struct scsi_rw_12 *cdb;
8904 
8905 		cdb = (struct scsi_rw_12 *)ctsio->cdb;
8906 		if (cdb->byte2 & SRW12_FUA)
8907 			flags |= CTL_LLF_FUA;
8908 		if (cdb->byte2 & SRW12_DPO)
8909 			flags |= CTL_LLF_DPO;
8910 		lba = scsi_4btoul(cdb->addr);
8911 		num_blocks = scsi_4btoul(cdb->length);
8912 		break;
8913 	}
8914 	case WRITE_VERIFY_12: {
8915 		struct scsi_write_verify_12 *cdb;
8916 
8917 		cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
8918 		flags |= CTL_LLF_FUA;
8919 		if (cdb->byte2 & SWV_DPO)
8920 			flags |= CTL_LLF_DPO;
8921 		lba = scsi_4btoul(cdb->addr);
8922 		num_blocks = scsi_4btoul(cdb->length);
8923 		break;
8924 	}
8925 	case READ_16:
8926 	case WRITE_16: {
8927 		struct scsi_rw_16 *cdb;
8928 
8929 		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8930 		if (cdb->byte2 & SRW12_FUA)
8931 			flags |= CTL_LLF_FUA;
8932 		if (cdb->byte2 & SRW12_DPO)
8933 			flags |= CTL_LLF_DPO;
8934 		lba = scsi_8btou64(cdb->addr);
8935 		num_blocks = scsi_4btoul(cdb->length);
8936 		break;
8937 	}
8938 	case WRITE_ATOMIC_16: {
8939 		struct scsi_rw_16 *cdb;
8940 
8941 		if (lun->be_lun->atomicblock == 0) {
8942 			ctl_set_invalid_opcode(ctsio);
8943 			ctl_done((union ctl_io *)ctsio);
8944 			return (CTL_RETVAL_COMPLETE);
8945 		}
8946 
8947 		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8948 		if (cdb->byte2 & SRW12_FUA)
8949 			flags |= CTL_LLF_FUA;
8950 		if (cdb->byte2 & SRW12_DPO)
8951 			flags |= CTL_LLF_DPO;
8952 		lba = scsi_8btou64(cdb->addr);
8953 		num_blocks = scsi_4btoul(cdb->length);
8954 		if (num_blocks > lun->be_lun->atomicblock) {
8955 			ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
8956 			    /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
8957 			    /*bit*/ 0);
8958 			ctl_done((union ctl_io *)ctsio);
8959 			return (CTL_RETVAL_COMPLETE);
8960 		}
8961 		break;
8962 	}
8963 	case WRITE_VERIFY_16: {
8964 		struct scsi_write_verify_16 *cdb;
8965 
8966 		cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
8967 		flags |= CTL_LLF_FUA;
8968 		if (cdb->byte2 & SWV_DPO)
8969 			flags |= CTL_LLF_DPO;
8970 		lba = scsi_8btou64(cdb->addr);
8971 		num_blocks = scsi_4btoul(cdb->length);
8972 		break;
8973 	}
8974 	default:
8975 		/*
8976 		 * We got a command we don't support.  This shouldn't
8977 		 * happen, commands should be filtered out above us.
8978 		 */
8979 		ctl_set_invalid_opcode(ctsio);
8980 		ctl_done((union ctl_io *)ctsio);
8981 
8982 		return (CTL_RETVAL_COMPLETE);
8983 		break; /* NOTREACHED */
8984 	}
8985 
8986 	/*
8987 	 * The first check is to make sure we're in bounds, the second
8988 	 * check is to catch wrap-around problems.  If the lba + num blocks
8989 	 * is less than the lba, then we've wrapped around and the block
8990 	 * range is invalid anyway.
8991 	 */
8992 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8993 	 || ((lba + num_blocks) < lba)) {
8994 		ctl_set_lba_out_of_range(ctsio);
8995 		ctl_done((union ctl_io *)ctsio);
8996 		return (CTL_RETVAL_COMPLETE);
8997 	}
8998 
8999 	/*
9000 	 * According to SBC-3, a transfer length of 0 is not an error.
9001 	 * Note that this cannot happen with WRITE(6) or READ(6), since 0
9002 	 * translates to 256 blocks for those commands.
9003 	 */
9004 	if (num_blocks == 0) {
9005 		ctl_set_success(ctsio);
9006 		ctl_done((union ctl_io *)ctsio);
9007 		return (CTL_RETVAL_COMPLETE);
9008 	}
9009 
9010 	/* Set FUA and/or DPO if caches are disabled. */
9011 	if (isread) {
9012 		if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9013 		    SCP_RCD) != 0)
9014 			flags |= CTL_LLF_FUA | CTL_LLF_DPO;
9015 	} else {
9016 		if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9017 		    SCP_WCE) == 0)
9018 			flags |= CTL_LLF_FUA;
9019 	}
9020 
9021 	lbalen = (struct ctl_lba_len_flags *)
9022 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9023 	lbalen->lba = lba;
9024 	lbalen->len = num_blocks;
9025 	lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
9026 
9027 	ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9028 	ctsio->kern_rel_offset = 0;
9029 
9030 	CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
9031 
9032 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9033 
9034 	return (retval);
9035 }
9036 
9037 static int
9038 ctl_cnw_cont(union ctl_io *io)
9039 {
9040 	struct ctl_scsiio *ctsio;
9041 	struct ctl_lun *lun;
9042 	struct ctl_lba_len_flags *lbalen;
9043 	int retval;
9044 
9045 	ctsio = &io->scsiio;
9046 	ctsio->io_hdr.status = CTL_STATUS_NONE;
9047 	ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
9048 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9049 	lbalen = (struct ctl_lba_len_flags *)
9050 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9051 	lbalen->flags &= ~CTL_LLF_COMPARE;
9052 	lbalen->flags |= CTL_LLF_WRITE;
9053 
9054 	CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
9055 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9056 	return (retval);
9057 }
9058 
9059 int
9060 ctl_cnw(struct ctl_scsiio *ctsio)
9061 {
9062 	struct ctl_lun *lun;
9063 	struct ctl_lba_len_flags *lbalen;
9064 	uint64_t lba;
9065 	uint32_t num_blocks;
9066 	int flags, retval;
9067 
9068 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9069 
9070 	CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
9071 
9072 	flags = 0;
9073 	retval = CTL_RETVAL_COMPLETE;
9074 
9075 	switch (ctsio->cdb[0]) {
9076 	case COMPARE_AND_WRITE: {
9077 		struct scsi_compare_and_write *cdb;
9078 
9079 		cdb = (struct scsi_compare_and_write *)ctsio->cdb;
9080 		if (cdb->byte2 & SRW10_FUA)
9081 			flags |= CTL_LLF_FUA;
9082 		if (cdb->byte2 & SRW10_DPO)
9083 			flags |= CTL_LLF_DPO;
9084 		lba = scsi_8btou64(cdb->addr);
9085 		num_blocks = cdb->length;
9086 		break;
9087 	}
9088 	default:
9089 		/*
9090 		 * We got a command we don't support.  This shouldn't
9091 		 * happen, commands should be filtered out above us.
9092 		 */
9093 		ctl_set_invalid_opcode(ctsio);
9094 		ctl_done((union ctl_io *)ctsio);
9095 
9096 		return (CTL_RETVAL_COMPLETE);
9097 		break; /* NOTREACHED */
9098 	}
9099 
9100 	/*
9101 	 * The first check is to make sure we're in bounds, the second
9102 	 * check is to catch wrap-around problems.  If the lba + num blocks
9103 	 * is less than the lba, then we've wrapped around and the block
9104 	 * range is invalid anyway.
9105 	 */
9106 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9107 	 || ((lba + num_blocks) < lba)) {
9108 		ctl_set_lba_out_of_range(ctsio);
9109 		ctl_done((union ctl_io *)ctsio);
9110 		return (CTL_RETVAL_COMPLETE);
9111 	}
9112 
9113 	/*
9114 	 * According to SBC-3, a transfer length of 0 is not an error.
9115 	 */
9116 	if (num_blocks == 0) {
9117 		ctl_set_success(ctsio);
9118 		ctl_done((union ctl_io *)ctsio);
9119 		return (CTL_RETVAL_COMPLETE);
9120 	}
9121 
9122 	/* Set FUA if write cache is disabled. */
9123 	if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9124 	    SCP_WCE) == 0)
9125 		flags |= CTL_LLF_FUA;
9126 
9127 	ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
9128 	ctsio->kern_rel_offset = 0;
9129 
9130 	/*
9131 	 * Set the IO_CONT flag, so that if this I/O gets passed to
9132 	 * ctl_data_submit_done(), it'll get passed back to
9133 	 * ctl_ctl_cnw_cont() for further processing.
9134 	 */
9135 	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
9136 	ctsio->io_cont = ctl_cnw_cont;
9137 
9138 	lbalen = (struct ctl_lba_len_flags *)
9139 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9140 	lbalen->lba = lba;
9141 	lbalen->len = num_blocks;
9142 	lbalen->flags = CTL_LLF_COMPARE | flags;
9143 
9144 	CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
9145 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9146 	return (retval);
9147 }
9148 
9149 int
9150 ctl_verify(struct ctl_scsiio *ctsio)
9151 {
9152 	struct ctl_lun *lun;
9153 	struct ctl_lba_len_flags *lbalen;
9154 	uint64_t lba;
9155 	uint32_t num_blocks;
9156 	int bytchk, flags;
9157 	int retval;
9158 
9159 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9160 
9161 	CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
9162 
9163 	bytchk = 0;
9164 	flags = CTL_LLF_FUA;
9165 	retval = CTL_RETVAL_COMPLETE;
9166 
9167 	switch (ctsio->cdb[0]) {
9168 	case VERIFY_10: {
9169 		struct scsi_verify_10 *cdb;
9170 
9171 		cdb = (struct scsi_verify_10 *)ctsio->cdb;
9172 		if (cdb->byte2 & SVFY_BYTCHK)
9173 			bytchk = 1;
9174 		if (cdb->byte2 & SVFY_DPO)
9175 			flags |= CTL_LLF_DPO;
9176 		lba = scsi_4btoul(cdb->addr);
9177 		num_blocks = scsi_2btoul(cdb->length);
9178 		break;
9179 	}
9180 	case VERIFY_12: {
9181 		struct scsi_verify_12 *cdb;
9182 
9183 		cdb = (struct scsi_verify_12 *)ctsio->cdb;
9184 		if (cdb->byte2 & SVFY_BYTCHK)
9185 			bytchk = 1;
9186 		if (cdb->byte2 & SVFY_DPO)
9187 			flags |= CTL_LLF_DPO;
9188 		lba = scsi_4btoul(cdb->addr);
9189 		num_blocks = scsi_4btoul(cdb->length);
9190 		break;
9191 	}
9192 	case VERIFY_16: {
9193 		struct scsi_rw_16 *cdb;
9194 
9195 		cdb = (struct scsi_rw_16 *)ctsio->cdb;
9196 		if (cdb->byte2 & SVFY_BYTCHK)
9197 			bytchk = 1;
9198 		if (cdb->byte2 & SVFY_DPO)
9199 			flags |= CTL_LLF_DPO;
9200 		lba = scsi_8btou64(cdb->addr);
9201 		num_blocks = scsi_4btoul(cdb->length);
9202 		break;
9203 	}
9204 	default:
9205 		/*
9206 		 * We got a command we don't support.  This shouldn't
9207 		 * happen, commands should be filtered out above us.
9208 		 */
9209 		ctl_set_invalid_opcode(ctsio);
9210 		ctl_done((union ctl_io *)ctsio);
9211 		return (CTL_RETVAL_COMPLETE);
9212 	}
9213 
9214 	/*
9215 	 * The first check is to make sure we're in bounds, the second
9216 	 * check is to catch wrap-around problems.  If the lba + num blocks
9217 	 * is less than the lba, then we've wrapped around and the block
9218 	 * range is invalid anyway.
9219 	 */
9220 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9221 	 || ((lba + num_blocks) < lba)) {
9222 		ctl_set_lba_out_of_range(ctsio);
9223 		ctl_done((union ctl_io *)ctsio);
9224 		return (CTL_RETVAL_COMPLETE);
9225 	}
9226 
9227 	/*
9228 	 * According to SBC-3, a transfer length of 0 is not an error.
9229 	 */
9230 	if (num_blocks == 0) {
9231 		ctl_set_success(ctsio);
9232 		ctl_done((union ctl_io *)ctsio);
9233 		return (CTL_RETVAL_COMPLETE);
9234 	}
9235 
9236 	lbalen = (struct ctl_lba_len_flags *)
9237 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9238 	lbalen->lba = lba;
9239 	lbalen->len = num_blocks;
9240 	if (bytchk) {
9241 		lbalen->flags = CTL_LLF_COMPARE | flags;
9242 		ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9243 	} else {
9244 		lbalen->flags = CTL_LLF_VERIFY | flags;
9245 		ctsio->kern_total_len = 0;
9246 	}
9247 	ctsio->kern_rel_offset = 0;
9248 
9249 	CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9250 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9251 	return (retval);
9252 }
9253 
9254 int
9255 ctl_report_luns(struct ctl_scsiio *ctsio)
9256 {
9257 	struct ctl_softc *softc = control_softc;
9258 	struct scsi_report_luns *cdb;
9259 	struct scsi_report_luns_data *lun_data;
9260 	struct ctl_lun *lun, *request_lun;
9261 	int num_luns, retval;
9262 	uint32_t alloc_len, lun_datalen;
9263 	int num_filled, well_known;
9264 	uint32_t initidx, targ_lun_id, lun_id;
9265 
9266 	retval = CTL_RETVAL_COMPLETE;
9267 	well_known = 0;
9268 
9269 	cdb = (struct scsi_report_luns *)ctsio->cdb;
9270 
9271 	CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9272 
9273 	mtx_lock(&softc->ctl_lock);
9274 	num_luns = softc->num_luns;
9275 	mtx_unlock(&softc->ctl_lock);
9276 
9277 	switch (cdb->select_report) {
9278 	case RPL_REPORT_DEFAULT:
9279 	case RPL_REPORT_ALL:
9280 		break;
9281 	case RPL_REPORT_WELLKNOWN:
9282 		well_known = 1;
9283 		num_luns = 0;
9284 		break;
9285 	default:
9286 		ctl_set_invalid_field(ctsio,
9287 				      /*sks_valid*/ 1,
9288 				      /*command*/ 1,
9289 				      /*field*/ 2,
9290 				      /*bit_valid*/ 0,
9291 				      /*bit*/ 0);
9292 		ctl_done((union ctl_io *)ctsio);
9293 		return (retval);
9294 		break; /* NOTREACHED */
9295 	}
9296 
9297 	alloc_len = scsi_4btoul(cdb->length);
9298 	/*
9299 	 * The initiator has to allocate at least 16 bytes for this request,
9300 	 * so he can at least get the header and the first LUN.  Otherwise
9301 	 * we reject the request (per SPC-3 rev 14, section 6.21).
9302 	 */
9303 	if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9304 	    sizeof(struct scsi_report_luns_lundata))) {
9305 		ctl_set_invalid_field(ctsio,
9306 				      /*sks_valid*/ 1,
9307 				      /*command*/ 1,
9308 				      /*field*/ 6,
9309 				      /*bit_valid*/ 0,
9310 				      /*bit*/ 0);
9311 		ctl_done((union ctl_io *)ctsio);
9312 		return (retval);
9313 	}
9314 
9315 	request_lun = (struct ctl_lun *)
9316 		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9317 
9318 	lun_datalen = sizeof(*lun_data) +
9319 		(num_luns * sizeof(struct scsi_report_luns_lundata));
9320 
9321 	ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9322 	lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9323 	ctsio->kern_sg_entries = 0;
9324 
9325 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9326 
9327 	mtx_lock(&softc->ctl_lock);
9328 	for (targ_lun_id = 0, num_filled = 0; targ_lun_id < CTL_MAX_LUNS && num_filled < num_luns; targ_lun_id++) {
9329 		lun_id = ctl_map_lun(softc, ctsio->io_hdr.nexus.targ_port,
9330 		    targ_lun_id);
9331 		if (lun_id >= CTL_MAX_LUNS)
9332 			continue;
9333 		lun = softc->ctl_luns[lun_id];
9334 		if (lun == NULL)
9335 			continue;
9336 
9337 		if (targ_lun_id <= 0xff) {
9338 			/*
9339 			 * Peripheral addressing method, bus number 0.
9340 			 */
9341 			lun_data->luns[num_filled].lundata[0] =
9342 				RPL_LUNDATA_ATYP_PERIPH;
9343 			lun_data->luns[num_filled].lundata[1] = targ_lun_id;
9344 			num_filled++;
9345 		} else if (targ_lun_id <= 0x3fff) {
9346 			/*
9347 			 * Flat addressing method.
9348 			 */
9349 			lun_data->luns[num_filled].lundata[0] =
9350 				RPL_LUNDATA_ATYP_FLAT | (targ_lun_id >> 8);
9351 			lun_data->luns[num_filled].lundata[1] =
9352 				(targ_lun_id & 0xff);
9353 			num_filled++;
9354 		} else if (targ_lun_id <= 0xffffff) {
9355 			/*
9356 			 * Extended flat addressing method.
9357 			 */
9358 			lun_data->luns[num_filled].lundata[0] =
9359 			    RPL_LUNDATA_ATYP_EXTLUN | 0x12;
9360 			scsi_ulto3b(targ_lun_id,
9361 			    &lun_data->luns[num_filled].lundata[1]);
9362 			num_filled++;
9363 		} else {
9364 			printf("ctl_report_luns: bogus LUN number %jd, "
9365 			       "skipping\n", (intmax_t)targ_lun_id);
9366 		}
9367 		/*
9368 		 * According to SPC-3, rev 14 section 6.21:
9369 		 *
9370 		 * "The execution of a REPORT LUNS command to any valid and
9371 		 * installed logical unit shall clear the REPORTED LUNS DATA
9372 		 * HAS CHANGED unit attention condition for all logical
9373 		 * units of that target with respect to the requesting
9374 		 * initiator. A valid and installed logical unit is one
9375 		 * having a PERIPHERAL QUALIFIER of 000b in the standard
9376 		 * INQUIRY data (see 6.4.2)."
9377 		 *
9378 		 * If request_lun is NULL, the LUN this report luns command
9379 		 * was issued to is either disabled or doesn't exist. In that
9380 		 * case, we shouldn't clear any pending lun change unit
9381 		 * attention.
9382 		 */
9383 		if (request_lun != NULL) {
9384 			mtx_lock(&lun->lun_lock);
9385 			ctl_clr_ua(lun, initidx, CTL_UA_RES_RELEASE);
9386 			mtx_unlock(&lun->lun_lock);
9387 		}
9388 	}
9389 	mtx_unlock(&softc->ctl_lock);
9390 
9391 	/*
9392 	 * It's quite possible that we've returned fewer LUNs than we allocated
9393 	 * space for.  Trim it.
9394 	 */
9395 	lun_datalen = sizeof(*lun_data) +
9396 		(num_filled * sizeof(struct scsi_report_luns_lundata));
9397 
9398 	if (lun_datalen < alloc_len) {
9399 		ctsio->residual = alloc_len - lun_datalen;
9400 		ctsio->kern_data_len = lun_datalen;
9401 		ctsio->kern_total_len = lun_datalen;
9402 	} else {
9403 		ctsio->residual = 0;
9404 		ctsio->kern_data_len = alloc_len;
9405 		ctsio->kern_total_len = alloc_len;
9406 	}
9407 	ctsio->kern_data_resid = 0;
9408 	ctsio->kern_rel_offset = 0;
9409 	ctsio->kern_sg_entries = 0;
9410 
9411 	/*
9412 	 * We set this to the actual data length, regardless of how much
9413 	 * space we actually have to return results.  If the user looks at
9414 	 * this value, he'll know whether or not he allocated enough space
9415 	 * and reissue the command if necessary.  We don't support well
9416 	 * known logical units, so if the user asks for that, return none.
9417 	 */
9418 	scsi_ulto4b(lun_datalen - 8, lun_data->length);
9419 
9420 	/*
9421 	 * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9422 	 * this request.
9423 	 */
9424 	ctl_set_success(ctsio);
9425 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9426 	ctsio->be_move_done = ctl_config_move_done;
9427 	ctl_datamove((union ctl_io *)ctsio);
9428 	return (retval);
9429 }
9430 
9431 int
9432 ctl_request_sense(struct ctl_scsiio *ctsio)
9433 {
9434 	struct scsi_request_sense *cdb;
9435 	struct scsi_sense_data *sense_ptr;
9436 	struct ctl_lun *lun;
9437 	uint32_t initidx;
9438 	int have_error;
9439 	scsi_sense_data_type sense_format;
9440 	ctl_ua_type ua_type;
9441 
9442 	cdb = (struct scsi_request_sense *)ctsio->cdb;
9443 
9444 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9445 
9446 	CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9447 
9448 	/*
9449 	 * Determine which sense format the user wants.
9450 	 */
9451 	if (cdb->byte2 & SRS_DESC)
9452 		sense_format = SSD_TYPE_DESC;
9453 	else
9454 		sense_format = SSD_TYPE_FIXED;
9455 
9456 	ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9457 	sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9458 	ctsio->kern_sg_entries = 0;
9459 
9460 	/*
9461 	 * struct scsi_sense_data, which is currently set to 256 bytes, is
9462 	 * larger than the largest allowed value for the length field in the
9463 	 * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9464 	 */
9465 	ctsio->residual = 0;
9466 	ctsio->kern_data_len = cdb->length;
9467 	ctsio->kern_total_len = cdb->length;
9468 
9469 	ctsio->kern_data_resid = 0;
9470 	ctsio->kern_rel_offset = 0;
9471 	ctsio->kern_sg_entries = 0;
9472 
9473 	/*
9474 	 * If we don't have a LUN, we don't have any pending sense.
9475 	 */
9476 	if (lun == NULL)
9477 		goto no_sense;
9478 
9479 	have_error = 0;
9480 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9481 	/*
9482 	 * Check for pending sense, and then for pending unit attentions.
9483 	 * Pending sense gets returned first, then pending unit attentions.
9484 	 */
9485 	mtx_lock(&lun->lun_lock);
9486 #ifdef CTL_WITH_CA
9487 	if (ctl_is_set(lun->have_ca, initidx)) {
9488 		scsi_sense_data_type stored_format;
9489 
9490 		/*
9491 		 * Check to see which sense format was used for the stored
9492 		 * sense data.
9493 		 */
9494 		stored_format = scsi_sense_type(&lun->pending_sense[initidx]);
9495 
9496 		/*
9497 		 * If the user requested a different sense format than the
9498 		 * one we stored, then we need to convert it to the other
9499 		 * format.  If we're going from descriptor to fixed format
9500 		 * sense data, we may lose things in translation, depending
9501 		 * on what options were used.
9502 		 *
9503 		 * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9504 		 * for some reason we'll just copy it out as-is.
9505 		 */
9506 		if ((stored_format == SSD_TYPE_FIXED)
9507 		 && (sense_format == SSD_TYPE_DESC))
9508 			ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9509 			    &lun->pending_sense[initidx],
9510 			    (struct scsi_sense_data_desc *)sense_ptr);
9511 		else if ((stored_format == SSD_TYPE_DESC)
9512 		      && (sense_format == SSD_TYPE_FIXED))
9513 			ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9514 			    &lun->pending_sense[initidx],
9515 			    (struct scsi_sense_data_fixed *)sense_ptr);
9516 		else
9517 			memcpy(sense_ptr, &lun->pending_sense[initidx],
9518 			       MIN(sizeof(*sense_ptr),
9519 			       sizeof(lun->pending_sense[initidx])));
9520 
9521 		ctl_clear_mask(lun->have_ca, initidx);
9522 		have_error = 1;
9523 	} else
9524 #endif
9525 	{
9526 		ua_type = ctl_build_ua(lun, initidx, sense_ptr, sense_format);
9527 		if (ua_type != CTL_UA_NONE)
9528 			have_error = 1;
9529 	}
9530 	mtx_unlock(&lun->lun_lock);
9531 
9532 	/*
9533 	 * We already have a pending error, return it.
9534 	 */
9535 	if (have_error != 0) {
9536 		/*
9537 		 * We report the SCSI status as OK, since the status of the
9538 		 * request sense command itself is OK.
9539 		 * We report 0 for the sense length, because we aren't doing
9540 		 * autosense in this case.  We're reporting sense as
9541 		 * parameter data.
9542 		 */
9543 		ctl_set_success(ctsio);
9544 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9545 		ctsio->be_move_done = ctl_config_move_done;
9546 		ctl_datamove((union ctl_io *)ctsio);
9547 		return (CTL_RETVAL_COMPLETE);
9548 	}
9549 
9550 no_sense:
9551 
9552 	/*
9553 	 * No sense information to report, so we report that everything is
9554 	 * okay.
9555 	 */
9556 	ctl_set_sense_data(sense_ptr,
9557 			   lun,
9558 			   sense_format,
9559 			   /*current_error*/ 1,
9560 			   /*sense_key*/ SSD_KEY_NO_SENSE,
9561 			   /*asc*/ 0x00,
9562 			   /*ascq*/ 0x00,
9563 			   SSD_ELEM_NONE);
9564 
9565 	/*
9566 	 * We report 0 for the sense length, because we aren't doing
9567 	 * autosense in this case.  We're reporting sense as parameter data.
9568 	 */
9569 	ctl_set_success(ctsio);
9570 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9571 	ctsio->be_move_done = ctl_config_move_done;
9572 	ctl_datamove((union ctl_io *)ctsio);
9573 	return (CTL_RETVAL_COMPLETE);
9574 }
9575 
9576 int
9577 ctl_tur(struct ctl_scsiio *ctsio)
9578 {
9579 
9580 	CTL_DEBUG_PRINT(("ctl_tur\n"));
9581 
9582 	ctl_set_success(ctsio);
9583 	ctl_done((union ctl_io *)ctsio);
9584 
9585 	return (CTL_RETVAL_COMPLETE);
9586 }
9587 
9588 #ifdef notyet
9589 static int
9590 ctl_cmddt_inquiry(struct ctl_scsiio *ctsio)
9591 {
9592 
9593 }
9594 #endif
9595 
9596 static int
9597 ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9598 {
9599 	struct scsi_vpd_supported_pages *pages;
9600 	int sup_page_size;
9601 	struct ctl_lun *lun;
9602 	int p;
9603 
9604 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9605 
9606 	sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9607 	    SCSI_EVPD_NUM_SUPPORTED_PAGES;
9608 	ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9609 	pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9610 	ctsio->kern_sg_entries = 0;
9611 
9612 	if (sup_page_size < alloc_len) {
9613 		ctsio->residual = alloc_len - sup_page_size;
9614 		ctsio->kern_data_len = sup_page_size;
9615 		ctsio->kern_total_len = sup_page_size;
9616 	} else {
9617 		ctsio->residual = 0;
9618 		ctsio->kern_data_len = alloc_len;
9619 		ctsio->kern_total_len = alloc_len;
9620 	}
9621 	ctsio->kern_data_resid = 0;
9622 	ctsio->kern_rel_offset = 0;
9623 	ctsio->kern_sg_entries = 0;
9624 
9625 	/*
9626 	 * The control device is always connected.  The disk device, on the
9627 	 * other hand, may not be online all the time.  Need to change this
9628 	 * to figure out whether the disk device is actually online or not.
9629 	 */
9630 	if (lun != NULL)
9631 		pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9632 				lun->be_lun->lun_type;
9633 	else
9634 		pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9635 
9636 	p = 0;
9637 	/* Supported VPD pages */
9638 	pages->page_list[p++] = SVPD_SUPPORTED_PAGES;
9639 	/* Serial Number */
9640 	pages->page_list[p++] = SVPD_UNIT_SERIAL_NUMBER;
9641 	/* Device Identification */
9642 	pages->page_list[p++] = SVPD_DEVICE_ID;
9643 	/* Extended INQUIRY Data */
9644 	pages->page_list[p++] = SVPD_EXTENDED_INQUIRY_DATA;
9645 	/* Mode Page Policy */
9646 	pages->page_list[p++] = SVPD_MODE_PAGE_POLICY;
9647 	/* SCSI Ports */
9648 	pages->page_list[p++] = SVPD_SCSI_PORTS;
9649 	/* Third-party Copy */
9650 	pages->page_list[p++] = SVPD_SCSI_TPC;
9651 	if (lun != NULL && lun->be_lun->lun_type == T_DIRECT) {
9652 		/* Block limits */
9653 		pages->page_list[p++] = SVPD_BLOCK_LIMITS;
9654 		/* Block Device Characteristics */
9655 		pages->page_list[p++] = SVPD_BDC;
9656 		/* Logical Block Provisioning */
9657 		pages->page_list[p++] = SVPD_LBP;
9658 	}
9659 	pages->length = p;
9660 
9661 	ctl_set_success(ctsio);
9662 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9663 	ctsio->be_move_done = ctl_config_move_done;
9664 	ctl_datamove((union ctl_io *)ctsio);
9665 	return (CTL_RETVAL_COMPLETE);
9666 }
9667 
9668 static int
9669 ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9670 {
9671 	struct scsi_vpd_unit_serial_number *sn_ptr;
9672 	struct ctl_lun *lun;
9673 	int data_len;
9674 
9675 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9676 
9677 	data_len = 4 + CTL_SN_LEN;
9678 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9679 	sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9680 	if (data_len < alloc_len) {
9681 		ctsio->residual = alloc_len - data_len;
9682 		ctsio->kern_data_len = data_len;
9683 		ctsio->kern_total_len = data_len;
9684 	} else {
9685 		ctsio->residual = 0;
9686 		ctsio->kern_data_len = alloc_len;
9687 		ctsio->kern_total_len = alloc_len;
9688 	}
9689 	ctsio->kern_data_resid = 0;
9690 	ctsio->kern_rel_offset = 0;
9691 	ctsio->kern_sg_entries = 0;
9692 
9693 	/*
9694 	 * The control device is always connected.  The disk device, on the
9695 	 * other hand, may not be online all the time.  Need to change this
9696 	 * to figure out whether the disk device is actually online or not.
9697 	 */
9698 	if (lun != NULL)
9699 		sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9700 				  lun->be_lun->lun_type;
9701 	else
9702 		sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9703 
9704 	sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9705 	sn_ptr->length = CTL_SN_LEN;
9706 	/*
9707 	 * If we don't have a LUN, we just leave the serial number as
9708 	 * all spaces.
9709 	 */
9710 	if (lun != NULL) {
9711 		strncpy((char *)sn_ptr->serial_num,
9712 			(char *)lun->be_lun->serial_num, CTL_SN_LEN);
9713 	} else
9714 		memset(sn_ptr->serial_num, 0x20, CTL_SN_LEN);
9715 
9716 	ctl_set_success(ctsio);
9717 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9718 	ctsio->be_move_done = ctl_config_move_done;
9719 	ctl_datamove((union ctl_io *)ctsio);
9720 	return (CTL_RETVAL_COMPLETE);
9721 }
9722 
9723 
9724 static int
9725 ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9726 {
9727 	struct scsi_vpd_extended_inquiry_data *eid_ptr;
9728 	struct ctl_lun *lun;
9729 	int data_len;
9730 
9731 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9732 
9733 	data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
9734 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9735 	eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9736 	ctsio->kern_sg_entries = 0;
9737 
9738 	if (data_len < alloc_len) {
9739 		ctsio->residual = alloc_len - data_len;
9740 		ctsio->kern_data_len = data_len;
9741 		ctsio->kern_total_len = data_len;
9742 	} else {
9743 		ctsio->residual = 0;
9744 		ctsio->kern_data_len = alloc_len;
9745 		ctsio->kern_total_len = alloc_len;
9746 	}
9747 	ctsio->kern_data_resid = 0;
9748 	ctsio->kern_rel_offset = 0;
9749 	ctsio->kern_sg_entries = 0;
9750 
9751 	/*
9752 	 * The control device is always connected.  The disk device, on the
9753 	 * other hand, may not be online all the time.
9754 	 */
9755 	if (lun != NULL)
9756 		eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9757 				     lun->be_lun->lun_type;
9758 	else
9759 		eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9760 	eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9761 	eid_ptr->page_length = data_len - 4;
9762 	eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9763 	eid_ptr->flags3 = SVPD_EID_V_SUP;
9764 
9765 	ctl_set_success(ctsio);
9766 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9767 	ctsio->be_move_done = ctl_config_move_done;
9768 	ctl_datamove((union ctl_io *)ctsio);
9769 	return (CTL_RETVAL_COMPLETE);
9770 }
9771 
9772 static int
9773 ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
9774 {
9775 	struct scsi_vpd_mode_page_policy *mpp_ptr;
9776 	struct ctl_lun *lun;
9777 	int data_len;
9778 
9779 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9780 
9781 	data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9782 	    sizeof(struct scsi_vpd_mode_page_policy_descr);
9783 
9784 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9785 	mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
9786 	ctsio->kern_sg_entries = 0;
9787 
9788 	if (data_len < alloc_len) {
9789 		ctsio->residual = alloc_len - data_len;
9790 		ctsio->kern_data_len = data_len;
9791 		ctsio->kern_total_len = data_len;
9792 	} else {
9793 		ctsio->residual = 0;
9794 		ctsio->kern_data_len = alloc_len;
9795 		ctsio->kern_total_len = alloc_len;
9796 	}
9797 	ctsio->kern_data_resid = 0;
9798 	ctsio->kern_rel_offset = 0;
9799 	ctsio->kern_sg_entries = 0;
9800 
9801 	/*
9802 	 * The control device is always connected.  The disk device, on the
9803 	 * other hand, may not be online all the time.
9804 	 */
9805 	if (lun != NULL)
9806 		mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9807 				     lun->be_lun->lun_type;
9808 	else
9809 		mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9810 	mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
9811 	scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
9812 	mpp_ptr->descr[0].page_code = 0x3f;
9813 	mpp_ptr->descr[0].subpage_code = 0xff;
9814 	mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
9815 
9816 	ctl_set_success(ctsio);
9817 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9818 	ctsio->be_move_done = ctl_config_move_done;
9819 	ctl_datamove((union ctl_io *)ctsio);
9820 	return (CTL_RETVAL_COMPLETE);
9821 }
9822 
9823 static int
9824 ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9825 {
9826 	struct scsi_vpd_device_id *devid_ptr;
9827 	struct scsi_vpd_id_descriptor *desc;
9828 	struct ctl_softc *softc;
9829 	struct ctl_lun *lun;
9830 	struct ctl_port *port;
9831 	int data_len;
9832 	uint8_t proto;
9833 
9834 	softc = control_softc;
9835 
9836 	port = softc->ctl_ports[ctl_port_idx(ctsio->io_hdr.nexus.targ_port)];
9837 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9838 
9839 	data_len = sizeof(struct scsi_vpd_device_id) +
9840 	    sizeof(struct scsi_vpd_id_descriptor) +
9841 		sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9842 	    sizeof(struct scsi_vpd_id_descriptor) +
9843 		sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9844 	if (lun && lun->lun_devid)
9845 		data_len += lun->lun_devid->len;
9846 	if (port->port_devid)
9847 		data_len += port->port_devid->len;
9848 	if (port->target_devid)
9849 		data_len += port->target_devid->len;
9850 
9851 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9852 	devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9853 	ctsio->kern_sg_entries = 0;
9854 
9855 	if (data_len < alloc_len) {
9856 		ctsio->residual = alloc_len - data_len;
9857 		ctsio->kern_data_len = data_len;
9858 		ctsio->kern_total_len = data_len;
9859 	} else {
9860 		ctsio->residual = 0;
9861 		ctsio->kern_data_len = alloc_len;
9862 		ctsio->kern_total_len = alloc_len;
9863 	}
9864 	ctsio->kern_data_resid = 0;
9865 	ctsio->kern_rel_offset = 0;
9866 	ctsio->kern_sg_entries = 0;
9867 
9868 	/*
9869 	 * The control device is always connected.  The disk device, on the
9870 	 * other hand, may not be online all the time.
9871 	 */
9872 	if (lun != NULL)
9873 		devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9874 				     lun->be_lun->lun_type;
9875 	else
9876 		devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9877 	devid_ptr->page_code = SVPD_DEVICE_ID;
9878 	scsi_ulto2b(data_len - 4, devid_ptr->length);
9879 
9880 	if (port->port_type == CTL_PORT_FC)
9881 		proto = SCSI_PROTO_FC << 4;
9882 	else if (port->port_type == CTL_PORT_ISCSI)
9883 		proto = SCSI_PROTO_ISCSI << 4;
9884 	else
9885 		proto = SCSI_PROTO_SPI << 4;
9886 	desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
9887 
9888 	/*
9889 	 * We're using a LUN association here.  i.e., this device ID is a
9890 	 * per-LUN identifier.
9891 	 */
9892 	if (lun && lun->lun_devid) {
9893 		memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
9894 		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9895 		    lun->lun_devid->len);
9896 	}
9897 
9898 	/*
9899 	 * This is for the WWPN which is a port association.
9900 	 */
9901 	if (port->port_devid) {
9902 		memcpy(desc, port->port_devid->data, port->port_devid->len);
9903 		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9904 		    port->port_devid->len);
9905 	}
9906 
9907 	/*
9908 	 * This is for the Relative Target Port(type 4h) identifier
9909 	 */
9910 	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9911 	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9912 	    SVPD_ID_TYPE_RELTARG;
9913 	desc->length = 4;
9914 	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
9915 	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9916 	    sizeof(struct scsi_vpd_id_rel_trgt_port_id));
9917 
9918 	/*
9919 	 * This is for the Target Port Group(type 5h) identifier
9920 	 */
9921 	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9922 	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9923 	    SVPD_ID_TYPE_TPORTGRP;
9924 	desc->length = 4;
9925 	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port / CTL_MAX_PORTS + 1,
9926 	    &desc->identifier[2]);
9927 	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9928 	    sizeof(struct scsi_vpd_id_trgt_port_grp_id));
9929 
9930 	/*
9931 	 * This is for the Target identifier
9932 	 */
9933 	if (port->target_devid) {
9934 		memcpy(desc, port->target_devid->data, port->target_devid->len);
9935 	}
9936 
9937 	ctl_set_success(ctsio);
9938 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9939 	ctsio->be_move_done = ctl_config_move_done;
9940 	ctl_datamove((union ctl_io *)ctsio);
9941 	return (CTL_RETVAL_COMPLETE);
9942 }
9943 
9944 static int
9945 ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
9946 {
9947 	struct ctl_softc *softc = control_softc;
9948 	struct scsi_vpd_scsi_ports *sp;
9949 	struct scsi_vpd_port_designation *pd;
9950 	struct scsi_vpd_port_designation_cont *pdc;
9951 	struct ctl_lun *lun;
9952 	struct ctl_port *port;
9953 	int data_len, num_target_ports, iid_len, id_len, g, pg, p;
9954 	int num_target_port_groups;
9955 
9956 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9957 
9958 	if (softc->is_single)
9959 		num_target_port_groups = 1;
9960 	else
9961 		num_target_port_groups = NUM_TARGET_PORT_GROUPS;
9962 	num_target_ports = 0;
9963 	iid_len = 0;
9964 	id_len = 0;
9965 	mtx_lock(&softc->ctl_lock);
9966 	STAILQ_FOREACH(port, &softc->port_list, links) {
9967 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9968 			continue;
9969 		if (lun != NULL &&
9970 		    ctl_map_lun_back(softc, port->targ_port, lun->lun) >=
9971 		    CTL_MAX_LUNS)
9972 			continue;
9973 		num_target_ports++;
9974 		if (port->init_devid)
9975 			iid_len += port->init_devid->len;
9976 		if (port->port_devid)
9977 			id_len += port->port_devid->len;
9978 	}
9979 	mtx_unlock(&softc->ctl_lock);
9980 
9981 	data_len = sizeof(struct scsi_vpd_scsi_ports) + num_target_port_groups *
9982 	    num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
9983 	     sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
9984 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9985 	sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
9986 	ctsio->kern_sg_entries = 0;
9987 
9988 	if (data_len < alloc_len) {
9989 		ctsio->residual = alloc_len - data_len;
9990 		ctsio->kern_data_len = data_len;
9991 		ctsio->kern_total_len = data_len;
9992 	} else {
9993 		ctsio->residual = 0;
9994 		ctsio->kern_data_len = alloc_len;
9995 		ctsio->kern_total_len = alloc_len;
9996 	}
9997 	ctsio->kern_data_resid = 0;
9998 	ctsio->kern_rel_offset = 0;
9999 	ctsio->kern_sg_entries = 0;
10000 
10001 	/*
10002 	 * The control device is always connected.  The disk device, on the
10003 	 * other hand, may not be online all the time.  Need to change this
10004 	 * to figure out whether the disk device is actually online or not.
10005 	 */
10006 	if (lun != NULL)
10007 		sp->device = (SID_QUAL_LU_CONNECTED << 5) |
10008 				  lun->be_lun->lun_type;
10009 	else
10010 		sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10011 
10012 	sp->page_code = SVPD_SCSI_PORTS;
10013 	scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
10014 	    sp->page_length);
10015 	pd = &sp->design[0];
10016 
10017 	mtx_lock(&softc->ctl_lock);
10018 	pg = softc->port_offset / CTL_MAX_PORTS;
10019 	for (g = 0; g < num_target_port_groups; g++) {
10020 		STAILQ_FOREACH(port, &softc->port_list, links) {
10021 			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
10022 				continue;
10023 			if (lun != NULL &&
10024 			    ctl_map_lun_back(softc, port->targ_port, lun->lun)
10025 			    >= CTL_MAX_LUNS)
10026 				continue;
10027 			p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
10028 			scsi_ulto2b(p, pd->relative_port_id);
10029 			if (port->init_devid && g == pg) {
10030 				iid_len = port->init_devid->len;
10031 				memcpy(pd->initiator_transportid,
10032 				    port->init_devid->data, port->init_devid->len);
10033 			} else
10034 				iid_len = 0;
10035 			scsi_ulto2b(iid_len, pd->initiator_transportid_length);
10036 			pdc = (struct scsi_vpd_port_designation_cont *)
10037 			    (&pd->initiator_transportid[iid_len]);
10038 			if (port->port_devid && g == pg) {
10039 				id_len = port->port_devid->len;
10040 				memcpy(pdc->target_port_descriptors,
10041 				    port->port_devid->data, port->port_devid->len);
10042 			} else
10043 				id_len = 0;
10044 			scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
10045 			pd = (struct scsi_vpd_port_designation *)
10046 			    ((uint8_t *)pdc->target_port_descriptors + id_len);
10047 		}
10048 	}
10049 	mtx_unlock(&softc->ctl_lock);
10050 
10051 	ctl_set_success(ctsio);
10052 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10053 	ctsio->be_move_done = ctl_config_move_done;
10054 	ctl_datamove((union ctl_io *)ctsio);
10055 	return (CTL_RETVAL_COMPLETE);
10056 }
10057 
10058 static int
10059 ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
10060 {
10061 	struct scsi_vpd_block_limits *bl_ptr;
10062 	struct ctl_lun *lun;
10063 	int bs;
10064 
10065 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10066 
10067 	ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
10068 	bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
10069 	ctsio->kern_sg_entries = 0;
10070 
10071 	if (sizeof(*bl_ptr) < alloc_len) {
10072 		ctsio->residual = alloc_len - sizeof(*bl_ptr);
10073 		ctsio->kern_data_len = sizeof(*bl_ptr);
10074 		ctsio->kern_total_len = sizeof(*bl_ptr);
10075 	} else {
10076 		ctsio->residual = 0;
10077 		ctsio->kern_data_len = alloc_len;
10078 		ctsio->kern_total_len = alloc_len;
10079 	}
10080 	ctsio->kern_data_resid = 0;
10081 	ctsio->kern_rel_offset = 0;
10082 	ctsio->kern_sg_entries = 0;
10083 
10084 	/*
10085 	 * The control device is always connected.  The disk device, on the
10086 	 * other hand, may not be online all the time.  Need to change this
10087 	 * to figure out whether the disk device is actually online or not.
10088 	 */
10089 	if (lun != NULL)
10090 		bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10091 				  lun->be_lun->lun_type;
10092 	else
10093 		bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10094 
10095 	bl_ptr->page_code = SVPD_BLOCK_LIMITS;
10096 	scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
10097 	bl_ptr->max_cmp_write_len = 0xff;
10098 	scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
10099 	if (lun != NULL) {
10100 		bs = lun->be_lun->blocksize;
10101 		scsi_ulto4b(lun->be_lun->opttxferlen, bl_ptr->opt_txfer_len);
10102 		if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10103 			scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_lba_cnt);
10104 			scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_blk_cnt);
10105 			if (lun->be_lun->ublockexp != 0) {
10106 				scsi_ulto4b((1 << lun->be_lun->ublockexp),
10107 				    bl_ptr->opt_unmap_grain);
10108 				scsi_ulto4b(0x80000000 | lun->be_lun->ublockoff,
10109 				    bl_ptr->unmap_grain_align);
10110 			}
10111 		}
10112 		scsi_ulto4b(lun->be_lun->atomicblock,
10113 		    bl_ptr->max_atomic_transfer_length);
10114 		scsi_ulto4b(0, bl_ptr->atomic_alignment);
10115 		scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
10116 	}
10117 	scsi_u64to8b(UINT64_MAX, bl_ptr->max_write_same_length);
10118 
10119 	ctl_set_success(ctsio);
10120 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10121 	ctsio->be_move_done = ctl_config_move_done;
10122 	ctl_datamove((union ctl_io *)ctsio);
10123 	return (CTL_RETVAL_COMPLETE);
10124 }
10125 
10126 static int
10127 ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
10128 {
10129 	struct scsi_vpd_block_device_characteristics *bdc_ptr;
10130 	struct ctl_lun *lun;
10131 	const char *value;
10132 	u_int i;
10133 
10134 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10135 
10136 	ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
10137 	bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
10138 	ctsio->kern_sg_entries = 0;
10139 
10140 	if (sizeof(*bdc_ptr) < alloc_len) {
10141 		ctsio->residual = alloc_len - sizeof(*bdc_ptr);
10142 		ctsio->kern_data_len = sizeof(*bdc_ptr);
10143 		ctsio->kern_total_len = sizeof(*bdc_ptr);
10144 	} else {
10145 		ctsio->residual = 0;
10146 		ctsio->kern_data_len = alloc_len;
10147 		ctsio->kern_total_len = alloc_len;
10148 	}
10149 	ctsio->kern_data_resid = 0;
10150 	ctsio->kern_rel_offset = 0;
10151 	ctsio->kern_sg_entries = 0;
10152 
10153 	/*
10154 	 * The control device is always connected.  The disk device, on the
10155 	 * other hand, may not be online all the time.  Need to change this
10156 	 * to figure out whether the disk device is actually online or not.
10157 	 */
10158 	if (lun != NULL)
10159 		bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10160 				  lun->be_lun->lun_type;
10161 	else
10162 		bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10163 	bdc_ptr->page_code = SVPD_BDC;
10164 	scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
10165 	if (lun != NULL &&
10166 	    (value = ctl_get_opt(&lun->be_lun->options, "rpm")) != NULL)
10167 		i = strtol(value, NULL, 0);
10168 	else
10169 		i = CTL_DEFAULT_ROTATION_RATE;
10170 	scsi_ulto2b(i, bdc_ptr->medium_rotation_rate);
10171 	if (lun != NULL &&
10172 	    (value = ctl_get_opt(&lun->be_lun->options, "formfactor")) != NULL)
10173 		i = strtol(value, NULL, 0);
10174 	else
10175 		i = 0;
10176 	bdc_ptr->wab_wac_ff = (i & 0x0f);
10177 	bdc_ptr->flags = SVPD_FUAB | SVPD_VBULS;
10178 
10179 	ctl_set_success(ctsio);
10180 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10181 	ctsio->be_move_done = ctl_config_move_done;
10182 	ctl_datamove((union ctl_io *)ctsio);
10183 	return (CTL_RETVAL_COMPLETE);
10184 }
10185 
10186 static int
10187 ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
10188 {
10189 	struct scsi_vpd_logical_block_prov *lbp_ptr;
10190 	struct ctl_lun *lun;
10191 
10192 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10193 
10194 	ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
10195 	lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
10196 	ctsio->kern_sg_entries = 0;
10197 
10198 	if (sizeof(*lbp_ptr) < alloc_len) {
10199 		ctsio->residual = alloc_len - sizeof(*lbp_ptr);
10200 		ctsio->kern_data_len = sizeof(*lbp_ptr);
10201 		ctsio->kern_total_len = sizeof(*lbp_ptr);
10202 	} else {
10203 		ctsio->residual = 0;
10204 		ctsio->kern_data_len = alloc_len;
10205 		ctsio->kern_total_len = alloc_len;
10206 	}
10207 	ctsio->kern_data_resid = 0;
10208 	ctsio->kern_rel_offset = 0;
10209 	ctsio->kern_sg_entries = 0;
10210 
10211 	/*
10212 	 * The control device is always connected.  The disk device, on the
10213 	 * other hand, may not be online all the time.  Need to change this
10214 	 * to figure out whether the disk device is actually online or not.
10215 	 */
10216 	if (lun != NULL)
10217 		lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10218 				  lun->be_lun->lun_type;
10219 	else
10220 		lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10221 
10222 	lbp_ptr->page_code = SVPD_LBP;
10223 	scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
10224 	lbp_ptr->threshold_exponent = CTL_LBP_EXPONENT;
10225 	if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10226 		lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
10227 		    SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
10228 		lbp_ptr->prov_type = SVPD_LBP_THIN;
10229 	}
10230 
10231 	ctl_set_success(ctsio);
10232 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10233 	ctsio->be_move_done = ctl_config_move_done;
10234 	ctl_datamove((union ctl_io *)ctsio);
10235 	return (CTL_RETVAL_COMPLETE);
10236 }
10237 
10238 static int
10239 ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
10240 {
10241 	struct ctl_lun *lun;
10242 	struct scsi_inquiry *cdb;
10243 	int alloc_len, retval;
10244 
10245 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10246 	cdb = (struct scsi_inquiry *)ctsio->cdb;
10247 	alloc_len = scsi_2btoul(cdb->length);
10248 
10249 	switch (cdb->page_code) {
10250 	case SVPD_SUPPORTED_PAGES:
10251 		retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
10252 		break;
10253 	case SVPD_UNIT_SERIAL_NUMBER:
10254 		retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
10255 		break;
10256 	case SVPD_DEVICE_ID:
10257 		retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
10258 		break;
10259 	case SVPD_EXTENDED_INQUIRY_DATA:
10260 		retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
10261 		break;
10262 	case SVPD_MODE_PAGE_POLICY:
10263 		retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
10264 		break;
10265 	case SVPD_SCSI_PORTS:
10266 		retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10267 		break;
10268 	case SVPD_SCSI_TPC:
10269 		retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
10270 		break;
10271 	case SVPD_BLOCK_LIMITS:
10272 		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10273 			goto err;
10274 		retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10275 		break;
10276 	case SVPD_BDC:
10277 		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10278 			goto err;
10279 		retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
10280 		break;
10281 	case SVPD_LBP:
10282 		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10283 			goto err;
10284 		retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10285 		break;
10286 	default:
10287 err:
10288 		ctl_set_invalid_field(ctsio,
10289 				      /*sks_valid*/ 1,
10290 				      /*command*/ 1,
10291 				      /*field*/ 2,
10292 				      /*bit_valid*/ 0,
10293 				      /*bit*/ 0);
10294 		ctl_done((union ctl_io *)ctsio);
10295 		retval = CTL_RETVAL_COMPLETE;
10296 		break;
10297 	}
10298 
10299 	return (retval);
10300 }
10301 
10302 static int
10303 ctl_inquiry_std(struct ctl_scsiio *ctsio)
10304 {
10305 	struct scsi_inquiry_data *inq_ptr;
10306 	struct scsi_inquiry *cdb;
10307 	struct ctl_softc *softc;
10308 	struct ctl_lun *lun;
10309 	char *val;
10310 	uint32_t alloc_len, data_len;
10311 	ctl_port_type port_type;
10312 
10313 	softc = control_softc;
10314 
10315 	/*
10316 	 * Figure out whether we're talking to a Fibre Channel port or not.
10317 	 * We treat the ioctl front end, and any SCSI adapters, as packetized
10318 	 * SCSI front ends.
10319 	 */
10320 	port_type = softc->ctl_ports[
10321 	    ctl_port_idx(ctsio->io_hdr.nexus.targ_port)]->port_type;
10322 	if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10323 		port_type = CTL_PORT_SCSI;
10324 
10325 	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10326 	cdb = (struct scsi_inquiry *)ctsio->cdb;
10327 	alloc_len = scsi_2btoul(cdb->length);
10328 
10329 	/*
10330 	 * We malloc the full inquiry data size here and fill it
10331 	 * in.  If the user only asks for less, we'll give him
10332 	 * that much.
10333 	 */
10334 	data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
10335 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10336 	inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10337 	ctsio->kern_sg_entries = 0;
10338 	ctsio->kern_data_resid = 0;
10339 	ctsio->kern_rel_offset = 0;
10340 
10341 	if (data_len < alloc_len) {
10342 		ctsio->residual = alloc_len - data_len;
10343 		ctsio->kern_data_len = data_len;
10344 		ctsio->kern_total_len = data_len;
10345 	} else {
10346 		ctsio->residual = 0;
10347 		ctsio->kern_data_len = alloc_len;
10348 		ctsio->kern_total_len = alloc_len;
10349 	}
10350 
10351 	/*
10352 	 * If we have a LUN configured, report it as connected.  Otherwise,
10353 	 * report that it is offline or no device is supported, depending
10354 	 * on the value of inquiry_pq_no_lun.
10355 	 *
10356 	 * According to the spec (SPC-4 r34), the peripheral qualifier
10357 	 * SID_QUAL_LU_OFFLINE (001b) is used in the following scenario:
10358 	 *
10359 	 * "A peripheral device having the specified peripheral device type
10360 	 * is not connected to this logical unit. However, the device
10361 	 * server is capable of supporting the specified peripheral device
10362 	 * type on this logical unit."
10363 	 *
10364 	 * According to the same spec, the peripheral qualifier
10365 	 * SID_QUAL_BAD_LU (011b) is used in this scenario:
10366 	 *
10367 	 * "The device server is not capable of supporting a peripheral
10368 	 * device on this logical unit. For this peripheral qualifier the
10369 	 * peripheral device type shall be set to 1Fh. All other peripheral
10370 	 * device type values are reserved for this peripheral qualifier."
10371 	 *
10372 	 * Given the text, it would seem that we probably want to report that
10373 	 * the LUN is offline here.  There is no LUN connected, but we can
10374 	 * support a LUN at the given LUN number.
10375 	 *
10376 	 * In the real world, though, it sounds like things are a little
10377 	 * different:
10378 	 *
10379 	 * - Linux, when presented with a LUN with the offline peripheral
10380 	 *   qualifier, will create an sg driver instance for it.  So when
10381 	 *   you attach it to CTL, you wind up with a ton of sg driver
10382 	 *   instances.  (One for every LUN that Linux bothered to probe.)
10383 	 *   Linux does this despite the fact that it issues a REPORT LUNs
10384 	 *   to LUN 0 to get the inventory of supported LUNs.
10385 	 *
10386 	 * - There is other anecdotal evidence (from Emulex folks) about
10387 	 *   arrays that use the offline peripheral qualifier for LUNs that
10388 	 *   are on the "passive" path in an active/passive array.
10389 	 *
10390 	 * So the solution is provide a hopefully reasonable default
10391 	 * (return bad/no LUN) and allow the user to change the behavior
10392 	 * with a tunable/sysctl variable.
10393 	 */
10394 	if (lun != NULL)
10395 		inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10396 				  lun->be_lun->lun_type;
10397 	else if (softc->inquiry_pq_no_lun == 0)
10398 		inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10399 	else
10400 		inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10401 
10402 	/* RMB in byte 2 is 0 */
10403 	inq_ptr->version = SCSI_REV_SPC4;
10404 
10405 	/*
10406 	 * According to SAM-3, even if a device only supports a single
10407 	 * level of LUN addressing, it should still set the HISUP bit:
10408 	 *
10409 	 * 4.9.1 Logical unit numbers overview
10410 	 *
10411 	 * All logical unit number formats described in this standard are
10412 	 * hierarchical in structure even when only a single level in that
10413 	 * hierarchy is used. The HISUP bit shall be set to one in the
10414 	 * standard INQUIRY data (see SPC-2) when any logical unit number
10415 	 * format described in this standard is used.  Non-hierarchical
10416 	 * formats are outside the scope of this standard.
10417 	 *
10418 	 * Therefore we set the HiSup bit here.
10419 	 *
10420 	 * The reponse format is 2, per SPC-3.
10421 	 */
10422 	inq_ptr->response_format = SID_HiSup | 2;
10423 
10424 	inq_ptr->additional_length = data_len -
10425 	    (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10426 	CTL_DEBUG_PRINT(("additional_length = %d\n",
10427 			 inq_ptr->additional_length));
10428 
10429 	inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10430 	/* 16 bit addressing */
10431 	if (port_type == CTL_PORT_SCSI)
10432 		inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10433 	/* XXX set the SID_MultiP bit here if we're actually going to
10434 	   respond on multiple ports */
10435 	inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10436 
10437 	/* 16 bit data bus, synchronous transfers */
10438 	if (port_type == CTL_PORT_SCSI)
10439 		inq_ptr->flags = SID_WBus16 | SID_Sync;
10440 	/*
10441 	 * XXX KDM do we want to support tagged queueing on the control
10442 	 * device at all?
10443 	 */
10444 	if ((lun == NULL)
10445 	 || (lun->be_lun->lun_type != T_PROCESSOR))
10446 		inq_ptr->flags |= SID_CmdQue;
10447 	/*
10448 	 * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10449 	 * We have 8 bytes for the vendor name, and 16 bytes for the device
10450 	 * name and 4 bytes for the revision.
10451 	 */
10452 	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10453 	    "vendor")) == NULL) {
10454 		strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10455 	} else {
10456 		memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10457 		strncpy(inq_ptr->vendor, val,
10458 		    min(sizeof(inq_ptr->vendor), strlen(val)));
10459 	}
10460 	if (lun == NULL) {
10461 		strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10462 		    sizeof(inq_ptr->product));
10463 	} else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10464 		switch (lun->be_lun->lun_type) {
10465 		case T_DIRECT:
10466 			strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10467 			    sizeof(inq_ptr->product));
10468 			break;
10469 		case T_PROCESSOR:
10470 			strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10471 			    sizeof(inq_ptr->product));
10472 			break;
10473 		default:
10474 			strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10475 			    sizeof(inq_ptr->product));
10476 			break;
10477 		}
10478 	} else {
10479 		memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10480 		strncpy(inq_ptr->product, val,
10481 		    min(sizeof(inq_ptr->product), strlen(val)));
10482 	}
10483 
10484 	/*
10485 	 * XXX make this a macro somewhere so it automatically gets
10486 	 * incremented when we make changes.
10487 	 */
10488 	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10489 	    "revision")) == NULL) {
10490 		strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10491 	} else {
10492 		memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10493 		strncpy(inq_ptr->revision, val,
10494 		    min(sizeof(inq_ptr->revision), strlen(val)));
10495 	}
10496 
10497 	/*
10498 	 * For parallel SCSI, we support double transition and single
10499 	 * transition clocking.  We also support QAS (Quick Arbitration
10500 	 * and Selection) and Information Unit transfers on both the
10501 	 * control and array devices.
10502 	 */
10503 	if (port_type == CTL_PORT_SCSI)
10504 		inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10505 				    SID_SPI_IUS;
10506 
10507 	/* SAM-5 (no version claimed) */
10508 	scsi_ulto2b(0x00A0, inq_ptr->version1);
10509 	/* SPC-4 (no version claimed) */
10510 	scsi_ulto2b(0x0460, inq_ptr->version2);
10511 	if (port_type == CTL_PORT_FC) {
10512 		/* FCP-2 ANSI INCITS.350:2003 */
10513 		scsi_ulto2b(0x0917, inq_ptr->version3);
10514 	} else if (port_type == CTL_PORT_SCSI) {
10515 		/* SPI-4 ANSI INCITS.362:200x */
10516 		scsi_ulto2b(0x0B56, inq_ptr->version3);
10517 	} else if (port_type == CTL_PORT_ISCSI) {
10518 		/* iSCSI (no version claimed) */
10519 		scsi_ulto2b(0x0960, inq_ptr->version3);
10520 	} else if (port_type == CTL_PORT_SAS) {
10521 		/* SAS (no version claimed) */
10522 		scsi_ulto2b(0x0BE0, inq_ptr->version3);
10523 	}
10524 
10525 	if (lun == NULL) {
10526 		/* SBC-4 (no version claimed) */
10527 		scsi_ulto2b(0x0600, inq_ptr->version4);
10528 	} else {
10529 		switch (lun->be_lun->lun_type) {
10530 		case T_DIRECT:
10531 			/* SBC-4 (no version claimed) */
10532 			scsi_ulto2b(0x0600, inq_ptr->version4);
10533 			break;
10534 		case T_PROCESSOR:
10535 		default:
10536 			break;
10537 		}
10538 	}
10539 
10540 	ctl_set_success(ctsio);
10541 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10542 	ctsio->be_move_done = ctl_config_move_done;
10543 	ctl_datamove((union ctl_io *)ctsio);
10544 	return (CTL_RETVAL_COMPLETE);
10545 }
10546 
10547 int
10548 ctl_inquiry(struct ctl_scsiio *ctsio)
10549 {
10550 	struct scsi_inquiry *cdb;
10551 	int retval;
10552 
10553 	CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10554 
10555 	cdb = (struct scsi_inquiry *)ctsio->cdb;
10556 	if (cdb->byte2 & SI_EVPD)
10557 		retval = ctl_inquiry_evpd(ctsio);
10558 	else if (cdb->page_code == 0)
10559 		retval = ctl_inquiry_std(ctsio);
10560 	else {
10561 		ctl_set_invalid_field(ctsio,
10562 				      /*sks_valid*/ 1,
10563 				      /*command*/ 1,
10564 				      /*field*/ 2,
10565 				      /*bit_valid*/ 0,
10566 				      /*bit*/ 0);
10567 		ctl_done((union ctl_io *)ctsio);
10568 		return (CTL_RETVAL_COMPLETE);
10569 	}
10570 
10571 	return (retval);
10572 }
10573 
10574 /*
10575  * For known CDB types, parse the LBA and length.
10576  */
10577 static int
10578 ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10579 {
10580 	if (io->io_hdr.io_type != CTL_IO_SCSI)
10581 		return (1);
10582 
10583 	switch (io->scsiio.cdb[0]) {
10584 	case COMPARE_AND_WRITE: {
10585 		struct scsi_compare_and_write *cdb;
10586 
10587 		cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10588 
10589 		*lba = scsi_8btou64(cdb->addr);
10590 		*len = cdb->length;
10591 		break;
10592 	}
10593 	case READ_6:
10594 	case WRITE_6: {
10595 		struct scsi_rw_6 *cdb;
10596 
10597 		cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10598 
10599 		*lba = scsi_3btoul(cdb->addr);
10600 		/* only 5 bits are valid in the most significant address byte */
10601 		*lba &= 0x1fffff;
10602 		*len = cdb->length;
10603 		break;
10604 	}
10605 	case READ_10:
10606 	case WRITE_10: {
10607 		struct scsi_rw_10 *cdb;
10608 
10609 		cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10610 
10611 		*lba = scsi_4btoul(cdb->addr);
10612 		*len = scsi_2btoul(cdb->length);
10613 		break;
10614 	}
10615 	case WRITE_VERIFY_10: {
10616 		struct scsi_write_verify_10 *cdb;
10617 
10618 		cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10619 
10620 		*lba = scsi_4btoul(cdb->addr);
10621 		*len = scsi_2btoul(cdb->length);
10622 		break;
10623 	}
10624 	case READ_12:
10625 	case WRITE_12: {
10626 		struct scsi_rw_12 *cdb;
10627 
10628 		cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10629 
10630 		*lba = scsi_4btoul(cdb->addr);
10631 		*len = scsi_4btoul(cdb->length);
10632 		break;
10633 	}
10634 	case WRITE_VERIFY_12: {
10635 		struct scsi_write_verify_12 *cdb;
10636 
10637 		cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10638 
10639 		*lba = scsi_4btoul(cdb->addr);
10640 		*len = scsi_4btoul(cdb->length);
10641 		break;
10642 	}
10643 	case READ_16:
10644 	case WRITE_16:
10645 	case WRITE_ATOMIC_16: {
10646 		struct scsi_rw_16 *cdb;
10647 
10648 		cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10649 
10650 		*lba = scsi_8btou64(cdb->addr);
10651 		*len = scsi_4btoul(cdb->length);
10652 		break;
10653 	}
10654 	case WRITE_VERIFY_16: {
10655 		struct scsi_write_verify_16 *cdb;
10656 
10657 		cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10658 
10659 		*lba = scsi_8btou64(cdb->addr);
10660 		*len = scsi_4btoul(cdb->length);
10661 		break;
10662 	}
10663 	case WRITE_SAME_10: {
10664 		struct scsi_write_same_10 *cdb;
10665 
10666 		cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10667 
10668 		*lba = scsi_4btoul(cdb->addr);
10669 		*len = scsi_2btoul(cdb->length);
10670 		break;
10671 	}
10672 	case WRITE_SAME_16: {
10673 		struct scsi_write_same_16 *cdb;
10674 
10675 		cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10676 
10677 		*lba = scsi_8btou64(cdb->addr);
10678 		*len = scsi_4btoul(cdb->length);
10679 		break;
10680 	}
10681 	case VERIFY_10: {
10682 		struct scsi_verify_10 *cdb;
10683 
10684 		cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10685 
10686 		*lba = scsi_4btoul(cdb->addr);
10687 		*len = scsi_2btoul(cdb->length);
10688 		break;
10689 	}
10690 	case VERIFY_12: {
10691 		struct scsi_verify_12 *cdb;
10692 
10693 		cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10694 
10695 		*lba = scsi_4btoul(cdb->addr);
10696 		*len = scsi_4btoul(cdb->length);
10697 		break;
10698 	}
10699 	case VERIFY_16: {
10700 		struct scsi_verify_16 *cdb;
10701 
10702 		cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10703 
10704 		*lba = scsi_8btou64(cdb->addr);
10705 		*len = scsi_4btoul(cdb->length);
10706 		break;
10707 	}
10708 	case UNMAP: {
10709 		*lba = 0;
10710 		*len = UINT64_MAX;
10711 		break;
10712 	}
10713 	case SERVICE_ACTION_IN: {	/* GET LBA STATUS */
10714 		struct scsi_get_lba_status *cdb;
10715 
10716 		cdb = (struct scsi_get_lba_status *)io->scsiio.cdb;
10717 		*lba = scsi_8btou64(cdb->addr);
10718 		*len = UINT32_MAX;
10719 		break;
10720 	}
10721 	default:
10722 		return (1);
10723 		break; /* NOTREACHED */
10724 	}
10725 
10726 	return (0);
10727 }
10728 
10729 static ctl_action
10730 ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2,
10731     bool seq)
10732 {
10733 	uint64_t endlba1, endlba2;
10734 
10735 	endlba1 = lba1 + len1 - (seq ? 0 : 1);
10736 	endlba2 = lba2 + len2 - 1;
10737 
10738 	if ((endlba1 < lba2) || (endlba2 < lba1))
10739 		return (CTL_ACTION_PASS);
10740 	else
10741 		return (CTL_ACTION_BLOCK);
10742 }
10743 
10744 static int
10745 ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
10746 {
10747 	struct ctl_ptr_len_flags *ptrlen;
10748 	struct scsi_unmap_desc *buf, *end, *range;
10749 	uint64_t lba;
10750 	uint32_t len;
10751 
10752 	/* If not UNMAP -- go other way. */
10753 	if (io->io_hdr.io_type != CTL_IO_SCSI ||
10754 	    io->scsiio.cdb[0] != UNMAP)
10755 		return (CTL_ACTION_ERROR);
10756 
10757 	/* If UNMAP without data -- block and wait for data. */
10758 	ptrlen = (struct ctl_ptr_len_flags *)
10759 	    &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10760 	if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
10761 	    ptrlen->ptr == NULL)
10762 		return (CTL_ACTION_BLOCK);
10763 
10764 	/* UNMAP with data -- check for collision. */
10765 	buf = (struct scsi_unmap_desc *)ptrlen->ptr;
10766 	end = buf + ptrlen->len / sizeof(*buf);
10767 	for (range = buf; range < end; range++) {
10768 		lba = scsi_8btou64(range->lba);
10769 		len = scsi_4btoul(range->length);
10770 		if ((lba < lba2 + len2) && (lba + len > lba2))
10771 			return (CTL_ACTION_BLOCK);
10772 	}
10773 	return (CTL_ACTION_PASS);
10774 }
10775 
10776 static ctl_action
10777 ctl_extent_check(union ctl_io *io1, union ctl_io *io2, bool seq)
10778 {
10779 	uint64_t lba1, lba2;
10780 	uint64_t len1, len2;
10781 	int retval;
10782 
10783 	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10784 		return (CTL_ACTION_ERROR);
10785 
10786 	retval = ctl_extent_check_unmap(io1, lba2, len2);
10787 	if (retval != CTL_ACTION_ERROR)
10788 		return (retval);
10789 
10790 	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10791 		return (CTL_ACTION_ERROR);
10792 
10793 	return (ctl_extent_check_lba(lba1, len1, lba2, len2, seq));
10794 }
10795 
10796 static ctl_action
10797 ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2)
10798 {
10799 	uint64_t lba1, lba2;
10800 	uint64_t len1, len2;
10801 
10802 	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10803 		return (CTL_ACTION_ERROR);
10804 	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10805 		return (CTL_ACTION_ERROR);
10806 
10807 	if (lba1 + len1 == lba2)
10808 		return (CTL_ACTION_BLOCK);
10809 	return (CTL_ACTION_PASS);
10810 }
10811 
10812 static ctl_action
10813 ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
10814     union ctl_io *ooa_io)
10815 {
10816 	const struct ctl_cmd_entry *pending_entry, *ooa_entry;
10817 	ctl_serialize_action *serialize_row;
10818 
10819 	/*
10820 	 * The initiator attempted multiple untagged commands at the same
10821 	 * time.  Can't do that.
10822 	 */
10823 	if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10824 	 && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10825 	 && ((pending_io->io_hdr.nexus.targ_port ==
10826 	      ooa_io->io_hdr.nexus.targ_port)
10827 	  && (pending_io->io_hdr.nexus.initid.id ==
10828 	      ooa_io->io_hdr.nexus.initid.id))
10829 	 && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
10830 		return (CTL_ACTION_OVERLAP);
10831 
10832 	/*
10833 	 * The initiator attempted to send multiple tagged commands with
10834 	 * the same ID.  (It's fine if different initiators have the same
10835 	 * tag ID.)
10836 	 *
10837 	 * Even if all of those conditions are true, we don't kill the I/O
10838 	 * if the command ahead of us has been aborted.  We won't end up
10839 	 * sending it to the FETD, and it's perfectly legal to resend a
10840 	 * command with the same tag number as long as the previous
10841 	 * instance of this tag number has been aborted somehow.
10842 	 */
10843 	if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10844 	 && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10845 	 && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
10846 	 && ((pending_io->io_hdr.nexus.targ_port ==
10847 	      ooa_io->io_hdr.nexus.targ_port)
10848 	  && (pending_io->io_hdr.nexus.initid.id ==
10849 	      ooa_io->io_hdr.nexus.initid.id))
10850 	 && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
10851 		return (CTL_ACTION_OVERLAP_TAG);
10852 
10853 	/*
10854 	 * If we get a head of queue tag, SAM-3 says that we should
10855 	 * immediately execute it.
10856 	 *
10857 	 * What happens if this command would normally block for some other
10858 	 * reason?  e.g. a request sense with a head of queue tag
10859 	 * immediately after a write.  Normally that would block, but this
10860 	 * will result in its getting executed immediately...
10861 	 *
10862 	 * We currently return "pass" instead of "skip", so we'll end up
10863 	 * going through the rest of the queue to check for overlapped tags.
10864 	 *
10865 	 * XXX KDM check for other types of blockage first??
10866 	 */
10867 	if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10868 		return (CTL_ACTION_PASS);
10869 
10870 	/*
10871 	 * Ordered tags have to block until all items ahead of them
10872 	 * have completed.  If we get called with an ordered tag, we always
10873 	 * block, if something else is ahead of us in the queue.
10874 	 */
10875 	if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
10876 		return (CTL_ACTION_BLOCK);
10877 
10878 	/*
10879 	 * Simple tags get blocked until all head of queue and ordered tags
10880 	 * ahead of them have completed.  I'm lumping untagged commands in
10881 	 * with simple tags here.  XXX KDM is that the right thing to do?
10882 	 */
10883 	if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10884 	  || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
10885 	 && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10886 	  || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
10887 		return (CTL_ACTION_BLOCK);
10888 
10889 	pending_entry = ctl_get_cmd_entry(&pending_io->scsiio, NULL);
10890 	ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio, NULL);
10891 
10892 	serialize_row = ctl_serialize_table[ooa_entry->seridx];
10893 
10894 	switch (serialize_row[pending_entry->seridx]) {
10895 	case CTL_SER_BLOCK:
10896 		return (CTL_ACTION_BLOCK);
10897 	case CTL_SER_EXTENT:
10898 		return (ctl_extent_check(ooa_io, pending_io,
10899 		    (lun->serseq == CTL_LUN_SERSEQ_ON)));
10900 	case CTL_SER_EXTENTOPT:
10901 		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
10902 		    & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
10903 			return (ctl_extent_check(ooa_io, pending_io,
10904 			    (lun->serseq == CTL_LUN_SERSEQ_ON)));
10905 		return (CTL_ACTION_PASS);
10906 	case CTL_SER_EXTENTSEQ:
10907 		if (lun->serseq != CTL_LUN_SERSEQ_OFF)
10908 			return (ctl_extent_check_seq(ooa_io, pending_io));
10909 		return (CTL_ACTION_PASS);
10910 	case CTL_SER_PASS:
10911 		return (CTL_ACTION_PASS);
10912 	case CTL_SER_BLOCKOPT:
10913 		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
10914 		    & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
10915 			return (CTL_ACTION_BLOCK);
10916 		return (CTL_ACTION_PASS);
10917 	case CTL_SER_SKIP:
10918 		return (CTL_ACTION_SKIP);
10919 	default:
10920 		panic("invalid serialization value %d",
10921 		      serialize_row[pending_entry->seridx]);
10922 	}
10923 
10924 	return (CTL_ACTION_ERROR);
10925 }
10926 
10927 /*
10928  * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
10929  * Assumptions:
10930  * - pending_io is generally either incoming, or on the blocked queue
10931  * - starting I/O is the I/O we want to start the check with.
10932  */
10933 static ctl_action
10934 ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
10935 	      union ctl_io *starting_io)
10936 {
10937 	union ctl_io *ooa_io;
10938 	ctl_action action;
10939 
10940 	mtx_assert(&lun->lun_lock, MA_OWNED);
10941 
10942 	/*
10943 	 * Run back along the OOA queue, starting with the current
10944 	 * blocked I/O and going through every I/O before it on the
10945 	 * queue.  If starting_io is NULL, we'll just end up returning
10946 	 * CTL_ACTION_PASS.
10947 	 */
10948 	for (ooa_io = starting_io; ooa_io != NULL;
10949 	     ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
10950 	     ooa_links)){
10951 
10952 		/*
10953 		 * This routine just checks to see whether
10954 		 * cur_blocked is blocked by ooa_io, which is ahead
10955 		 * of it in the queue.  It doesn't queue/dequeue
10956 		 * cur_blocked.
10957 		 */
10958 		action = ctl_check_for_blockage(lun, pending_io, ooa_io);
10959 		switch (action) {
10960 		case CTL_ACTION_BLOCK:
10961 		case CTL_ACTION_OVERLAP:
10962 		case CTL_ACTION_OVERLAP_TAG:
10963 		case CTL_ACTION_SKIP:
10964 		case CTL_ACTION_ERROR:
10965 			return (action);
10966 			break; /* NOTREACHED */
10967 		case CTL_ACTION_PASS:
10968 			break;
10969 		default:
10970 			panic("invalid action %d", action);
10971 			break;  /* NOTREACHED */
10972 		}
10973 	}
10974 
10975 	return (CTL_ACTION_PASS);
10976 }
10977 
10978 /*
10979  * Assumptions:
10980  * - An I/O has just completed, and has been removed from the per-LUN OOA
10981  *   queue, so some items on the blocked queue may now be unblocked.
10982  */
10983 static int
10984 ctl_check_blocked(struct ctl_lun *lun)
10985 {
10986 	union ctl_io *cur_blocked, *next_blocked;
10987 
10988 	mtx_assert(&lun->lun_lock, MA_OWNED);
10989 
10990 	/*
10991 	 * Run forward from the head of the blocked queue, checking each
10992 	 * entry against the I/Os prior to it on the OOA queue to see if
10993 	 * there is still any blockage.
10994 	 *
10995 	 * We cannot use the TAILQ_FOREACH() macro, because it can't deal
10996 	 * with our removing a variable on it while it is traversing the
10997 	 * list.
10998 	 */
10999 	for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
11000 	     cur_blocked != NULL; cur_blocked = next_blocked) {
11001 		union ctl_io *prev_ooa;
11002 		ctl_action action;
11003 
11004 		next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
11005 							  blocked_links);
11006 
11007 		prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
11008 						      ctl_ooaq, ooa_links);
11009 
11010 		/*
11011 		 * If cur_blocked happens to be the first item in the OOA
11012 		 * queue now, prev_ooa will be NULL, and the action
11013 		 * returned will just be CTL_ACTION_PASS.
11014 		 */
11015 		action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
11016 
11017 		switch (action) {
11018 		case CTL_ACTION_BLOCK:
11019 			/* Nothing to do here, still blocked */
11020 			break;
11021 		case CTL_ACTION_OVERLAP:
11022 		case CTL_ACTION_OVERLAP_TAG:
11023 			/*
11024 			 * This shouldn't happen!  In theory we've already
11025 			 * checked this command for overlap...
11026 			 */
11027 			break;
11028 		case CTL_ACTION_PASS:
11029 		case CTL_ACTION_SKIP: {
11030 			const struct ctl_cmd_entry *entry;
11031 			int isc_retval;
11032 
11033 			/*
11034 			 * The skip case shouldn't happen, this transaction
11035 			 * should have never made it onto the blocked queue.
11036 			 */
11037 			/*
11038 			 * This I/O is no longer blocked, we can remove it
11039 			 * from the blocked queue.  Since this is a TAILQ
11040 			 * (doubly linked list), we can do O(1) removals
11041 			 * from any place on the list.
11042 			 */
11043 			TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
11044 				     blocked_links);
11045 			cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11046 
11047 			if (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC){
11048 				/*
11049 				 * Need to send IO back to original side to
11050 				 * run
11051 				 */
11052 				union ctl_ha_msg msg_info;
11053 
11054 				msg_info.hdr.original_sc =
11055 					cur_blocked->io_hdr.original_sc;
11056 				msg_info.hdr.serializing_sc = cur_blocked;
11057 				msg_info.hdr.msg_type = CTL_MSG_R2R;
11058 				if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11059 				     &msg_info, sizeof(msg_info), 0)) >
11060 				     CTL_HA_STATUS_SUCCESS) {
11061 					printf("CTL:Check Blocked error from "
11062 					       "ctl_ha_msg_send %d\n",
11063 					       isc_retval);
11064 				}
11065 				break;
11066 			}
11067 			entry = ctl_get_cmd_entry(&cur_blocked->scsiio, NULL);
11068 
11069 			/*
11070 			 * Check this I/O for LUN state changes that may
11071 			 * have happened while this command was blocked.
11072 			 * The LUN state may have been changed by a command
11073 			 * ahead of us in the queue, so we need to re-check
11074 			 * for any states that can be caused by SCSI
11075 			 * commands.
11076 			 */
11077 			if (ctl_scsiio_lun_check(lun, entry,
11078 						 &cur_blocked->scsiio) == 0) {
11079 				cur_blocked->io_hdr.flags |=
11080 				                      CTL_FLAG_IS_WAS_ON_RTR;
11081 				ctl_enqueue_rtr(cur_blocked);
11082 			} else
11083 				ctl_done(cur_blocked);
11084 			break;
11085 		}
11086 		default:
11087 			/*
11088 			 * This probably shouldn't happen -- we shouldn't
11089 			 * get CTL_ACTION_ERROR, or anything else.
11090 			 */
11091 			break;
11092 		}
11093 	}
11094 
11095 	return (CTL_RETVAL_COMPLETE);
11096 }
11097 
11098 /*
11099  * This routine (with one exception) checks LUN flags that can be set by
11100  * commands ahead of us in the OOA queue.  These flags have to be checked
11101  * when a command initially comes in, and when we pull a command off the
11102  * blocked queue and are preparing to execute it.  The reason we have to
11103  * check these flags for commands on the blocked queue is that the LUN
11104  * state may have been changed by a command ahead of us while we're on the
11105  * blocked queue.
11106  *
11107  * Ordering is somewhat important with these checks, so please pay
11108  * careful attention to the placement of any new checks.
11109  */
11110 static int
11111 ctl_scsiio_lun_check(struct ctl_lun *lun,
11112     const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11113 {
11114 	struct ctl_softc *softc = lun->ctl_softc;
11115 	int retval;
11116 	uint32_t residx;
11117 
11118 	retval = 0;
11119 
11120 	mtx_assert(&lun->lun_lock, MA_OWNED);
11121 
11122 	/*
11123 	 * If this shelf is a secondary shelf controller, we have to reject
11124 	 * any media access commands.
11125 	 */
11126 	if ((softc->flags & CTL_FLAG_ACTIVE_SHELF) == 0 &&
11127 	    (entry->flags & CTL_CMD_FLAG_OK_ON_SECONDARY) == 0) {
11128 		ctl_set_lun_standby(ctsio);
11129 		retval = 1;
11130 		goto bailout;
11131 	}
11132 
11133 	if (entry->pattern & CTL_LUN_PAT_WRITE) {
11134 		if (lun->flags & CTL_LUN_READONLY) {
11135 			ctl_set_sense(ctsio, /*current_error*/ 1,
11136 			    /*sense_key*/ SSD_KEY_DATA_PROTECT,
11137 			    /*asc*/ 0x27, /*ascq*/ 0x01, SSD_ELEM_NONE);
11138 			retval = 1;
11139 			goto bailout;
11140 		}
11141 		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT]
11142 		    .eca_and_aen & SCP_SWP) != 0) {
11143 			ctl_set_sense(ctsio, /*current_error*/ 1,
11144 			    /*sense_key*/ SSD_KEY_DATA_PROTECT,
11145 			    /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
11146 			retval = 1;
11147 			goto bailout;
11148 		}
11149 	}
11150 
11151 	/*
11152 	 * Check for a reservation conflict.  If this command isn't allowed
11153 	 * even on reserved LUNs, and if this initiator isn't the one who
11154 	 * reserved us, reject the command with a reservation conflict.
11155 	 */
11156 	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
11157 	if ((lun->flags & CTL_LUN_RESERVED)
11158 	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11159 		if (lun->res_idx != residx) {
11160 			ctl_set_reservation_conflict(ctsio);
11161 			retval = 1;
11162 			goto bailout;
11163 		}
11164 	}
11165 
11166 	if ((lun->flags & CTL_LUN_PR_RESERVED) == 0 ||
11167 	    (entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV)) {
11168 		/* No reservation or command is allowed. */;
11169 	} else if ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_WRESV) &&
11170 	    (lun->res_type == SPR_TYPE_WR_EX ||
11171 	     lun->res_type == SPR_TYPE_WR_EX_RO ||
11172 	     lun->res_type == SPR_TYPE_WR_EX_AR)) {
11173 		/* The command is allowed for Write Exclusive resv. */;
11174 	} else {
11175 		/*
11176 		 * if we aren't registered or it's a res holder type
11177 		 * reservation and this isn't the res holder then set a
11178 		 * conflict.
11179 		 */
11180 		if (ctl_get_prkey(lun, residx) == 0
11181 		 || (residx != lun->pr_res_idx && lun->res_type < 4)) {
11182 			ctl_set_reservation_conflict(ctsio);
11183 			retval = 1;
11184 			goto bailout;
11185 		}
11186 
11187 	}
11188 
11189 	if ((lun->flags & CTL_LUN_OFFLINE)
11190 	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_OFFLINE) == 0)) {
11191 		ctl_set_lun_not_ready(ctsio);
11192 		retval = 1;
11193 		goto bailout;
11194 	}
11195 
11196 	/*
11197 	 * If the LUN is stopped, see if this particular command is allowed
11198 	 * for a stopped lun.  Otherwise, reject it with 0x04,0x02.
11199 	 */
11200 	if ((lun->flags & CTL_LUN_STOPPED)
11201 	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_STOPPED) == 0)) {
11202 		/* "Logical unit not ready, initializing cmd. required" */
11203 		ctl_set_lun_stopped(ctsio);
11204 		retval = 1;
11205 		goto bailout;
11206 	}
11207 
11208 	if ((lun->flags & CTL_LUN_INOPERABLE)
11209 	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_INOPERABLE) == 0)) {
11210 		/* "Medium format corrupted" */
11211 		ctl_set_medium_format_corrupted(ctsio);
11212 		retval = 1;
11213 		goto bailout;
11214 	}
11215 
11216 bailout:
11217 	return (retval);
11218 
11219 }
11220 
11221 static void
11222 ctl_failover_io(union ctl_io *io, int have_lock)
11223 {
11224 	ctl_set_busy(&io->scsiio);
11225 	ctl_done(io);
11226 }
11227 
11228 static void
11229 ctl_failover(void)
11230 {
11231 	struct ctl_lun *lun;
11232 	struct ctl_softc *softc;
11233 	union ctl_io *next_io, *pending_io;
11234 	union ctl_io *io;
11235 	int lun_idx;
11236 
11237 	softc = control_softc;
11238 
11239 	mtx_lock(&softc->ctl_lock);
11240 	/*
11241 	 * Remove any cmds from the other SC from the rtr queue.  These
11242 	 * will obviously only be for LUNs for which we're the primary.
11243 	 * We can't send status or get/send data for these commands.
11244 	 * Since they haven't been executed yet, we can just remove them.
11245 	 * We'll either abort them or delete them below, depending on
11246 	 * which HA mode we're in.
11247 	 */
11248 #ifdef notyet
11249 	mtx_lock(&softc->queue_lock);
11250 	for (io = (union ctl_io *)STAILQ_FIRST(&softc->rtr_queue);
11251 	     io != NULL; io = next_io) {
11252 		next_io = (union ctl_io *)STAILQ_NEXT(&io->io_hdr, links);
11253 		if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11254 			STAILQ_REMOVE(&softc->rtr_queue, &io->io_hdr,
11255 				      ctl_io_hdr, links);
11256 	}
11257 	mtx_unlock(&softc->queue_lock);
11258 #endif
11259 
11260 	for (lun_idx=0; lun_idx < softc->num_luns; lun_idx++) {
11261 		lun = softc->ctl_luns[lun_idx];
11262 		if (lun==NULL)
11263 			continue;
11264 
11265 		/*
11266 		 * Processor LUNs are primary on both sides.
11267 		 * XXX will this always be true?
11268 		 */
11269 		if (lun->be_lun->lun_type == T_PROCESSOR)
11270 			continue;
11271 
11272 		if ((lun->flags & CTL_LUN_PRIMARY_SC)
11273 		 && (softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11274 			printf("FAILOVER: primary lun %d\n", lun_idx);
11275 		        /*
11276 			 * Remove all commands from the other SC. First from the
11277 			 * blocked queue then from the ooa queue. Once we have
11278 			 * removed them. Call ctl_check_blocked to see if there
11279 			 * is anything that can run.
11280 			 */
11281 			for (io = (union ctl_io *)TAILQ_FIRST(
11282 			     &lun->blocked_queue); io != NULL; io = next_io) {
11283 
11284 		        	next_io = (union ctl_io *)TAILQ_NEXT(
11285 				    &io->io_hdr, blocked_links);
11286 
11287 				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11288 					TAILQ_REMOVE(&lun->blocked_queue,
11289 						     &io->io_hdr,blocked_links);
11290 					io->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11291 					TAILQ_REMOVE(&lun->ooa_queue,
11292 						     &io->io_hdr, ooa_links);
11293 
11294 					ctl_free_io(io);
11295 				}
11296 			}
11297 
11298 			for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11299 	     		     io != NULL; io = next_io) {
11300 
11301 		        	next_io = (union ctl_io *)TAILQ_NEXT(
11302 				    &io->io_hdr, ooa_links);
11303 
11304 				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11305 
11306 					TAILQ_REMOVE(&lun->ooa_queue,
11307 						&io->io_hdr,
11308 					     	ooa_links);
11309 
11310 					ctl_free_io(io);
11311 				}
11312 			}
11313 			ctl_check_blocked(lun);
11314 		} else if ((lun->flags & CTL_LUN_PRIMARY_SC)
11315 			&& (softc->ha_mode == CTL_HA_MODE_XFER)) {
11316 
11317 			printf("FAILOVER: primary lun %d\n", lun_idx);
11318 			/*
11319 			 * Abort all commands from the other SC.  We can't
11320 			 * send status back for them now.  These should get
11321 			 * cleaned up when they are completed or come out
11322 			 * for a datamove operation.
11323 			 */
11324 			for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11325 	     		     io != NULL; io = next_io) {
11326 		        	next_io = (union ctl_io *)TAILQ_NEXT(
11327 					&io->io_hdr, ooa_links);
11328 
11329 				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11330 					io->io_hdr.flags |= CTL_FLAG_ABORT;
11331 			}
11332 		} else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11333 			&& (softc->ha_mode == CTL_HA_MODE_XFER)) {
11334 
11335 			printf("FAILOVER: secondary lun %d\n", lun_idx);
11336 
11337 			lun->flags |= CTL_LUN_PRIMARY_SC;
11338 
11339 			/*
11340 			 * We send all I/O that was sent to this controller
11341 			 * and redirected to the other side back with
11342 			 * busy status, and have the initiator retry it.
11343 			 * Figuring out how much data has been transferred,
11344 			 * etc. and picking up where we left off would be
11345 			 * very tricky.
11346 			 *
11347 			 * XXX KDM need to remove I/O from the blocked
11348 			 * queue as well!
11349 			 */
11350 			for (pending_io = (union ctl_io *)TAILQ_FIRST(
11351 			     &lun->ooa_queue); pending_io != NULL;
11352 			     pending_io = next_io) {
11353 
11354 				next_io =  (union ctl_io *)TAILQ_NEXT(
11355 					&pending_io->io_hdr, ooa_links);
11356 
11357 				pending_io->io_hdr.flags &=
11358 					~CTL_FLAG_SENT_2OTHER_SC;
11359 
11360 				if (pending_io->io_hdr.flags &
11361 				    CTL_FLAG_IO_ACTIVE) {
11362 					pending_io->io_hdr.flags |=
11363 						CTL_FLAG_FAILOVER;
11364 				} else {
11365 					ctl_set_busy(&pending_io->scsiio);
11366 					ctl_done(pending_io);
11367 				}
11368 			}
11369 
11370 			ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
11371 		} else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11372 			&& (softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11373 			printf("FAILOVER: secondary lun %d\n", lun_idx);
11374 			/*
11375 			 * if the first io on the OOA is not on the RtR queue
11376 			 * add it.
11377 			 */
11378 			lun->flags |= CTL_LUN_PRIMARY_SC;
11379 
11380 			pending_io = (union ctl_io *)TAILQ_FIRST(
11381 			    &lun->ooa_queue);
11382 			if (pending_io==NULL) {
11383 				printf("Nothing on OOA queue\n");
11384 				continue;
11385 			}
11386 
11387 			pending_io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11388 			if ((pending_io->io_hdr.flags &
11389 			     CTL_FLAG_IS_WAS_ON_RTR) == 0) {
11390 				pending_io->io_hdr.flags |=
11391 				    CTL_FLAG_IS_WAS_ON_RTR;
11392 				ctl_enqueue_rtr(pending_io);
11393 			}
11394 #if 0
11395 			else
11396 			{
11397 				printf("Tag 0x%04x is running\n",
11398 				      pending_io->scsiio.tag_num);
11399 			}
11400 #endif
11401 
11402 			next_io = (union ctl_io *)TAILQ_NEXT(
11403 			    &pending_io->io_hdr, ooa_links);
11404 			for (pending_io=next_io; pending_io != NULL;
11405 			     pending_io = next_io) {
11406 				pending_io->io_hdr.flags &=
11407 				    ~CTL_FLAG_SENT_2OTHER_SC;
11408 				next_io = (union ctl_io *)TAILQ_NEXT(
11409 					&pending_io->io_hdr, ooa_links);
11410 				if (pending_io->io_hdr.flags &
11411 				    CTL_FLAG_IS_WAS_ON_RTR) {
11412 #if 0
11413 				        printf("Tag 0x%04x is running\n",
11414 				      		pending_io->scsiio.tag_num);
11415 #endif
11416 					continue;
11417 				}
11418 
11419 				switch (ctl_check_ooa(lun, pending_io,
11420 			            (union ctl_io *)TAILQ_PREV(
11421 				    &pending_io->io_hdr, ctl_ooaq,
11422 				    ooa_links))) {
11423 
11424 				case CTL_ACTION_BLOCK:
11425 					TAILQ_INSERT_TAIL(&lun->blocked_queue,
11426 							  &pending_io->io_hdr,
11427 							  blocked_links);
11428 					pending_io->io_hdr.flags |=
11429 					    CTL_FLAG_BLOCKED;
11430 					break;
11431 				case CTL_ACTION_PASS:
11432 				case CTL_ACTION_SKIP:
11433 					pending_io->io_hdr.flags |=
11434 					    CTL_FLAG_IS_WAS_ON_RTR;
11435 					ctl_enqueue_rtr(pending_io);
11436 					break;
11437 				case CTL_ACTION_OVERLAP:
11438 					ctl_set_overlapped_cmd(
11439 					    (struct ctl_scsiio *)pending_io);
11440 					ctl_done(pending_io);
11441 					break;
11442 				case CTL_ACTION_OVERLAP_TAG:
11443 					ctl_set_overlapped_tag(
11444 					    (struct ctl_scsiio *)pending_io,
11445 					    pending_io->scsiio.tag_num & 0xff);
11446 					ctl_done(pending_io);
11447 					break;
11448 				case CTL_ACTION_ERROR:
11449 				default:
11450 					ctl_set_internal_failure(
11451 						(struct ctl_scsiio *)pending_io,
11452 						0,  // sks_valid
11453 						0); //retry count
11454 					ctl_done(pending_io);
11455 					break;
11456 				}
11457 			}
11458 
11459 			ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
11460 		} else {
11461 			panic("Unhandled HA mode failover, LUN flags = %#x, "
11462 			      "ha_mode = #%x", lun->flags, softc->ha_mode);
11463 		}
11464 	}
11465 	ctl_pause_rtr = 0;
11466 	mtx_unlock(&softc->ctl_lock);
11467 }
11468 
11469 static int
11470 ctl_scsiio_precheck(struct ctl_softc *softc, struct ctl_scsiio *ctsio)
11471 {
11472 	struct ctl_lun *lun;
11473 	const struct ctl_cmd_entry *entry;
11474 	uint32_t initidx, targ_lun;
11475 	int retval;
11476 
11477 	retval = 0;
11478 
11479 	lun = NULL;
11480 
11481 	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11482 	if ((targ_lun < CTL_MAX_LUNS)
11483 	 && ((lun = softc->ctl_luns[targ_lun]) != NULL)) {
11484 		/*
11485 		 * If the LUN is invalid, pretend that it doesn't exist.
11486 		 * It will go away as soon as all pending I/O has been
11487 		 * completed.
11488 		 */
11489 		mtx_lock(&lun->lun_lock);
11490 		if (lun->flags & CTL_LUN_DISABLED) {
11491 			mtx_unlock(&lun->lun_lock);
11492 			lun = NULL;
11493 			ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11494 			ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11495 		} else {
11496 			ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
11497 			ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr =
11498 				lun->be_lun;
11499 			if (lun->be_lun->lun_type == T_PROCESSOR) {
11500 				ctsio->io_hdr.flags |= CTL_FLAG_CONTROL_DEV;
11501 			}
11502 
11503 			/*
11504 			 * Every I/O goes into the OOA queue for a
11505 			 * particular LUN, and stays there until completion.
11506 			 */
11507 			TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr,
11508 			    ooa_links);
11509 		}
11510 	} else {
11511 		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11512 		ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11513 	}
11514 
11515 	/* Get command entry and return error if it is unsuppotyed. */
11516 	entry = ctl_validate_command(ctsio);
11517 	if (entry == NULL) {
11518 		if (lun)
11519 			mtx_unlock(&lun->lun_lock);
11520 		return (retval);
11521 	}
11522 
11523 	ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11524 	ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11525 
11526 	/*
11527 	 * Check to see whether we can send this command to LUNs that don't
11528 	 * exist.  This should pretty much only be the case for inquiry
11529 	 * and request sense.  Further checks, below, really require having
11530 	 * a LUN, so we can't really check the command anymore.  Just put
11531 	 * it on the rtr queue.
11532 	 */
11533 	if (lun == NULL) {
11534 		if (entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) {
11535 			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11536 			ctl_enqueue_rtr((union ctl_io *)ctsio);
11537 			return (retval);
11538 		}
11539 
11540 		ctl_set_unsupported_lun(ctsio);
11541 		ctl_done((union ctl_io *)ctsio);
11542 		CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11543 		return (retval);
11544 	} else {
11545 		/*
11546 		 * Make sure we support this particular command on this LUN.
11547 		 * e.g., we don't support writes to the control LUN.
11548 		 */
11549 		if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11550 			mtx_unlock(&lun->lun_lock);
11551 			ctl_set_invalid_opcode(ctsio);
11552 			ctl_done((union ctl_io *)ctsio);
11553 			return (retval);
11554 		}
11555 	}
11556 
11557 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11558 
11559 #ifdef CTL_WITH_CA
11560 	/*
11561 	 * If we've got a request sense, it'll clear the contingent
11562 	 * allegiance condition.  Otherwise, if we have a CA condition for
11563 	 * this initiator, clear it, because it sent down a command other
11564 	 * than request sense.
11565 	 */
11566 	if ((ctsio->cdb[0] != REQUEST_SENSE)
11567 	 && (ctl_is_set(lun->have_ca, initidx)))
11568 		ctl_clear_mask(lun->have_ca, initidx);
11569 #endif
11570 
11571 	/*
11572 	 * If the command has this flag set, it handles its own unit
11573 	 * attention reporting, we shouldn't do anything.  Otherwise we
11574 	 * check for any pending unit attentions, and send them back to the
11575 	 * initiator.  We only do this when a command initially comes in,
11576 	 * not when we pull it off the blocked queue.
11577 	 *
11578 	 * According to SAM-3, section 5.3.2, the order that things get
11579 	 * presented back to the host is basically unit attentions caused
11580 	 * by some sort of reset event, busy status, reservation conflicts
11581 	 * or task set full, and finally any other status.
11582 	 *
11583 	 * One issue here is that some of the unit attentions we report
11584 	 * don't fall into the "reset" category (e.g. "reported luns data
11585 	 * has changed").  So reporting it here, before the reservation
11586 	 * check, may be technically wrong.  I guess the only thing to do
11587 	 * would be to check for and report the reset events here, and then
11588 	 * check for the other unit attention types after we check for a
11589 	 * reservation conflict.
11590 	 *
11591 	 * XXX KDM need to fix this
11592 	 */
11593 	if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11594 		ctl_ua_type ua_type;
11595 		scsi_sense_data_type sense_format;
11596 
11597 		if (lun->flags & CTL_LUN_SENSE_DESC)
11598 			sense_format = SSD_TYPE_DESC;
11599 		else
11600 			sense_format = SSD_TYPE_FIXED;
11601 
11602 		ua_type = ctl_build_ua(lun, initidx, &ctsio->sense_data,
11603 		    sense_format);
11604 		if (ua_type != CTL_UA_NONE) {
11605 			mtx_unlock(&lun->lun_lock);
11606 			ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11607 			ctsio->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
11608 			ctsio->sense_len = SSD_FULL_SIZE;
11609 			ctl_done((union ctl_io *)ctsio);
11610 			return (retval);
11611 		}
11612 	}
11613 
11614 
11615 	if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
11616 		mtx_unlock(&lun->lun_lock);
11617 		ctl_done((union ctl_io *)ctsio);
11618 		return (retval);
11619 	}
11620 
11621 	/*
11622 	 * XXX CHD this is where we want to send IO to other side if
11623 	 * this LUN is secondary on this SC. We will need to make a copy
11624 	 * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11625 	 * the copy we send as FROM_OTHER.
11626 	 * We also need to stuff the address of the original IO so we can
11627 	 * find it easily. Something similar will need be done on the other
11628 	 * side so when we are done we can find the copy.
11629 	 */
11630 	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11631 		union ctl_ha_msg msg_info;
11632 		int isc_retval;
11633 
11634 		ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11635 
11636 		msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11637 		msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11638 #if 0
11639 		printf("1. ctsio %p\n", ctsio);
11640 #endif
11641 		msg_info.hdr.serializing_sc = NULL;
11642 		msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11643 		msg_info.scsi.tag_num = ctsio->tag_num;
11644 		msg_info.scsi.tag_type = ctsio->tag_type;
11645 		memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11646 
11647 		ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11648 
11649 		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11650 		    (void *)&msg_info, sizeof(msg_info), 0)) >
11651 		    CTL_HA_STATUS_SUCCESS) {
11652 			printf("CTL:precheck, ctl_ha_msg_send returned %d\n",
11653 			       isc_retval);
11654 			printf("CTL:opcode is %x\n", ctsio->cdb[0]);
11655 		} else {
11656 #if 0
11657 			printf("CTL:Precheck sent msg, opcode is %x\n",opcode);
11658 #endif
11659 		}
11660 
11661 		/*
11662 		 * XXX KDM this I/O is off the incoming queue, but hasn't
11663 		 * been inserted on any other queue.  We may need to come
11664 		 * up with a holding queue while we wait for serialization
11665 		 * so that we have an idea of what we're waiting for from
11666 		 * the other side.
11667 		 */
11668 		mtx_unlock(&lun->lun_lock);
11669 		return (retval);
11670 	}
11671 
11672 	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11673 			      (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11674 			      ctl_ooaq, ooa_links))) {
11675 	case CTL_ACTION_BLOCK:
11676 		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11677 		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11678 				  blocked_links);
11679 		mtx_unlock(&lun->lun_lock);
11680 		return (retval);
11681 	case CTL_ACTION_PASS:
11682 	case CTL_ACTION_SKIP:
11683 		ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11684 		mtx_unlock(&lun->lun_lock);
11685 		ctl_enqueue_rtr((union ctl_io *)ctsio);
11686 		break;
11687 	case CTL_ACTION_OVERLAP:
11688 		mtx_unlock(&lun->lun_lock);
11689 		ctl_set_overlapped_cmd(ctsio);
11690 		ctl_done((union ctl_io *)ctsio);
11691 		break;
11692 	case CTL_ACTION_OVERLAP_TAG:
11693 		mtx_unlock(&lun->lun_lock);
11694 		ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11695 		ctl_done((union ctl_io *)ctsio);
11696 		break;
11697 	case CTL_ACTION_ERROR:
11698 	default:
11699 		mtx_unlock(&lun->lun_lock);
11700 		ctl_set_internal_failure(ctsio,
11701 					 /*sks_valid*/ 0,
11702 					 /*retry_count*/ 0);
11703 		ctl_done((union ctl_io *)ctsio);
11704 		break;
11705 	}
11706 	return (retval);
11707 }
11708 
11709 const struct ctl_cmd_entry *
11710 ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11711 {
11712 	const struct ctl_cmd_entry *entry;
11713 	int service_action;
11714 
11715 	entry = &ctl_cmd_table[ctsio->cdb[0]];
11716 	if (sa)
11717 		*sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11718 	if (entry->flags & CTL_CMD_FLAG_SA5) {
11719 		service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11720 		entry = &((const struct ctl_cmd_entry *)
11721 		    entry->execute)[service_action];
11722 	}
11723 	return (entry);
11724 }
11725 
11726 const struct ctl_cmd_entry *
11727 ctl_validate_command(struct ctl_scsiio *ctsio)
11728 {
11729 	const struct ctl_cmd_entry *entry;
11730 	int i, sa;
11731 	uint8_t diff;
11732 
11733 	entry = ctl_get_cmd_entry(ctsio, &sa);
11734 	if (entry->execute == NULL) {
11735 		if (sa)
11736 			ctl_set_invalid_field(ctsio,
11737 					      /*sks_valid*/ 1,
11738 					      /*command*/ 1,
11739 					      /*field*/ 1,
11740 					      /*bit_valid*/ 1,
11741 					      /*bit*/ 4);
11742 		else
11743 			ctl_set_invalid_opcode(ctsio);
11744 		ctl_done((union ctl_io *)ctsio);
11745 		return (NULL);
11746 	}
11747 	KASSERT(entry->length > 0,
11748 	    ("Not defined length for command 0x%02x/0x%02x",
11749 	     ctsio->cdb[0], ctsio->cdb[1]));
11750 	for (i = 1; i < entry->length; i++) {
11751 		diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11752 		if (diff == 0)
11753 			continue;
11754 		ctl_set_invalid_field(ctsio,
11755 				      /*sks_valid*/ 1,
11756 				      /*command*/ 1,
11757 				      /*field*/ i,
11758 				      /*bit_valid*/ 1,
11759 				      /*bit*/ fls(diff) - 1);
11760 		ctl_done((union ctl_io *)ctsio);
11761 		return (NULL);
11762 	}
11763 	return (entry);
11764 }
11765 
11766 static int
11767 ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11768 {
11769 
11770 	switch (lun_type) {
11771 	case T_PROCESSOR:
11772 		if (((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0) &&
11773 		    ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11774 			return (0);
11775 		break;
11776 	case T_DIRECT:
11777 		if (((entry->flags & CTL_CMD_FLAG_OK_ON_SLUN) == 0) &&
11778 		    ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11779 			return (0);
11780 		break;
11781 	default:
11782 		return (0);
11783 	}
11784 	return (1);
11785 }
11786 
11787 static int
11788 ctl_scsiio(struct ctl_scsiio *ctsio)
11789 {
11790 	int retval;
11791 	const struct ctl_cmd_entry *entry;
11792 
11793 	retval = CTL_RETVAL_COMPLETE;
11794 
11795 	CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11796 
11797 	entry = ctl_get_cmd_entry(ctsio, NULL);
11798 
11799 	/*
11800 	 * If this I/O has been aborted, just send it straight to
11801 	 * ctl_done() without executing it.
11802 	 */
11803 	if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11804 		ctl_done((union ctl_io *)ctsio);
11805 		goto bailout;
11806 	}
11807 
11808 	/*
11809 	 * All the checks should have been handled by ctl_scsiio_precheck().
11810 	 * We should be clear now to just execute the I/O.
11811 	 */
11812 	retval = entry->execute(ctsio);
11813 
11814 bailout:
11815 	return (retval);
11816 }
11817 
11818 /*
11819  * Since we only implement one target right now, a bus reset simply resets
11820  * our single target.
11821  */
11822 static int
11823 ctl_bus_reset(struct ctl_softc *softc, union ctl_io *io)
11824 {
11825 	return(ctl_target_reset(softc, io, CTL_UA_BUS_RESET));
11826 }
11827 
11828 static int
11829 ctl_target_reset(struct ctl_softc *softc, union ctl_io *io,
11830 		 ctl_ua_type ua_type)
11831 {
11832 	struct ctl_lun *lun;
11833 	int retval;
11834 
11835 	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11836 		union ctl_ha_msg msg_info;
11837 
11838 		io->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11839 		msg_info.hdr.nexus = io->io_hdr.nexus;
11840 		if (ua_type==CTL_UA_TARG_RESET)
11841 			msg_info.task.task_action = CTL_TASK_TARGET_RESET;
11842 		else
11843 			msg_info.task.task_action = CTL_TASK_BUS_RESET;
11844 		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11845 		msg_info.hdr.original_sc = NULL;
11846 		msg_info.hdr.serializing_sc = NULL;
11847 		if (CTL_HA_STATUS_SUCCESS != ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11848 		    (void *)&msg_info, sizeof(msg_info), 0)) {
11849 		}
11850 	}
11851 	retval = 0;
11852 
11853 	mtx_lock(&softc->ctl_lock);
11854 	STAILQ_FOREACH(lun, &softc->lun_list, links)
11855 		retval += ctl_lun_reset(lun, io, ua_type);
11856 	mtx_unlock(&softc->ctl_lock);
11857 
11858 	return (retval);
11859 }
11860 
11861 /*
11862  * The LUN should always be set.  The I/O is optional, and is used to
11863  * distinguish between I/Os sent by this initiator, and by other
11864  * initiators.  We set unit attention for initiators other than this one.
11865  * SAM-3 is vague on this point.  It does say that a unit attention should
11866  * be established for other initiators when a LUN is reset (see section
11867  * 5.7.3), but it doesn't specifically say that the unit attention should
11868  * be established for this particular initiator when a LUN is reset.  Here
11869  * is the relevant text, from SAM-3 rev 8:
11870  *
11871  * 5.7.2 When a SCSI initiator port aborts its own tasks
11872  *
11873  * When a SCSI initiator port causes its own task(s) to be aborted, no
11874  * notification that the task(s) have been aborted shall be returned to
11875  * the SCSI initiator port other than the completion response for the
11876  * command or task management function action that caused the task(s) to
11877  * be aborted and notification(s) associated with related effects of the
11878  * action (e.g., a reset unit attention condition).
11879  *
11880  * XXX KDM for now, we're setting unit attention for all initiators.
11881  */
11882 static int
11883 ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
11884 {
11885 	union ctl_io *xio;
11886 #if 0
11887 	uint32_t initidx;
11888 #endif
11889 #ifdef CTL_WITH_CA
11890 	int i;
11891 #endif
11892 
11893 	mtx_lock(&lun->lun_lock);
11894 	/*
11895 	 * Run through the OOA queue and abort each I/O.
11896 	 */
11897 #if 0
11898 	TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
11899 #endif
11900 	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11901 	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11902 		xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
11903 	}
11904 
11905 	/*
11906 	 * This version sets unit attention for every
11907 	 */
11908 #if 0
11909 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
11910 	ctl_est_ua_all(lun, initidx, ua_type);
11911 #else
11912 	ctl_est_ua_all(lun, -1, ua_type);
11913 #endif
11914 
11915 	/*
11916 	 * A reset (any kind, really) clears reservations established with
11917 	 * RESERVE/RELEASE.  It does not clear reservations established
11918 	 * with PERSISTENT RESERVE OUT, but we don't support that at the
11919 	 * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
11920 	 * reservations made with the RESERVE/RELEASE commands, because
11921 	 * those commands are obsolete in SPC-3.
11922 	 */
11923 	lun->flags &= ~CTL_LUN_RESERVED;
11924 
11925 #ifdef CTL_WITH_CA
11926 	for (i = 0; i < CTL_MAX_INITIATORS; i++)
11927 		ctl_clear_mask(lun->have_ca, i);
11928 #endif
11929 	mtx_unlock(&lun->lun_lock);
11930 
11931 	return (0);
11932 }
11933 
11934 static void
11935 ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
11936     int other_sc)
11937 {
11938 	union ctl_io *xio;
11939 
11940 	mtx_assert(&lun->lun_lock, MA_OWNED);
11941 
11942 	/*
11943 	 * Run through the OOA queue and attempt to find the given I/O.
11944 	 * The target port, initiator ID, tag type and tag number have to
11945 	 * match the values that we got from the initiator.  If we have an
11946 	 * untagged command to abort, simply abort the first untagged command
11947 	 * we come to.  We only allow one untagged command at a time of course.
11948 	 */
11949 	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11950 	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11951 
11952 		if ((targ_port == UINT32_MAX ||
11953 		     targ_port == xio->io_hdr.nexus.targ_port) &&
11954 		    (init_id == UINT32_MAX ||
11955 		     init_id == xio->io_hdr.nexus.initid.id)) {
11956 			if (targ_port != xio->io_hdr.nexus.targ_port ||
11957 			    init_id != xio->io_hdr.nexus.initid.id)
11958 				xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
11959 			xio->io_hdr.flags |= CTL_FLAG_ABORT;
11960 			if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11961 				union ctl_ha_msg msg_info;
11962 
11963 				msg_info.hdr.nexus = xio->io_hdr.nexus;
11964 				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
11965 				msg_info.task.tag_num = xio->scsiio.tag_num;
11966 				msg_info.task.tag_type = xio->scsiio.tag_type;
11967 				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11968 				msg_info.hdr.original_sc = NULL;
11969 				msg_info.hdr.serializing_sc = NULL;
11970 				ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11971 				    (void *)&msg_info, sizeof(msg_info), 0);
11972 			}
11973 		}
11974 	}
11975 }
11976 
11977 static int
11978 ctl_abort_task_set(union ctl_io *io)
11979 {
11980 	struct ctl_softc *softc = control_softc;
11981 	struct ctl_lun *lun;
11982 	uint32_t targ_lun;
11983 
11984 	/*
11985 	 * Look up the LUN.
11986 	 */
11987 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11988 	mtx_lock(&softc->ctl_lock);
11989 	if ((targ_lun < CTL_MAX_LUNS) && (softc->ctl_luns[targ_lun] != NULL))
11990 		lun = softc->ctl_luns[targ_lun];
11991 	else {
11992 		mtx_unlock(&softc->ctl_lock);
11993 		return (1);
11994 	}
11995 
11996 	mtx_lock(&lun->lun_lock);
11997 	mtx_unlock(&softc->ctl_lock);
11998 	if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
11999 		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12000 		    io->io_hdr.nexus.initid.id,
12001 		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12002 	} else { /* CTL_TASK_CLEAR_TASK_SET */
12003 		ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
12004 		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12005 	}
12006 	mtx_unlock(&lun->lun_lock);
12007 	return (0);
12008 }
12009 
12010 static int
12011 ctl_i_t_nexus_reset(union ctl_io *io)
12012 {
12013 	struct ctl_softc *softc = control_softc;
12014 	struct ctl_lun *lun;
12015 	uint32_t initidx, residx;
12016 
12017 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
12018 	residx = ctl_get_resindex(&io->io_hdr.nexus);
12019 	mtx_lock(&softc->ctl_lock);
12020 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
12021 		mtx_lock(&lun->lun_lock);
12022 		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12023 		    io->io_hdr.nexus.initid.id,
12024 		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12025 #ifdef CTL_WITH_CA
12026 		ctl_clear_mask(lun->have_ca, initidx);
12027 #endif
12028 		if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
12029 			lun->flags &= ~CTL_LUN_RESERVED;
12030 		ctl_est_ua(lun, initidx, CTL_UA_I_T_NEXUS_LOSS);
12031 		mtx_unlock(&lun->lun_lock);
12032 	}
12033 	mtx_unlock(&softc->ctl_lock);
12034 	return (0);
12035 }
12036 
12037 static int
12038 ctl_abort_task(union ctl_io *io)
12039 {
12040 	union ctl_io *xio;
12041 	struct ctl_lun *lun;
12042 	struct ctl_softc *softc;
12043 #if 0
12044 	struct sbuf sb;
12045 	char printbuf[128];
12046 #endif
12047 	int found;
12048 	uint32_t targ_lun;
12049 
12050 	softc = control_softc;
12051 	found = 0;
12052 
12053 	/*
12054 	 * Look up the LUN.
12055 	 */
12056 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12057 	mtx_lock(&softc->ctl_lock);
12058 	if ((targ_lun < CTL_MAX_LUNS)
12059 	 && (softc->ctl_luns[targ_lun] != NULL))
12060 		lun = softc->ctl_luns[targ_lun];
12061 	else {
12062 		mtx_unlock(&softc->ctl_lock);
12063 		return (1);
12064 	}
12065 
12066 #if 0
12067 	printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
12068 	       lun->lun, io->taskio.tag_num, io->taskio.tag_type);
12069 #endif
12070 
12071 	mtx_lock(&lun->lun_lock);
12072 	mtx_unlock(&softc->ctl_lock);
12073 	/*
12074 	 * Run through the OOA queue and attempt to find the given I/O.
12075 	 * The target port, initiator ID, tag type and tag number have to
12076 	 * match the values that we got from the initiator.  If we have an
12077 	 * untagged command to abort, simply abort the first untagged command
12078 	 * we come to.  We only allow one untagged command at a time of course.
12079 	 */
12080 #if 0
12081 	TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
12082 #endif
12083 	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12084 	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12085 #if 0
12086 		sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
12087 
12088 		sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
12089 			    lun->lun, xio->scsiio.tag_num,
12090 			    xio->scsiio.tag_type,
12091 			    (xio->io_hdr.blocked_links.tqe_prev
12092 			    == NULL) ? "" : " BLOCKED",
12093 			    (xio->io_hdr.flags &
12094 			    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
12095 			    (xio->io_hdr.flags &
12096 			    CTL_FLAG_ABORT) ? " ABORT" : "",
12097 			    (xio->io_hdr.flags &
12098 			    CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
12099 		ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
12100 		sbuf_finish(&sb);
12101 		printf("%s\n", sbuf_data(&sb));
12102 #endif
12103 
12104 		if ((xio->io_hdr.nexus.targ_port == io->io_hdr.nexus.targ_port)
12105 		 && (xio->io_hdr.nexus.initid.id ==
12106 		     io->io_hdr.nexus.initid.id)) {
12107 			/*
12108 			 * If the abort says that the task is untagged, the
12109 			 * task in the queue must be untagged.  Otherwise,
12110 			 * we just check to see whether the tag numbers
12111 			 * match.  This is because the QLogic firmware
12112 			 * doesn't pass back the tag type in an abort
12113 			 * request.
12114 			 */
12115 #if 0
12116 			if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
12117 			  && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
12118 			 || (xio->scsiio.tag_num == io->taskio.tag_num)) {
12119 #endif
12120 			/*
12121 			 * XXX KDM we've got problems with FC, because it
12122 			 * doesn't send down a tag type with aborts.  So we
12123 			 * can only really go by the tag number...
12124 			 * This may cause problems with parallel SCSI.
12125 			 * Need to figure that out!!
12126 			 */
12127 			if (xio->scsiio.tag_num == io->taskio.tag_num) {
12128 				xio->io_hdr.flags |= CTL_FLAG_ABORT;
12129 				found = 1;
12130 				if ((io->io_hdr.flags &
12131 				     CTL_FLAG_FROM_OTHER_SC) == 0 &&
12132 				    !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12133 					union ctl_ha_msg msg_info;
12134 
12135 					io->io_hdr.flags |=
12136 					                CTL_FLAG_SENT_2OTHER_SC;
12137 					msg_info.hdr.nexus = io->io_hdr.nexus;
12138 					msg_info.task.task_action =
12139 						CTL_TASK_ABORT_TASK;
12140 					msg_info.task.tag_num =
12141 						io->taskio.tag_num;
12142 					msg_info.task.tag_type =
12143 						io->taskio.tag_type;
12144 					msg_info.hdr.msg_type =
12145 						CTL_MSG_MANAGE_TASKS;
12146 					msg_info.hdr.original_sc = NULL;
12147 					msg_info.hdr.serializing_sc = NULL;
12148 #if 0
12149 					printf("Sent Abort to other side\n");
12150 #endif
12151 					if (CTL_HA_STATUS_SUCCESS !=
12152 					        ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12153 		    				(void *)&msg_info,
12154 						sizeof(msg_info), 0)) {
12155 					}
12156 				}
12157 #if 0
12158 				printf("ctl_abort_task: found I/O to abort\n");
12159 #endif
12160 				break;
12161 			}
12162 		}
12163 	}
12164 	mtx_unlock(&lun->lun_lock);
12165 
12166 	if (found == 0) {
12167 		/*
12168 		 * This isn't really an error.  It's entirely possible for
12169 		 * the abort and command completion to cross on the wire.
12170 		 * This is more of an informative/diagnostic error.
12171 		 */
12172 #if 0
12173 		printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
12174 		       "%d:%d:%d:%d tag %d type %d\n",
12175 		       io->io_hdr.nexus.initid.id,
12176 		       io->io_hdr.nexus.targ_port,
12177 		       io->io_hdr.nexus.targ_target.id,
12178 		       io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
12179 		       io->taskio.tag_type);
12180 #endif
12181 	}
12182 	return (0);
12183 }
12184 
12185 static void
12186 ctl_run_task(union ctl_io *io)
12187 {
12188 	struct ctl_softc *softc = control_softc;
12189 	int retval = 1;
12190 	const char *task_desc;
12191 
12192 	CTL_DEBUG_PRINT(("ctl_run_task\n"));
12193 
12194 	KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12195 	    ("ctl_run_task: Unextected io_type %d\n",
12196 	     io->io_hdr.io_type));
12197 
12198 	task_desc = ctl_scsi_task_string(&io->taskio);
12199 	if (task_desc != NULL) {
12200 #ifdef NEEDTOPORT
12201 		csevent_log(CSC_CTL | CSC_SHELF_SW |
12202 			    CTL_TASK_REPORT,
12203 			    csevent_LogType_Trace,
12204 			    csevent_Severity_Information,
12205 			    csevent_AlertLevel_Green,
12206 			    csevent_FRU_Firmware,
12207 			    csevent_FRU_Unknown,
12208 			    "CTL: received task: %s",task_desc);
12209 #endif
12210 	} else {
12211 #ifdef NEEDTOPORT
12212 		csevent_log(CSC_CTL | CSC_SHELF_SW |
12213 			    CTL_TASK_REPORT,
12214 			    csevent_LogType_Trace,
12215 			    csevent_Severity_Information,
12216 			    csevent_AlertLevel_Green,
12217 			    csevent_FRU_Firmware,
12218 			    csevent_FRU_Unknown,
12219 			    "CTL: received unknown task "
12220 			    "type: %d (%#x)",
12221 			    io->taskio.task_action,
12222 			    io->taskio.task_action);
12223 #endif
12224 	}
12225 	switch (io->taskio.task_action) {
12226 	case CTL_TASK_ABORT_TASK:
12227 		retval = ctl_abort_task(io);
12228 		break;
12229 	case CTL_TASK_ABORT_TASK_SET:
12230 	case CTL_TASK_CLEAR_TASK_SET:
12231 		retval = ctl_abort_task_set(io);
12232 		break;
12233 	case CTL_TASK_CLEAR_ACA:
12234 		break;
12235 	case CTL_TASK_I_T_NEXUS_RESET:
12236 		retval = ctl_i_t_nexus_reset(io);
12237 		break;
12238 	case CTL_TASK_LUN_RESET: {
12239 		struct ctl_lun *lun;
12240 		uint32_t targ_lun;
12241 
12242 		targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12243 		mtx_lock(&softc->ctl_lock);
12244 		if ((targ_lun < CTL_MAX_LUNS)
12245 		 && (softc->ctl_luns[targ_lun] != NULL))
12246 			lun = softc->ctl_luns[targ_lun];
12247 		else {
12248 			mtx_unlock(&softc->ctl_lock);
12249 			retval = 1;
12250 			break;
12251 		}
12252 
12253 		if (!(io->io_hdr.flags &
12254 		    CTL_FLAG_FROM_OTHER_SC)) {
12255 			union ctl_ha_msg msg_info;
12256 
12257 			io->io_hdr.flags |=
12258 				CTL_FLAG_SENT_2OTHER_SC;
12259 			msg_info.hdr.msg_type =
12260 				CTL_MSG_MANAGE_TASKS;
12261 			msg_info.hdr.nexus = io->io_hdr.nexus;
12262 			msg_info.task.task_action =
12263 				CTL_TASK_LUN_RESET;
12264 			msg_info.hdr.original_sc = NULL;
12265 			msg_info.hdr.serializing_sc = NULL;
12266 			if (CTL_HA_STATUS_SUCCESS !=
12267 			    ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12268 			    (void *)&msg_info,
12269 			    sizeof(msg_info), 0)) {
12270 			}
12271 		}
12272 
12273 		retval = ctl_lun_reset(lun, io,
12274 				       CTL_UA_LUN_RESET);
12275 		mtx_unlock(&softc->ctl_lock);
12276 		break;
12277 	}
12278 	case CTL_TASK_TARGET_RESET:
12279 		retval = ctl_target_reset(softc, io, CTL_UA_TARG_RESET);
12280 		break;
12281 	case CTL_TASK_BUS_RESET:
12282 		retval = ctl_bus_reset(softc, io);
12283 		break;
12284 	case CTL_TASK_PORT_LOGIN:
12285 		break;
12286 	case CTL_TASK_PORT_LOGOUT:
12287 		break;
12288 	default:
12289 		printf("ctl_run_task: got unknown task management event %d\n",
12290 		       io->taskio.task_action);
12291 		break;
12292 	}
12293 	if (retval == 0)
12294 		io->io_hdr.status = CTL_SUCCESS;
12295 	else
12296 		io->io_hdr.status = CTL_ERROR;
12297 	ctl_done(io);
12298 }
12299 
12300 /*
12301  * For HA operation.  Handle commands that come in from the other
12302  * controller.
12303  */
12304 static void
12305 ctl_handle_isc(union ctl_io *io)
12306 {
12307 	int free_io;
12308 	struct ctl_lun *lun;
12309 	struct ctl_softc *softc;
12310 	uint32_t targ_lun;
12311 
12312 	softc = control_softc;
12313 
12314 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12315 	lun = softc->ctl_luns[targ_lun];
12316 
12317 	switch (io->io_hdr.msg_type) {
12318 	case CTL_MSG_SERIALIZE:
12319 		free_io = ctl_serialize_other_sc_cmd(&io->scsiio);
12320 		break;
12321 	case CTL_MSG_R2R: {
12322 		const struct ctl_cmd_entry *entry;
12323 
12324 		/*
12325 		 * This is only used in SER_ONLY mode.
12326 		 */
12327 		free_io = 0;
12328 		entry = ctl_get_cmd_entry(&io->scsiio, NULL);
12329 		mtx_lock(&lun->lun_lock);
12330 		if (ctl_scsiio_lun_check(lun,
12331 		    entry, (struct ctl_scsiio *)io) != 0) {
12332 			mtx_unlock(&lun->lun_lock);
12333 			ctl_done(io);
12334 			break;
12335 		}
12336 		io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12337 		mtx_unlock(&lun->lun_lock);
12338 		ctl_enqueue_rtr(io);
12339 		break;
12340 	}
12341 	case CTL_MSG_FINISH_IO:
12342 		if (softc->ha_mode == CTL_HA_MODE_XFER) {
12343 			free_io = 0;
12344 			ctl_done(io);
12345 		} else {
12346 			free_io = 1;
12347 			mtx_lock(&lun->lun_lock);
12348 			TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr,
12349 				     ooa_links);
12350 			ctl_check_blocked(lun);
12351 			mtx_unlock(&lun->lun_lock);
12352 		}
12353 		break;
12354 	case CTL_MSG_PERS_ACTION:
12355 		ctl_hndl_per_res_out_on_other_sc(
12356 			(union ctl_ha_msg *)&io->presio.pr_msg);
12357 		free_io = 1;
12358 		break;
12359 	case CTL_MSG_BAD_JUJU:
12360 		free_io = 0;
12361 		ctl_done(io);
12362 		break;
12363 	case CTL_MSG_DATAMOVE:
12364 		/* Only used in XFER mode */
12365 		free_io = 0;
12366 		ctl_datamove_remote(io);
12367 		break;
12368 	case CTL_MSG_DATAMOVE_DONE:
12369 		/* Only used in XFER mode */
12370 		free_io = 0;
12371 		io->scsiio.be_move_done(io);
12372 		break;
12373 	default:
12374 		free_io = 1;
12375 		printf("%s: Invalid message type %d\n",
12376 		       __func__, io->io_hdr.msg_type);
12377 		break;
12378 	}
12379 	if (free_io)
12380 		ctl_free_io(io);
12381 
12382 }
12383 
12384 
12385 /*
12386  * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12387  * there is no match.
12388  */
12389 static ctl_lun_error_pattern
12390 ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12391 {
12392 	const struct ctl_cmd_entry *entry;
12393 	ctl_lun_error_pattern filtered_pattern, pattern;
12394 
12395 	pattern = desc->error_pattern;
12396 
12397 	/*
12398 	 * XXX KDM we need more data passed into this function to match a
12399 	 * custom pattern, and we actually need to implement custom pattern
12400 	 * matching.
12401 	 */
12402 	if (pattern & CTL_LUN_PAT_CMD)
12403 		return (CTL_LUN_PAT_CMD);
12404 
12405 	if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12406 		return (CTL_LUN_PAT_ANY);
12407 
12408 	entry = ctl_get_cmd_entry(ctsio, NULL);
12409 
12410 	filtered_pattern = entry->pattern & pattern;
12411 
12412 	/*
12413 	 * If the user requested specific flags in the pattern (e.g.
12414 	 * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12415 	 * flags.
12416 	 *
12417 	 * If the user did not specify any flags, it doesn't matter whether
12418 	 * or not the command supports the flags.
12419 	 */
12420 	if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12421 	     (pattern & ~CTL_LUN_PAT_MASK))
12422 		return (CTL_LUN_PAT_NONE);
12423 
12424 	/*
12425 	 * If the user asked for a range check, see if the requested LBA
12426 	 * range overlaps with this command's LBA range.
12427 	 */
12428 	if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12429 		uint64_t lba1;
12430 		uint64_t len1;
12431 		ctl_action action;
12432 		int retval;
12433 
12434 		retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12435 		if (retval != 0)
12436 			return (CTL_LUN_PAT_NONE);
12437 
12438 		action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12439 					      desc->lba_range.len, FALSE);
12440 		/*
12441 		 * A "pass" means that the LBA ranges don't overlap, so
12442 		 * this doesn't match the user's range criteria.
12443 		 */
12444 		if (action == CTL_ACTION_PASS)
12445 			return (CTL_LUN_PAT_NONE);
12446 	}
12447 
12448 	return (filtered_pattern);
12449 }
12450 
12451 static void
12452 ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12453 {
12454 	struct ctl_error_desc *desc, *desc2;
12455 
12456 	mtx_assert(&lun->lun_lock, MA_OWNED);
12457 
12458 	STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12459 		ctl_lun_error_pattern pattern;
12460 		/*
12461 		 * Check to see whether this particular command matches
12462 		 * the pattern in the descriptor.
12463 		 */
12464 		pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12465 		if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12466 			continue;
12467 
12468 		switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12469 		case CTL_LUN_INJ_ABORTED:
12470 			ctl_set_aborted(&io->scsiio);
12471 			break;
12472 		case CTL_LUN_INJ_MEDIUM_ERR:
12473 			ctl_set_medium_error(&io->scsiio);
12474 			break;
12475 		case CTL_LUN_INJ_UA:
12476 			/* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12477 			 * OCCURRED */
12478 			ctl_set_ua(&io->scsiio, 0x29, 0x00);
12479 			break;
12480 		case CTL_LUN_INJ_CUSTOM:
12481 			/*
12482 			 * We're assuming the user knows what he is doing.
12483 			 * Just copy the sense information without doing
12484 			 * checks.
12485 			 */
12486 			bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12487 			      MIN(sizeof(desc->custom_sense),
12488 				  sizeof(io->scsiio.sense_data)));
12489 			io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12490 			io->scsiio.sense_len = SSD_FULL_SIZE;
12491 			io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12492 			break;
12493 		case CTL_LUN_INJ_NONE:
12494 		default:
12495 			/*
12496 			 * If this is an error injection type we don't know
12497 			 * about, clear the continuous flag (if it is set)
12498 			 * so it will get deleted below.
12499 			 */
12500 			desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12501 			break;
12502 		}
12503 		/*
12504 		 * By default, each error injection action is a one-shot
12505 		 */
12506 		if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12507 			continue;
12508 
12509 		STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12510 
12511 		free(desc, M_CTL);
12512 	}
12513 }
12514 
12515 #ifdef CTL_IO_DELAY
12516 static void
12517 ctl_datamove_timer_wakeup(void *arg)
12518 {
12519 	union ctl_io *io;
12520 
12521 	io = (union ctl_io *)arg;
12522 
12523 	ctl_datamove(io);
12524 }
12525 #endif /* CTL_IO_DELAY */
12526 
12527 void
12528 ctl_datamove(union ctl_io *io)
12529 {
12530 	void (*fe_datamove)(union ctl_io *io);
12531 
12532 	mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12533 
12534 	CTL_DEBUG_PRINT(("ctl_datamove\n"));
12535 
12536 #ifdef CTL_TIME_IO
12537 	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12538 		char str[256];
12539 		char path_str[64];
12540 		struct sbuf sb;
12541 
12542 		ctl_scsi_path_string(io, path_str, sizeof(path_str));
12543 		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12544 
12545 		sbuf_cat(&sb, path_str);
12546 		switch (io->io_hdr.io_type) {
12547 		case CTL_IO_SCSI:
12548 			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12549 			sbuf_printf(&sb, "\n");
12550 			sbuf_cat(&sb, path_str);
12551 			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12552 				    io->scsiio.tag_num, io->scsiio.tag_type);
12553 			break;
12554 		case CTL_IO_TASK:
12555 			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12556 				    "Tag Type: %d\n", io->taskio.task_action,
12557 				    io->taskio.tag_num, io->taskio.tag_type);
12558 			break;
12559 		default:
12560 			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12561 			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12562 			break;
12563 		}
12564 		sbuf_cat(&sb, path_str);
12565 		sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12566 			    (intmax_t)time_uptime - io->io_hdr.start_time);
12567 		sbuf_finish(&sb);
12568 		printf("%s", sbuf_data(&sb));
12569 	}
12570 #endif /* CTL_TIME_IO */
12571 
12572 #ifdef CTL_IO_DELAY
12573 	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12574 		struct ctl_lun *lun;
12575 
12576 		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12577 
12578 		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12579 	} else {
12580 		struct ctl_lun *lun;
12581 
12582 		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12583 		if ((lun != NULL)
12584 		 && (lun->delay_info.datamove_delay > 0)) {
12585 			struct callout *callout;
12586 
12587 			callout = (struct callout *)&io->io_hdr.timer_bytes;
12588 			callout_init(callout, /*mpsafe*/ 1);
12589 			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12590 			callout_reset(callout,
12591 				      lun->delay_info.datamove_delay * hz,
12592 				      ctl_datamove_timer_wakeup, io);
12593 			if (lun->delay_info.datamove_type ==
12594 			    CTL_DELAY_TYPE_ONESHOT)
12595 				lun->delay_info.datamove_delay = 0;
12596 			return;
12597 		}
12598 	}
12599 #endif
12600 
12601 	/*
12602 	 * This command has been aborted.  Set the port status, so we fail
12603 	 * the data move.
12604 	 */
12605 	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12606 		printf("ctl_datamove: tag 0x%04x on (%ju:%d:%ju:%d) aborted\n",
12607 		       io->scsiio.tag_num,(uintmax_t)io->io_hdr.nexus.initid.id,
12608 		       io->io_hdr.nexus.targ_port,
12609 		       (uintmax_t)io->io_hdr.nexus.targ_target.id,
12610 		       io->io_hdr.nexus.targ_lun);
12611 		io->io_hdr.port_status = 31337;
12612 		/*
12613 		 * Note that the backend, in this case, will get the
12614 		 * callback in its context.  In other cases it may get
12615 		 * called in the frontend's interrupt thread context.
12616 		 */
12617 		io->scsiio.be_move_done(io);
12618 		return;
12619 	}
12620 
12621 	/* Don't confuse frontend with zero length data move. */
12622 	if (io->scsiio.kern_data_len == 0) {
12623 		io->scsiio.be_move_done(io);
12624 		return;
12625 	}
12626 
12627 	/*
12628 	 * If we're in XFER mode and this I/O is from the other shelf
12629 	 * controller, we need to send the DMA to the other side to
12630 	 * actually transfer the data to/from the host.  In serialize only
12631 	 * mode the transfer happens below CTL and ctl_datamove() is only
12632 	 * called on the machine that originally received the I/O.
12633 	 */
12634 	if ((control_softc->ha_mode == CTL_HA_MODE_XFER)
12635 	 && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12636 		union ctl_ha_msg msg;
12637 		uint32_t sg_entries_sent;
12638 		int do_sg_copy;
12639 		int i;
12640 
12641 		memset(&msg, 0, sizeof(msg));
12642 		msg.hdr.msg_type = CTL_MSG_DATAMOVE;
12643 		msg.hdr.original_sc = io->io_hdr.original_sc;
12644 		msg.hdr.serializing_sc = io;
12645 		msg.hdr.nexus = io->io_hdr.nexus;
12646 		msg.dt.flags = io->io_hdr.flags;
12647 		/*
12648 		 * We convert everything into a S/G list here.  We can't
12649 		 * pass by reference, only by value between controllers.
12650 		 * So we can't pass a pointer to the S/G list, only as many
12651 		 * S/G entries as we can fit in here.  If it's possible for
12652 		 * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
12653 		 * then we need to break this up into multiple transfers.
12654 		 */
12655 		if (io->scsiio.kern_sg_entries == 0) {
12656 			msg.dt.kern_sg_entries = 1;
12657 			/*
12658 			 * If this is in cached memory, flush the cache
12659 			 * before we send the DMA request to the other
12660 			 * controller.  We want to do this in either the
12661 			 * read or the write case.  The read case is
12662 			 * straightforward.  In the write case, we want to
12663 			 * make sure nothing is in the local cache that
12664 			 * could overwrite the DMAed data.
12665 			 */
12666 			if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12667 				/*
12668 				 * XXX KDM use bus_dmamap_sync() here.
12669 				 */
12670 			}
12671 
12672 			/*
12673 			 * Convert to a physical address if this is a
12674 			 * virtual address.
12675 			 */
12676 			if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
12677 				msg.dt.sg_list[0].addr =
12678 					io->scsiio.kern_data_ptr;
12679 			} else {
12680 				/*
12681 				 * XXX KDM use busdma here!
12682 				 */
12683 #if 0
12684 				msg.dt.sg_list[0].addr = (void *)
12685 					vtophys(io->scsiio.kern_data_ptr);
12686 #endif
12687 			}
12688 
12689 			msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
12690 			do_sg_copy = 0;
12691 		} else {
12692 			struct ctl_sg_entry *sgl;
12693 
12694 			do_sg_copy = 1;
12695 			msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
12696 			sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
12697 			if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12698 				/*
12699 				 * XXX KDM use bus_dmamap_sync() here.
12700 				 */
12701 			}
12702 		}
12703 
12704 		msg.dt.kern_data_len = io->scsiio.kern_data_len;
12705 		msg.dt.kern_total_len = io->scsiio.kern_total_len;
12706 		msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
12707 		msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
12708 		msg.dt.sg_sequence = 0;
12709 
12710 		/*
12711 		 * Loop until we've sent all of the S/G entries.  On the
12712 		 * other end, we'll recompose these S/G entries into one
12713 		 * contiguous list before passing it to the
12714 		 */
12715 		for (sg_entries_sent = 0; sg_entries_sent <
12716 		     msg.dt.kern_sg_entries; msg.dt.sg_sequence++) {
12717 			msg.dt.cur_sg_entries = MIN((sizeof(msg.dt.sg_list)/
12718 				sizeof(msg.dt.sg_list[0])),
12719 				msg.dt.kern_sg_entries - sg_entries_sent);
12720 
12721 			if (do_sg_copy != 0) {
12722 				struct ctl_sg_entry *sgl;
12723 				int j;
12724 
12725 				sgl = (struct ctl_sg_entry *)
12726 					io->scsiio.kern_data_ptr;
12727 				/*
12728 				 * If this is in cached memory, flush the cache
12729 				 * before we send the DMA request to the other
12730 				 * controller.  We want to do this in either
12731 				 * the * read or the write case.  The read
12732 				 * case is straightforward.  In the write
12733 				 * case, we want to make sure nothing is
12734 				 * in the local cache that could overwrite
12735 				 * the DMAed data.
12736 				 */
12737 
12738 				for (i = sg_entries_sent, j = 0;
12739 				     i < msg.dt.cur_sg_entries; i++, j++) {
12740 					if ((io->io_hdr.flags &
12741 					     CTL_FLAG_NO_DATASYNC) == 0) {
12742 						/*
12743 						 * XXX KDM use bus_dmamap_sync()
12744 						 */
12745 					}
12746 					if ((io->io_hdr.flags &
12747 					     CTL_FLAG_BUS_ADDR) == 0) {
12748 						/*
12749 						 * XXX KDM use busdma.
12750 						 */
12751 #if 0
12752 						msg.dt.sg_list[j].addr =(void *)
12753 						       vtophys(sgl[i].addr);
12754 #endif
12755 					} else {
12756 						msg.dt.sg_list[j].addr =
12757 							sgl[i].addr;
12758 					}
12759 					msg.dt.sg_list[j].len = sgl[i].len;
12760 				}
12761 			}
12762 
12763 			sg_entries_sent += msg.dt.cur_sg_entries;
12764 			if (sg_entries_sent >= msg.dt.kern_sg_entries)
12765 				msg.dt.sg_last = 1;
12766 			else
12767 				msg.dt.sg_last = 0;
12768 
12769 			/*
12770 			 * XXX KDM drop and reacquire the lock here?
12771 			 */
12772 			if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12773 			    sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
12774 				/*
12775 				 * XXX do something here.
12776 				 */
12777 			}
12778 
12779 			msg.dt.sent_sg_entries = sg_entries_sent;
12780 		}
12781 		io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12782 		if (io->io_hdr.flags & CTL_FLAG_FAILOVER)
12783 			ctl_failover_io(io, /*have_lock*/ 0);
12784 
12785 	} else {
12786 
12787 		/*
12788 		 * Lookup the fe_datamove() function for this particular
12789 		 * front end.
12790 		 */
12791 		fe_datamove =
12792 		    control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12793 
12794 		fe_datamove(io);
12795 	}
12796 }
12797 
12798 static void
12799 ctl_send_datamove_done(union ctl_io *io, int have_lock)
12800 {
12801 	union ctl_ha_msg msg;
12802 	int isc_status;
12803 
12804 	memset(&msg, 0, sizeof(msg));
12805 
12806 	msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12807 	msg.hdr.original_sc = io;
12808 	msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12809 	msg.hdr.nexus = io->io_hdr.nexus;
12810 	msg.hdr.status = io->io_hdr.status;
12811 	msg.scsi.tag_num = io->scsiio.tag_num;
12812 	msg.scsi.tag_type = io->scsiio.tag_type;
12813 	msg.scsi.scsi_status = io->scsiio.scsi_status;
12814 	memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12815 	       sizeof(io->scsiio.sense_data));
12816 	msg.scsi.sense_len = io->scsiio.sense_len;
12817 	msg.scsi.sense_residual = io->scsiio.sense_residual;
12818 	msg.scsi.fetd_status = io->io_hdr.port_status;
12819 	msg.scsi.residual = io->scsiio.residual;
12820 	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12821 
12822 	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12823 		ctl_failover_io(io, /*have_lock*/ have_lock);
12824 		return;
12825 	}
12826 
12827 	isc_status = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0);
12828 	if (isc_status > CTL_HA_STATUS_SUCCESS) {
12829 		/* XXX do something if this fails */
12830 	}
12831 
12832 }
12833 
12834 /*
12835  * The DMA to the remote side is done, now we need to tell the other side
12836  * we're done so it can continue with its data movement.
12837  */
12838 static void
12839 ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12840 {
12841 	union ctl_io *io;
12842 
12843 	io = rq->context;
12844 
12845 	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12846 		printf("%s: ISC DMA write failed with error %d", __func__,
12847 		       rq->ret);
12848 		ctl_set_internal_failure(&io->scsiio,
12849 					 /*sks_valid*/ 1,
12850 					 /*retry_count*/ rq->ret);
12851 	}
12852 
12853 	ctl_dt_req_free(rq);
12854 
12855 	/*
12856 	 * In this case, we had to malloc the memory locally.  Free it.
12857 	 */
12858 	if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
12859 		int i;
12860 		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12861 			free(io->io_hdr.local_sglist[i].addr, M_CTL);
12862 	}
12863 	/*
12864 	 * The data is in local and remote memory, so now we need to send
12865 	 * status (good or back) back to the other side.
12866 	 */
12867 	ctl_send_datamove_done(io, /*have_lock*/ 0);
12868 }
12869 
12870 /*
12871  * We've moved the data from the host/controller into local memory.  Now we
12872  * need to push it over to the remote controller's memory.
12873  */
12874 static int
12875 ctl_datamove_remote_dm_write_cb(union ctl_io *io)
12876 {
12877 	int retval;
12878 
12879 	retval = 0;
12880 
12881 	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
12882 					  ctl_datamove_remote_write_cb);
12883 
12884 	return (retval);
12885 }
12886 
12887 static void
12888 ctl_datamove_remote_write(union ctl_io *io)
12889 {
12890 	int retval;
12891 	void (*fe_datamove)(union ctl_io *io);
12892 
12893 	/*
12894 	 * - Get the data from the host/HBA into local memory.
12895 	 * - DMA memory from the local controller to the remote controller.
12896 	 * - Send status back to the remote controller.
12897 	 */
12898 
12899 	retval = ctl_datamove_remote_sgl_setup(io);
12900 	if (retval != 0)
12901 		return;
12902 
12903 	/* Switch the pointer over so the FETD knows what to do */
12904 	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12905 
12906 	/*
12907 	 * Use a custom move done callback, since we need to send completion
12908 	 * back to the other controller, not to the backend on this side.
12909 	 */
12910 	io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
12911 
12912 	fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12913 
12914 	fe_datamove(io);
12915 
12916 	return;
12917 
12918 }
12919 
12920 static int
12921 ctl_datamove_remote_dm_read_cb(union ctl_io *io)
12922 {
12923 #if 0
12924 	char str[256];
12925 	char path_str[64];
12926 	struct sbuf sb;
12927 #endif
12928 
12929 	/*
12930 	 * In this case, we had to malloc the memory locally.  Free it.
12931 	 */
12932 	if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
12933 		int i;
12934 		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12935 			free(io->io_hdr.local_sglist[i].addr, M_CTL);
12936 	}
12937 
12938 #if 0
12939 	scsi_path_string(io, path_str, sizeof(path_str));
12940 	sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12941 	sbuf_cat(&sb, path_str);
12942 	scsi_command_string(&io->scsiio, NULL, &sb);
12943 	sbuf_printf(&sb, "\n");
12944 	sbuf_cat(&sb, path_str);
12945 	sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12946 		    io->scsiio.tag_num, io->scsiio.tag_type);
12947 	sbuf_cat(&sb, path_str);
12948 	sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
12949 		    io->io_hdr.flags, io->io_hdr.status);
12950 	sbuf_finish(&sb);
12951 	printk("%s", sbuf_data(&sb));
12952 #endif
12953 
12954 
12955 	/*
12956 	 * The read is done, now we need to send status (good or bad) back
12957 	 * to the other side.
12958 	 */
12959 	ctl_send_datamove_done(io, /*have_lock*/ 0);
12960 
12961 	return (0);
12962 }
12963 
12964 static void
12965 ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
12966 {
12967 	union ctl_io *io;
12968 	void (*fe_datamove)(union ctl_io *io);
12969 
12970 	io = rq->context;
12971 
12972 	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12973 		printf("%s: ISC DMA read failed with error %d", __func__,
12974 		       rq->ret);
12975 		ctl_set_internal_failure(&io->scsiio,
12976 					 /*sks_valid*/ 1,
12977 					 /*retry_count*/ rq->ret);
12978 	}
12979 
12980 	ctl_dt_req_free(rq);
12981 
12982 	/* Switch the pointer over so the FETD knows what to do */
12983 	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12984 
12985 	/*
12986 	 * Use a custom move done callback, since we need to send completion
12987 	 * back to the other controller, not to the backend on this side.
12988 	 */
12989 	io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
12990 
12991 	/* XXX KDM add checks like the ones in ctl_datamove? */
12992 
12993 	fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12994 
12995 	fe_datamove(io);
12996 }
12997 
12998 static int
12999 ctl_datamove_remote_sgl_setup(union ctl_io *io)
13000 {
13001 	struct ctl_sg_entry *local_sglist, *remote_sglist;
13002 	struct ctl_sg_entry *local_dma_sglist, *remote_dma_sglist;
13003 	struct ctl_softc *softc;
13004 	int retval;
13005 	int i;
13006 
13007 	retval = 0;
13008 	softc = control_softc;
13009 
13010 	local_sglist = io->io_hdr.local_sglist;
13011 	local_dma_sglist = io->io_hdr.local_dma_sglist;
13012 	remote_sglist = io->io_hdr.remote_sglist;
13013 	remote_dma_sglist = io->io_hdr.remote_dma_sglist;
13014 
13015 	if (io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) {
13016 		for (i = 0; i < io->scsiio.kern_sg_entries; i++) {
13017 			local_sglist[i].len = remote_sglist[i].len;
13018 
13019 			/*
13020 			 * XXX Detect the situation where the RS-level I/O
13021 			 * redirector on the other side has already read the
13022 			 * data off of the AOR RS on this side, and
13023 			 * transferred it to remote (mirror) memory on the
13024 			 * other side.  Since we already have the data in
13025 			 * memory here, we just need to use it.
13026 			 *
13027 			 * XXX KDM this can probably be removed once we
13028 			 * get the cache device code in and take the
13029 			 * current AOR implementation out.
13030 			 */
13031 #ifdef NEEDTOPORT
13032 			if ((remote_sglist[i].addr >=
13033 			     (void *)vtophys(softc->mirr->addr))
13034 			 && (remote_sglist[i].addr <
13035 			     ((void *)vtophys(softc->mirr->addr) +
13036 			     CacheMirrorOffset))) {
13037 				local_sglist[i].addr = remote_sglist[i].addr -
13038 					CacheMirrorOffset;
13039 				if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13040 				     CTL_FLAG_DATA_IN)
13041 					io->io_hdr.flags |= CTL_FLAG_REDIR_DONE;
13042 			} else {
13043 				local_sglist[i].addr = remote_sglist[i].addr +
13044 					CacheMirrorOffset;
13045 			}
13046 #endif
13047 #if 0
13048 			printf("%s: local %p, remote %p, len %d\n",
13049 			       __func__, local_sglist[i].addr,
13050 			       remote_sglist[i].addr, local_sglist[i].len);
13051 #endif
13052 		}
13053 	} else {
13054 		uint32_t len_to_go;
13055 
13056 		/*
13057 		 * In this case, we don't have automatically allocated
13058 		 * memory for this I/O on this controller.  This typically
13059 		 * happens with internal CTL I/O -- e.g. inquiry, mode
13060 		 * sense, etc.  Anything coming from RAIDCore will have
13061 		 * a mirror area available.
13062 		 */
13063 		len_to_go = io->scsiio.kern_data_len;
13064 
13065 		/*
13066 		 * Clear the no datasync flag, we have to use malloced
13067 		 * buffers.
13068 		 */
13069 		io->io_hdr.flags &= ~CTL_FLAG_NO_DATASYNC;
13070 
13071 		/*
13072 		 * The difficult thing here is that the size of the various
13073 		 * S/G segments may be different than the size from the
13074 		 * remote controller.  That'll make it harder when DMAing
13075 		 * the data back to the other side.
13076 		 */
13077 		for (i = 0; (i < sizeof(io->io_hdr.remote_sglist) /
13078 		     sizeof(io->io_hdr.remote_sglist[0])) &&
13079 		     (len_to_go > 0); i++) {
13080 			local_sglist[i].len = MIN(len_to_go, 131072);
13081 			CTL_SIZE_8B(local_dma_sglist[i].len,
13082 				    local_sglist[i].len);
13083 			local_sglist[i].addr =
13084 				malloc(local_dma_sglist[i].len, M_CTL,M_WAITOK);
13085 
13086 			local_dma_sglist[i].addr = local_sglist[i].addr;
13087 
13088 			if (local_sglist[i].addr == NULL) {
13089 				int j;
13090 
13091 				printf("malloc failed for %zd bytes!",
13092 				       local_dma_sglist[i].len);
13093 				for (j = 0; j < i; j++) {
13094 					free(local_sglist[j].addr, M_CTL);
13095 				}
13096 				ctl_set_internal_failure(&io->scsiio,
13097 							 /*sks_valid*/ 1,
13098 							 /*retry_count*/ 4857);
13099 				retval = 1;
13100 				goto bailout_error;
13101 
13102 			}
13103 			/* XXX KDM do we need a sync here? */
13104 
13105 			len_to_go -= local_sglist[i].len;
13106 		}
13107 		/*
13108 		 * Reset the number of S/G entries accordingly.  The
13109 		 * original number of S/G entries is available in
13110 		 * rem_sg_entries.
13111 		 */
13112 		io->scsiio.kern_sg_entries = i;
13113 
13114 #if 0
13115 		printf("%s: kern_sg_entries = %d\n", __func__,
13116 		       io->scsiio.kern_sg_entries);
13117 		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13118 			printf("%s: sg[%d] = %p, %d (DMA: %d)\n", __func__, i,
13119 			       local_sglist[i].addr, local_sglist[i].len,
13120 			       local_dma_sglist[i].len);
13121 #endif
13122 	}
13123 
13124 
13125 	return (retval);
13126 
13127 bailout_error:
13128 
13129 	ctl_send_datamove_done(io, /*have_lock*/ 0);
13130 
13131 	return (retval);
13132 }
13133 
13134 static int
13135 ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
13136 			 ctl_ha_dt_cb callback)
13137 {
13138 	struct ctl_ha_dt_req *rq;
13139 	struct ctl_sg_entry *remote_sglist, *local_sglist;
13140 	struct ctl_sg_entry *remote_dma_sglist, *local_dma_sglist;
13141 	uint32_t local_used, remote_used, total_used;
13142 	int retval;
13143 	int i, j;
13144 
13145 	retval = 0;
13146 
13147 	rq = ctl_dt_req_alloc();
13148 
13149 	/*
13150 	 * If we failed to allocate the request, and if the DMA didn't fail
13151 	 * anyway, set busy status.  This is just a resource allocation
13152 	 * failure.
13153 	 */
13154 	if ((rq == NULL)
13155 	 && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE))
13156 		ctl_set_busy(&io->scsiio);
13157 
13158 	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE) {
13159 
13160 		if (rq != NULL)
13161 			ctl_dt_req_free(rq);
13162 
13163 		/*
13164 		 * The data move failed.  We need to return status back
13165 		 * to the other controller.  No point in trying to DMA
13166 		 * data to the remote controller.
13167 		 */
13168 
13169 		ctl_send_datamove_done(io, /*have_lock*/ 0);
13170 
13171 		retval = 1;
13172 
13173 		goto bailout;
13174 	}
13175 
13176 	local_sglist = io->io_hdr.local_sglist;
13177 	local_dma_sglist = io->io_hdr.local_dma_sglist;
13178 	remote_sglist = io->io_hdr.remote_sglist;
13179 	remote_dma_sglist = io->io_hdr.remote_dma_sglist;
13180 	local_used = 0;
13181 	remote_used = 0;
13182 	total_used = 0;
13183 
13184 	if (io->io_hdr.flags & CTL_FLAG_REDIR_DONE) {
13185 		rq->ret = CTL_HA_STATUS_SUCCESS;
13186 		rq->context = io;
13187 		callback(rq);
13188 		goto bailout;
13189 	}
13190 
13191 	/*
13192 	 * Pull/push the data over the wire from/to the other controller.
13193 	 * This takes into account the possibility that the local and
13194 	 * remote sglists may not be identical in terms of the size of
13195 	 * the elements and the number of elements.
13196 	 *
13197 	 * One fundamental assumption here is that the length allocated for
13198 	 * both the local and remote sglists is identical.  Otherwise, we've
13199 	 * essentially got a coding error of some sort.
13200 	 */
13201 	for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
13202 		int isc_ret;
13203 		uint32_t cur_len, dma_length;
13204 		uint8_t *tmp_ptr;
13205 
13206 		rq->id = CTL_HA_DATA_CTL;
13207 		rq->command = command;
13208 		rq->context = io;
13209 
13210 		/*
13211 		 * Both pointers should be aligned.  But it is possible
13212 		 * that the allocation length is not.  They should both
13213 		 * also have enough slack left over at the end, though,
13214 		 * to round up to the next 8 byte boundary.
13215 		 */
13216 		cur_len = MIN(local_sglist[i].len - local_used,
13217 			      remote_sglist[j].len - remote_used);
13218 
13219 		/*
13220 		 * In this case, we have a size issue and need to decrease
13221 		 * the size, except in the case where we actually have less
13222 		 * than 8 bytes left.  In that case, we need to increase
13223 		 * the DMA length to get the last bit.
13224 		 */
13225 		if ((cur_len & 0x7) != 0) {
13226 			if (cur_len > 0x7) {
13227 				cur_len = cur_len - (cur_len & 0x7);
13228 				dma_length = cur_len;
13229 			} else {
13230 				CTL_SIZE_8B(dma_length, cur_len);
13231 			}
13232 
13233 		} else
13234 			dma_length = cur_len;
13235 
13236 		/*
13237 		 * If we had to allocate memory for this I/O, instead of using
13238 		 * the non-cached mirror memory, we'll need to flush the cache
13239 		 * before trying to DMA to the other controller.
13240 		 *
13241 		 * We could end up doing this multiple times for the same
13242 		 * segment if we have a larger local segment than remote
13243 		 * segment.  That shouldn't be an issue.
13244 		 */
13245 		if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
13246 			/*
13247 			 * XXX KDM use bus_dmamap_sync() here.
13248 			 */
13249 		}
13250 
13251 		rq->size = dma_length;
13252 
13253 		tmp_ptr = (uint8_t *)local_sglist[i].addr;
13254 		tmp_ptr += local_used;
13255 
13256 		/* Use physical addresses when talking to ISC hardware */
13257 		if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
13258 			/* XXX KDM use busdma */
13259 #if 0
13260 			rq->local = vtophys(tmp_ptr);
13261 #endif
13262 		} else
13263 			rq->local = tmp_ptr;
13264 
13265 		tmp_ptr = (uint8_t *)remote_sglist[j].addr;
13266 		tmp_ptr += remote_used;
13267 		rq->remote = tmp_ptr;
13268 
13269 		rq->callback = NULL;
13270 
13271 		local_used += cur_len;
13272 		if (local_used >= local_sglist[i].len) {
13273 			i++;
13274 			local_used = 0;
13275 		}
13276 
13277 		remote_used += cur_len;
13278 		if (remote_used >= remote_sglist[j].len) {
13279 			j++;
13280 			remote_used = 0;
13281 		}
13282 		total_used += cur_len;
13283 
13284 		if (total_used >= io->scsiio.kern_data_len)
13285 			rq->callback = callback;
13286 
13287 		if ((rq->size & 0x7) != 0) {
13288 			printf("%s: warning: size %d is not on 8b boundary\n",
13289 			       __func__, rq->size);
13290 		}
13291 		if (((uintptr_t)rq->local & 0x7) != 0) {
13292 			printf("%s: warning: local %p not on 8b boundary\n",
13293 			       __func__, rq->local);
13294 		}
13295 		if (((uintptr_t)rq->remote & 0x7) != 0) {
13296 			printf("%s: warning: remote %p not on 8b boundary\n",
13297 			       __func__, rq->local);
13298 		}
13299 #if 0
13300 		printf("%s: %s: local %#x remote %#x size %d\n", __func__,
13301 		       (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
13302 		       rq->local, rq->remote, rq->size);
13303 #endif
13304 
13305 		isc_ret = ctl_dt_single(rq);
13306 		if (isc_ret == CTL_HA_STATUS_WAIT)
13307 			continue;
13308 
13309 		if (isc_ret == CTL_HA_STATUS_DISCONNECT) {
13310 			rq->ret = CTL_HA_STATUS_SUCCESS;
13311 		} else {
13312 			rq->ret = isc_ret;
13313 		}
13314 		callback(rq);
13315 		goto bailout;
13316 	}
13317 
13318 bailout:
13319 	return (retval);
13320 
13321 }
13322 
13323 static void
13324 ctl_datamove_remote_read(union ctl_io *io)
13325 {
13326 	int retval;
13327 	int i;
13328 
13329 	/*
13330 	 * This will send an error to the other controller in the case of a
13331 	 * failure.
13332 	 */
13333 	retval = ctl_datamove_remote_sgl_setup(io);
13334 	if (retval != 0)
13335 		return;
13336 
13337 	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
13338 					  ctl_datamove_remote_read_cb);
13339 	if ((retval != 0)
13340 	 && ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0)) {
13341 		/*
13342 		 * Make sure we free memory if there was an error..  The
13343 		 * ctl_datamove_remote_xfer() function will send the
13344 		 * datamove done message, or call the callback with an
13345 		 * error if there is a problem.
13346 		 */
13347 		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13348 			free(io->io_hdr.local_sglist[i].addr, M_CTL);
13349 	}
13350 
13351 	return;
13352 }
13353 
13354 /*
13355  * Process a datamove request from the other controller.  This is used for
13356  * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
13357  * first.  Once that is complete, the data gets DMAed into the remote
13358  * controller's memory.  For reads, we DMA from the remote controller's
13359  * memory into our memory first, and then move it out to the FETD.
13360  */
13361 static void
13362 ctl_datamove_remote(union ctl_io *io)
13363 {
13364 	struct ctl_softc *softc;
13365 
13366 	softc = control_softc;
13367 
13368 	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
13369 
13370 	/*
13371 	 * Note that we look for an aborted I/O here, but don't do some of
13372 	 * the other checks that ctl_datamove() normally does.
13373 	 * We don't need to run the datamove delay code, since that should
13374 	 * have been done if need be on the other controller.
13375 	 */
13376 	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
13377 		printf("%s: tag 0x%04x on (%d:%d:%d:%d) aborted\n", __func__,
13378 		       io->scsiio.tag_num, io->io_hdr.nexus.initid.id,
13379 		       io->io_hdr.nexus.targ_port,
13380 		       io->io_hdr.nexus.targ_target.id,
13381 		       io->io_hdr.nexus.targ_lun);
13382 		io->io_hdr.port_status = 31338;
13383 		ctl_send_datamove_done(io, /*have_lock*/ 0);
13384 		return;
13385 	}
13386 
13387 	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT) {
13388 		ctl_datamove_remote_write(io);
13389 	} else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN){
13390 		ctl_datamove_remote_read(io);
13391 	} else {
13392 		union ctl_ha_msg msg;
13393 		struct scsi_sense_data *sense;
13394 		uint8_t sks[3];
13395 		int retry_count;
13396 
13397 		memset(&msg, 0, sizeof(msg));
13398 
13399 		msg.hdr.msg_type = CTL_MSG_BAD_JUJU;
13400 		msg.hdr.status = CTL_SCSI_ERROR;
13401 		msg.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
13402 
13403 		retry_count = 4243;
13404 
13405 		sense = &msg.scsi.sense_data;
13406 		sks[0] = SSD_SCS_VALID;
13407 		sks[1] = (retry_count >> 8) & 0xff;
13408 		sks[2] = retry_count & 0xff;
13409 
13410 		/* "Internal target failure" */
13411 		scsi_set_sense_data(sense,
13412 				    /*sense_format*/ SSD_TYPE_NONE,
13413 				    /*current_error*/ 1,
13414 				    /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
13415 				    /*asc*/ 0x44,
13416 				    /*ascq*/ 0x00,
13417 				    /*type*/ SSD_ELEM_SKS,
13418 				    /*size*/ sizeof(sks),
13419 				    /*data*/ sks,
13420 				    SSD_ELEM_NONE);
13421 
13422 		io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
13423 		if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13424 			ctl_failover_io(io, /*have_lock*/ 1);
13425 			return;
13426 		}
13427 
13428 		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0) >
13429 		    CTL_HA_STATUS_SUCCESS) {
13430 			/* XXX KDM what to do if this fails? */
13431 		}
13432 		return;
13433 	}
13434 
13435 }
13436 
13437 static int
13438 ctl_process_done(union ctl_io *io)
13439 {
13440 	struct ctl_lun *lun;
13441 	struct ctl_softc *softc = control_softc;
13442 	void (*fe_done)(union ctl_io *io);
13443 	uint32_t targ_port = ctl_port_idx(io->io_hdr.nexus.targ_port);
13444 
13445 	CTL_DEBUG_PRINT(("ctl_process_done\n"));
13446 
13447 	fe_done = softc->ctl_ports[targ_port]->fe_done;
13448 
13449 #ifdef CTL_TIME_IO
13450 	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
13451 		char str[256];
13452 		char path_str[64];
13453 		struct sbuf sb;
13454 
13455 		ctl_scsi_path_string(io, path_str, sizeof(path_str));
13456 		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13457 
13458 		sbuf_cat(&sb, path_str);
13459 		switch (io->io_hdr.io_type) {
13460 		case CTL_IO_SCSI:
13461 			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
13462 			sbuf_printf(&sb, "\n");
13463 			sbuf_cat(&sb, path_str);
13464 			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13465 				    io->scsiio.tag_num, io->scsiio.tag_type);
13466 			break;
13467 		case CTL_IO_TASK:
13468 			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
13469 				    "Tag Type: %d\n", io->taskio.task_action,
13470 				    io->taskio.tag_num, io->taskio.tag_type);
13471 			break;
13472 		default:
13473 			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13474 			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13475 			break;
13476 		}
13477 		sbuf_cat(&sb, path_str);
13478 		sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
13479 			    (intmax_t)time_uptime - io->io_hdr.start_time);
13480 		sbuf_finish(&sb);
13481 		printf("%s", sbuf_data(&sb));
13482 	}
13483 #endif /* CTL_TIME_IO */
13484 
13485 	switch (io->io_hdr.io_type) {
13486 	case CTL_IO_SCSI:
13487 		break;
13488 	case CTL_IO_TASK:
13489 		if (bootverbose || (ctl_debug & CTL_DEBUG_INFO))
13490 			ctl_io_error_print(io, NULL);
13491 		if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
13492 			ctl_free_io(io);
13493 		else
13494 			fe_done(io);
13495 		return (CTL_RETVAL_COMPLETE);
13496 	default:
13497 		panic("ctl_process_done: invalid io type %d\n",
13498 		      io->io_hdr.io_type);
13499 		break; /* NOTREACHED */
13500 	}
13501 
13502 	lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13503 	if (lun == NULL) {
13504 		CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13505 				 io->io_hdr.nexus.targ_mapped_lun));
13506 		goto bailout;
13507 	}
13508 
13509 	mtx_lock(&lun->lun_lock);
13510 
13511 	/*
13512 	 * Check to see if we have any errors to inject here.  We only
13513 	 * inject errors for commands that don't already have errors set.
13514 	 */
13515 	if ((STAILQ_FIRST(&lun->error_list) != NULL) &&
13516 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS) &&
13517 	    ((io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0))
13518 		ctl_inject_error(lun, io);
13519 
13520 	/*
13521 	 * XXX KDM how do we treat commands that aren't completed
13522 	 * successfully?
13523 	 *
13524 	 * XXX KDM should we also track I/O latency?
13525 	 */
13526 	if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13527 	    io->io_hdr.io_type == CTL_IO_SCSI) {
13528 #ifdef CTL_TIME_IO
13529 		struct bintime cur_bt;
13530 #endif
13531 		int type;
13532 
13533 		if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13534 		    CTL_FLAG_DATA_IN)
13535 			type = CTL_STATS_READ;
13536 		else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13537 		    CTL_FLAG_DATA_OUT)
13538 			type = CTL_STATS_WRITE;
13539 		else
13540 			type = CTL_STATS_NO_IO;
13541 
13542 		lun->stats.ports[targ_port].bytes[type] +=
13543 		    io->scsiio.kern_total_len;
13544 		lun->stats.ports[targ_port].operations[type]++;
13545 #ifdef CTL_TIME_IO
13546 		bintime_add(&lun->stats.ports[targ_port].dma_time[type],
13547 		   &io->io_hdr.dma_bt);
13548 		lun->stats.ports[targ_port].num_dmas[type] +=
13549 		    io->io_hdr.num_dmas;
13550 		getbintime(&cur_bt);
13551 		bintime_sub(&cur_bt, &io->io_hdr.start_bt);
13552 		bintime_add(&lun->stats.ports[targ_port].time[type], &cur_bt);
13553 #endif
13554 	}
13555 
13556 	/*
13557 	 * Remove this from the OOA queue.
13558 	 */
13559 	TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13560 
13561 	/*
13562 	 * Run through the blocked queue on this LUN and see if anything
13563 	 * has become unblocked, now that this transaction is done.
13564 	 */
13565 	ctl_check_blocked(lun);
13566 
13567 	/*
13568 	 * If the LUN has been invalidated, free it if there is nothing
13569 	 * left on its OOA queue.
13570 	 */
13571 	if ((lun->flags & CTL_LUN_INVALID)
13572 	 && TAILQ_EMPTY(&lun->ooa_queue)) {
13573 		mtx_unlock(&lun->lun_lock);
13574 		mtx_lock(&softc->ctl_lock);
13575 		ctl_free_lun(lun);
13576 		mtx_unlock(&softc->ctl_lock);
13577 	} else
13578 		mtx_unlock(&lun->lun_lock);
13579 
13580 bailout:
13581 
13582 	/*
13583 	 * If this command has been aborted, make sure we set the status
13584 	 * properly.  The FETD is responsible for freeing the I/O and doing
13585 	 * whatever it needs to do to clean up its state.
13586 	 */
13587 	if (io->io_hdr.flags & CTL_FLAG_ABORT)
13588 		ctl_set_task_aborted(&io->scsiio);
13589 
13590 	/*
13591 	 * If enabled, print command error status.
13592 	 * We don't print UAs unless debugging was enabled explicitly.
13593 	 */
13594 	do {
13595 		if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)
13596 			break;
13597 		if (!bootverbose && (ctl_debug & CTL_DEBUG_INFO) == 0)
13598 			break;
13599 		if ((ctl_debug & CTL_DEBUG_INFO) == 0 &&
13600 		    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SCSI_ERROR) &&
13601 		     (io->scsiio.scsi_status == SCSI_STATUS_CHECK_COND)) {
13602 			int error_code, sense_key, asc, ascq;
13603 
13604 			scsi_extract_sense_len(&io->scsiio.sense_data,
13605 			    io->scsiio.sense_len, &error_code, &sense_key,
13606 			    &asc, &ascq, /*show_errors*/ 0);
13607 			if (sense_key == SSD_KEY_UNIT_ATTENTION)
13608 				break;
13609 		}
13610 
13611 		ctl_io_error_print(io, NULL);
13612 	} while (0);
13613 
13614 	/*
13615 	 * Tell the FETD or the other shelf controller we're done with this
13616 	 * command.  Note that only SCSI commands get to this point.  Task
13617 	 * management commands are completed above.
13618 	 *
13619 	 * We only send status to the other controller if we're in XFER
13620 	 * mode.  In SER_ONLY mode, the I/O is done on the controller that
13621 	 * received the I/O (from CTL's perspective), and so the status is
13622 	 * generated there.
13623 	 *
13624 	 * XXX KDM if we hold the lock here, we could cause a deadlock
13625 	 * if the frontend comes back in in this context to queue
13626 	 * something.
13627 	 */
13628 	if ((softc->ha_mode == CTL_HA_MODE_XFER)
13629 	 && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
13630 		union ctl_ha_msg msg;
13631 
13632 		memset(&msg, 0, sizeof(msg));
13633 		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13634 		msg.hdr.original_sc = io->io_hdr.original_sc;
13635 		msg.hdr.nexus = io->io_hdr.nexus;
13636 		msg.hdr.status = io->io_hdr.status;
13637 		msg.scsi.scsi_status = io->scsiio.scsi_status;
13638 		msg.scsi.tag_num = io->scsiio.tag_num;
13639 		msg.scsi.tag_type = io->scsiio.tag_type;
13640 		msg.scsi.sense_len = io->scsiio.sense_len;
13641 		msg.scsi.sense_residual = io->scsiio.sense_residual;
13642 		msg.scsi.residual = io->scsiio.residual;
13643 		memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
13644 		       sizeof(io->scsiio.sense_data));
13645 		/*
13646 		 * We copy this whether or not this is an I/O-related
13647 		 * command.  Otherwise, we'd have to go and check to see
13648 		 * whether it's a read/write command, and it really isn't
13649 		 * worth it.
13650 		 */
13651 		memcpy(&msg.scsi.lbalen,
13652 		       &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
13653 		       sizeof(msg.scsi.lbalen));
13654 
13655 		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13656 				sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
13657 			/* XXX do something here */
13658 		}
13659 
13660 		ctl_free_io(io);
13661 	} else
13662 		fe_done(io);
13663 
13664 	return (CTL_RETVAL_COMPLETE);
13665 }
13666 
13667 #ifdef CTL_WITH_CA
13668 /*
13669  * Front end should call this if it doesn't do autosense.  When the request
13670  * sense comes back in from the initiator, we'll dequeue this and send it.
13671  */
13672 int
13673 ctl_queue_sense(union ctl_io *io)
13674 {
13675 	struct ctl_lun *lun;
13676 	struct ctl_softc *softc;
13677 	uint32_t initidx, targ_lun;
13678 
13679 	softc = control_softc;
13680 
13681 	CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13682 
13683 	/*
13684 	 * LUN lookup will likely move to the ctl_work_thread() once we
13685 	 * have our new queueing infrastructure (that doesn't put things on
13686 	 * a per-LUN queue initially).  That is so that we can handle
13687 	 * things like an INQUIRY to a LUN that we don't have enabled.  We
13688 	 * can't deal with that right now.
13689 	 */
13690 	mtx_lock(&softc->ctl_lock);
13691 
13692 	/*
13693 	 * If we don't have a LUN for this, just toss the sense
13694 	 * information.
13695 	 */
13696 	targ_lun = io->io_hdr.nexus.targ_lun;
13697 	targ_lun = ctl_map_lun(softc, io->io_hdr.nexus.targ_port, targ_lun);
13698 	if ((targ_lun < CTL_MAX_LUNS)
13699 	 && (softc->ctl_luns[targ_lun] != NULL))
13700 		lun = softc->ctl_luns[targ_lun];
13701 	else
13702 		goto bailout;
13703 
13704 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
13705 
13706 	mtx_lock(&lun->lun_lock);
13707 	/*
13708 	 * Already have CA set for this LUN...toss the sense information.
13709 	 */
13710 	if (ctl_is_set(lun->have_ca, initidx)) {
13711 		mtx_unlock(&lun->lun_lock);
13712 		goto bailout;
13713 	}
13714 
13715 	memcpy(&lun->pending_sense[initidx], &io->scsiio.sense_data,
13716 	       MIN(sizeof(lun->pending_sense[initidx]),
13717 	       sizeof(io->scsiio.sense_data)));
13718 	ctl_set_mask(lun->have_ca, initidx);
13719 	mtx_unlock(&lun->lun_lock);
13720 
13721 bailout:
13722 	mtx_unlock(&softc->ctl_lock);
13723 
13724 	ctl_free_io(io);
13725 
13726 	return (CTL_RETVAL_COMPLETE);
13727 }
13728 #endif
13729 
13730 /*
13731  * Primary command inlet from frontend ports.  All SCSI and task I/O
13732  * requests must go through this function.
13733  */
13734 int
13735 ctl_queue(union ctl_io *io)
13736 {
13737 
13738 	CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13739 
13740 #ifdef CTL_TIME_IO
13741 	io->io_hdr.start_time = time_uptime;
13742 	getbintime(&io->io_hdr.start_bt);
13743 #endif /* CTL_TIME_IO */
13744 
13745 	/* Map FE-specific LUN ID into global one. */
13746 	io->io_hdr.nexus.targ_mapped_lun =
13747 	    ctl_map_lun(control_softc, io->io_hdr.nexus.targ_port,
13748 	     io->io_hdr.nexus.targ_lun);
13749 
13750 	switch (io->io_hdr.io_type) {
13751 	case CTL_IO_SCSI:
13752 	case CTL_IO_TASK:
13753 		if (ctl_debug & CTL_DEBUG_CDB)
13754 			ctl_io_print(io);
13755 		ctl_enqueue_incoming(io);
13756 		break;
13757 	default:
13758 		printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13759 		return (EINVAL);
13760 	}
13761 
13762 	return (CTL_RETVAL_COMPLETE);
13763 }
13764 
13765 #ifdef CTL_IO_DELAY
13766 static void
13767 ctl_done_timer_wakeup(void *arg)
13768 {
13769 	union ctl_io *io;
13770 
13771 	io = (union ctl_io *)arg;
13772 	ctl_done(io);
13773 }
13774 #endif /* CTL_IO_DELAY */
13775 
13776 void
13777 ctl_done(union ctl_io *io)
13778 {
13779 
13780 	/*
13781 	 * Enable this to catch duplicate completion issues.
13782 	 */
13783 #if 0
13784 	if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13785 		printf("%s: type %d msg %d cdb %x iptl: "
13786 		       "%d:%d:%d:%d tag 0x%04x "
13787 		       "flag %#x status %x\n",
13788 			__func__,
13789 			io->io_hdr.io_type,
13790 			io->io_hdr.msg_type,
13791 			io->scsiio.cdb[0],
13792 			io->io_hdr.nexus.initid.id,
13793 			io->io_hdr.nexus.targ_port,
13794 			io->io_hdr.nexus.targ_target.id,
13795 			io->io_hdr.nexus.targ_lun,
13796 			(io->io_hdr.io_type ==
13797 			CTL_IO_TASK) ?
13798 			io->taskio.tag_num :
13799 			io->scsiio.tag_num,
13800 		        io->io_hdr.flags,
13801 			io->io_hdr.status);
13802 	} else
13803 		io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13804 #endif
13805 
13806 	/*
13807 	 * This is an internal copy of an I/O, and should not go through
13808 	 * the normal done processing logic.
13809 	 */
13810 	if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13811 		return;
13812 
13813 	/*
13814 	 * We need to send a msg to the serializing shelf to finish the IO
13815 	 * as well.  We don't send a finish message to the other shelf if
13816 	 * this is a task management command.  Task management commands
13817 	 * aren't serialized in the OOA queue, but rather just executed on
13818 	 * both shelf controllers for commands that originated on that
13819 	 * controller.
13820 	 */
13821 	if ((io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)
13822 	 && (io->io_hdr.io_type != CTL_IO_TASK)) {
13823 		union ctl_ha_msg msg_io;
13824 
13825 		msg_io.hdr.msg_type = CTL_MSG_FINISH_IO;
13826 		msg_io.hdr.serializing_sc = io->io_hdr.serializing_sc;
13827 		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_io,
13828 		    sizeof(msg_io), 0 ) != CTL_HA_STATUS_SUCCESS) {
13829 		}
13830 		/* continue on to finish IO */
13831 	}
13832 #ifdef CTL_IO_DELAY
13833 	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13834 		struct ctl_lun *lun;
13835 
13836 		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13837 
13838 		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13839 	} else {
13840 		struct ctl_lun *lun;
13841 
13842 		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13843 
13844 		if ((lun != NULL)
13845 		 && (lun->delay_info.done_delay > 0)) {
13846 			struct callout *callout;
13847 
13848 			callout = (struct callout *)&io->io_hdr.timer_bytes;
13849 			callout_init(callout, /*mpsafe*/ 1);
13850 			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
13851 			callout_reset(callout,
13852 				      lun->delay_info.done_delay * hz,
13853 				      ctl_done_timer_wakeup, io);
13854 			if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
13855 				lun->delay_info.done_delay = 0;
13856 			return;
13857 		}
13858 	}
13859 #endif /* CTL_IO_DELAY */
13860 
13861 	ctl_enqueue_done(io);
13862 }
13863 
13864 int
13865 ctl_isc(struct ctl_scsiio *ctsio)
13866 {
13867 	struct ctl_lun *lun;
13868 	int retval;
13869 
13870 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13871 
13872 	CTL_DEBUG_PRINT(("ctl_isc: command: %02x\n", ctsio->cdb[0]));
13873 
13874 	CTL_DEBUG_PRINT(("ctl_isc: calling data_submit()\n"));
13875 
13876 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
13877 
13878 	return (retval);
13879 }
13880 
13881 
13882 static void
13883 ctl_work_thread(void *arg)
13884 {
13885 	struct ctl_thread *thr = (struct ctl_thread *)arg;
13886 	struct ctl_softc *softc = thr->ctl_softc;
13887 	union ctl_io *io;
13888 	int retval;
13889 
13890 	CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
13891 
13892 	for (;;) {
13893 		retval = 0;
13894 
13895 		/*
13896 		 * We handle the queues in this order:
13897 		 * - ISC
13898 		 * - done queue (to free up resources, unblock other commands)
13899 		 * - RtR queue
13900 		 * - incoming queue
13901 		 *
13902 		 * If those queues are empty, we break out of the loop and
13903 		 * go to sleep.
13904 		 */
13905 		mtx_lock(&thr->queue_lock);
13906 		io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
13907 		if (io != NULL) {
13908 			STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
13909 			mtx_unlock(&thr->queue_lock);
13910 			ctl_handle_isc(io);
13911 			continue;
13912 		}
13913 		io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
13914 		if (io != NULL) {
13915 			STAILQ_REMOVE_HEAD(&thr->done_queue, links);
13916 			/* clear any blocked commands, call fe_done */
13917 			mtx_unlock(&thr->queue_lock);
13918 			retval = ctl_process_done(io);
13919 			continue;
13920 		}
13921 		io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
13922 		if (io != NULL) {
13923 			STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
13924 			mtx_unlock(&thr->queue_lock);
13925 			if (io->io_hdr.io_type == CTL_IO_TASK)
13926 				ctl_run_task(io);
13927 			else
13928 				ctl_scsiio_precheck(softc, &io->scsiio);
13929 			continue;
13930 		}
13931 		if (!ctl_pause_rtr) {
13932 			io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
13933 			if (io != NULL) {
13934 				STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
13935 				mtx_unlock(&thr->queue_lock);
13936 				retval = ctl_scsiio(&io->scsiio);
13937 				if (retval != CTL_RETVAL_COMPLETE)
13938 					CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
13939 				continue;
13940 			}
13941 		}
13942 
13943 		/* Sleep until we have something to do. */
13944 		mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
13945 	}
13946 }
13947 
13948 static void
13949 ctl_lun_thread(void *arg)
13950 {
13951 	struct ctl_softc *softc = (struct ctl_softc *)arg;
13952 	struct ctl_be_lun *be_lun;
13953 	int retval;
13954 
13955 	CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
13956 
13957 	for (;;) {
13958 		retval = 0;
13959 		mtx_lock(&softc->ctl_lock);
13960 		be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
13961 		if (be_lun != NULL) {
13962 			STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
13963 			mtx_unlock(&softc->ctl_lock);
13964 			ctl_create_lun(be_lun);
13965 			continue;
13966 		}
13967 
13968 		/* Sleep until we have something to do. */
13969 		mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
13970 		    PDROP | PRIBIO, "-", 0);
13971 	}
13972 }
13973 
13974 static void
13975 ctl_thresh_thread(void *arg)
13976 {
13977 	struct ctl_softc *softc = (struct ctl_softc *)arg;
13978 	struct ctl_lun *lun;
13979 	struct ctl_be_lun *be_lun;
13980 	struct scsi_da_rw_recovery_page *rwpage;
13981 	struct ctl_logical_block_provisioning_page *page;
13982 	const char *attr;
13983 	uint64_t thres, val;
13984 	int i, e;
13985 
13986 	CTL_DEBUG_PRINT(("ctl_thresh_thread starting\n"));
13987 
13988 	for (;;) {
13989 		mtx_lock(&softc->ctl_lock);
13990 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
13991 			be_lun = lun->be_lun;
13992 			if ((lun->flags & CTL_LUN_DISABLED) ||
13993 			    (lun->flags & CTL_LUN_OFFLINE) ||
13994 			    lun->backend->lun_attr == NULL)
13995 				continue;
13996 			rwpage = &lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT];
13997 			if ((rwpage->byte8 & SMS_RWER_LBPERE) == 0)
13998 				continue;
13999 			e = 0;
14000 			page = &lun->mode_pages.lbp_page[CTL_PAGE_CURRENT];
14001 			for (i = 0; i < CTL_NUM_LBP_THRESH; i++) {
14002 				if ((page->descr[i].flags & SLBPPD_ENABLED) == 0)
14003 					continue;
14004 				thres = scsi_4btoul(page->descr[i].count);
14005 				thres <<= CTL_LBP_EXPONENT;
14006 				switch (page->descr[i].resource) {
14007 				case 0x01:
14008 					attr = "blocksavail";
14009 					break;
14010 				case 0x02:
14011 					attr = "blocksused";
14012 					break;
14013 				case 0xf1:
14014 					attr = "poolblocksavail";
14015 					break;
14016 				case 0xf2:
14017 					attr = "poolblocksused";
14018 					break;
14019 				default:
14020 					continue;
14021 				}
14022 				mtx_unlock(&softc->ctl_lock); // XXX
14023 				val = lun->backend->lun_attr(
14024 				    lun->be_lun->be_lun, attr);
14025 				mtx_lock(&softc->ctl_lock);
14026 				if (val == UINT64_MAX)
14027 					continue;
14028 				if ((page->descr[i].flags & SLBPPD_ARMING_MASK)
14029 				    == SLBPPD_ARMING_INC)
14030 					e |= (val >= thres);
14031 				else
14032 					e |= (val <= thres);
14033 			}
14034 			mtx_lock(&lun->lun_lock);
14035 			if (e) {
14036 				if (lun->lasttpt == 0 ||
14037 				    time_uptime - lun->lasttpt >= CTL_LBP_UA_PERIOD) {
14038 					lun->lasttpt = time_uptime;
14039 					ctl_est_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
14040 				}
14041 			} else {
14042 				lun->lasttpt = 0;
14043 				ctl_clr_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
14044 			}
14045 			mtx_unlock(&lun->lun_lock);
14046 		}
14047 		mtx_unlock(&softc->ctl_lock);
14048 		pause("-", CTL_LBP_PERIOD * hz);
14049 	}
14050 }
14051 
14052 static void
14053 ctl_enqueue_incoming(union ctl_io *io)
14054 {
14055 	struct ctl_softc *softc = control_softc;
14056 	struct ctl_thread *thr;
14057 	u_int idx;
14058 
14059 	idx = (io->io_hdr.nexus.targ_port * 127 +
14060 	       io->io_hdr.nexus.initid.id) % worker_threads;
14061 	thr = &softc->threads[idx];
14062 	mtx_lock(&thr->queue_lock);
14063 	STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
14064 	mtx_unlock(&thr->queue_lock);
14065 	wakeup(thr);
14066 }
14067 
14068 static void
14069 ctl_enqueue_rtr(union ctl_io *io)
14070 {
14071 	struct ctl_softc *softc = control_softc;
14072 	struct ctl_thread *thr;
14073 
14074 	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14075 	mtx_lock(&thr->queue_lock);
14076 	STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
14077 	mtx_unlock(&thr->queue_lock);
14078 	wakeup(thr);
14079 }
14080 
14081 static void
14082 ctl_enqueue_done(union ctl_io *io)
14083 {
14084 	struct ctl_softc *softc = control_softc;
14085 	struct ctl_thread *thr;
14086 
14087 	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14088 	mtx_lock(&thr->queue_lock);
14089 	STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
14090 	mtx_unlock(&thr->queue_lock);
14091 	wakeup(thr);
14092 }
14093 
14094 static void
14095 ctl_enqueue_isc(union ctl_io *io)
14096 {
14097 	struct ctl_softc *softc = control_softc;
14098 	struct ctl_thread *thr;
14099 
14100 	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14101 	mtx_lock(&thr->queue_lock);
14102 	STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
14103 	mtx_unlock(&thr->queue_lock);
14104 	wakeup(thr);
14105 }
14106 
14107 /* Initialization and failover */
14108 
14109 void
14110 ctl_init_isc_msg(void)
14111 {
14112 	printf("CTL: Still calling this thing\n");
14113 }
14114 
14115 /*
14116  * Init component
14117  * 	Initializes component into configuration defined by bootMode
14118  *	(see hasc-sv.c)
14119  *  	returns hasc_Status:
14120  * 		OK
14121  *		ERROR - fatal error
14122  */
14123 static ctl_ha_comp_status
14124 ctl_isc_init(struct ctl_ha_component *c)
14125 {
14126 	ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14127 
14128 	c->status = ret;
14129 	return ret;
14130 }
14131 
14132 /* Start component
14133  * 	Starts component in state requested. If component starts successfully,
14134  *	it must set its own state to the requestrd state
14135  *	When requested state is HASC_STATE_HA, the component may refine it
14136  * 	by adding _SLAVE or _MASTER flags.
14137  *	Currently allowed state transitions are:
14138  *	UNKNOWN->HA		- initial startup
14139  *	UNKNOWN->SINGLE - initial startup when no parter detected
14140  *	HA->SINGLE		- failover
14141  * returns ctl_ha_comp_status:
14142  * 		OK	- component successfully started in requested state
14143  *		FAILED  - could not start the requested state, failover may
14144  * 			  be possible
14145  *		ERROR	- fatal error detected, no future startup possible
14146  */
14147 static ctl_ha_comp_status
14148 ctl_isc_start(struct ctl_ha_component *c, ctl_ha_state state)
14149 {
14150 	ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14151 
14152 	printf("%s: go\n", __func__);
14153 
14154 	// UNKNOWN->HA or UNKNOWN->SINGLE (bootstrap)
14155 	if (c->state == CTL_HA_STATE_UNKNOWN ) {
14156 		control_softc->is_single = 0;
14157 		if (ctl_ha_msg_create(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
14158 		    != CTL_HA_STATUS_SUCCESS) {
14159 			printf("ctl_isc_start: ctl_ha_msg_create failed.\n");
14160 			ret = CTL_HA_COMP_STATUS_ERROR;
14161 		}
14162 	} else if (CTL_HA_STATE_IS_HA(c->state)
14163 		&& CTL_HA_STATE_IS_SINGLE(state)){
14164 		// HA->SINGLE transition
14165 	        ctl_failover();
14166 		control_softc->is_single = 1;
14167 	} else {
14168 		printf("ctl_isc_start:Invalid state transition %X->%X\n",
14169 		       c->state, state);
14170 		ret = CTL_HA_COMP_STATUS_ERROR;
14171 	}
14172 	if (CTL_HA_STATE_IS_SINGLE(state))
14173 		control_softc->is_single = 1;
14174 
14175 	c->state = state;
14176 	c->status = ret;
14177 	return ret;
14178 }
14179 
14180 /*
14181  * Quiesce component
14182  * The component must clear any error conditions (set status to OK) and
14183  * prepare itself to another Start call
14184  * returns ctl_ha_comp_status:
14185  * 	OK
14186  *	ERROR
14187  */
14188 static ctl_ha_comp_status
14189 ctl_isc_quiesce(struct ctl_ha_component *c)
14190 {
14191 	int ret = CTL_HA_COMP_STATUS_OK;
14192 
14193 	ctl_pause_rtr = 1;
14194 	c->status = ret;
14195 	return ret;
14196 }
14197 
14198 struct ctl_ha_component ctl_ha_component_ctlisc =
14199 {
14200 	.name = "CTL ISC",
14201 	.state = CTL_HA_STATE_UNKNOWN,
14202 	.init = ctl_isc_init,
14203 	.start = ctl_isc_start,
14204 	.quiesce = ctl_isc_quiesce
14205 };
14206 
14207 /*
14208  *  vim: ts=8
14209  */
14210