xref: /freebsd/sys/cam/ctl/ctl.c (revision 5ca8e32633c4ffbbcd6762e5888b6a4ba0708c6c)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2003-2009 Silicon Graphics International Corp.
5  * Copyright (c) 2012 The FreeBSD Foundation
6  * Copyright (c) 2014-2017 Alexander Motin <mav@FreeBSD.org>
7  * Copyright (c) 2017 Jakub Wojciech Klama <jceel@FreeBSD.org>
8  * Copyright (c) 2018 Marcelo Araujo <araujo@FreeBSD.org>
9  * All rights reserved.
10  *
11  * Portions of this software were developed by Edward Tomasz Napierala
12  * under sponsorship from the FreeBSD Foundation.
13  *
14  * Redistribution and use in source and binary forms, with or without
15  * modification, are permitted provided that the following conditions
16  * are met:
17  * 1. Redistributions of source code must retain the above copyright
18  *    notice, this list of conditions, and the following disclaimer,
19  *    without modification.
20  * 2. Redistributions in binary form must reproduce at minimum a disclaimer
21  *    substantially similar to the "NO WARRANTY" disclaimer below
22  *    ("Disclaimer") and any redistribution must be conditioned upon
23  *    including a substantially similar Disclaimer requirement for further
24  *    binary redistribution.
25  *
26  * NO WARRANTY
27  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
28  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
29  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
30  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
31  * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
32  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
33  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
34  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
35  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
36  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
37  * POSSIBILITY OF SUCH DAMAGES.
38  *
39  * $Id$
40  */
41 /*
42  * CAM Target Layer, a SCSI device emulation subsystem.
43  *
44  * Author: Ken Merry <ken@FreeBSD.org>
45  */
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/proc.h>
67 #include <sys/sched.h>
68 #include <sys/sysctl.h>
69 #include <sys/nv.h>
70 #include <sys/dnv.h>
71 #include <vm/uma.h>
72 
73 #include <cam/cam.h>
74 #include <cam/scsi/scsi_all.h>
75 #include <cam/scsi/scsi_cd.h>
76 #include <cam/scsi/scsi_da.h>
77 #include <cam/ctl/ctl_io.h>
78 #include <cam/ctl/ctl.h>
79 #include <cam/ctl/ctl_frontend.h>
80 #include <cam/ctl/ctl_util.h>
81 #include <cam/ctl/ctl_backend.h>
82 #include <cam/ctl/ctl_ioctl.h>
83 #include <cam/ctl/ctl_ha.h>
84 #include <cam/ctl/ctl_private.h>
85 #include <cam/ctl/ctl_debug.h>
86 #include <cam/ctl/ctl_scsi_all.h>
87 #include <cam/ctl/ctl_error.h>
88 
89 struct ctl_softc *control_softc = NULL;
90 
91 /*
92  * Template mode pages.
93  */
94 
95 /*
96  * Note that these are default values only.  The actual values will be
97  * filled in when the user does a mode sense.
98  */
99 const static struct scsi_da_rw_recovery_page rw_er_page_default = {
100 	/*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
101 	/*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
102 	/*byte3*/SMS_RWER_AWRE|SMS_RWER_ARRE,
103 	/*read_retry_count*/0,
104 	/*correction_span*/0,
105 	/*head_offset_count*/0,
106 	/*data_strobe_offset_cnt*/0,
107 	/*byte8*/SMS_RWER_LBPERE,
108 	/*write_retry_count*/0,
109 	/*reserved2*/0,
110 	/*recovery_time_limit*/{0, 0},
111 };
112 
113 const static struct scsi_da_rw_recovery_page rw_er_page_changeable = {
114 	/*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
115 	/*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
116 	/*byte3*/SMS_RWER_PER,
117 	/*read_retry_count*/0,
118 	/*correction_span*/0,
119 	/*head_offset_count*/0,
120 	/*data_strobe_offset_cnt*/0,
121 	/*byte8*/SMS_RWER_LBPERE,
122 	/*write_retry_count*/0,
123 	/*reserved2*/0,
124 	/*recovery_time_limit*/{0, 0},
125 };
126 
127 const static struct scsi_da_verify_recovery_page verify_er_page_default = {
128 	/*page_code*/SMS_VERIFY_ERROR_RECOVERY_PAGE,
129 	/*page_length*/sizeof(struct scsi_da_verify_recovery_page) - 2,
130 	/*byte3*/0,
131 	/*read_retry_count*/0,
132 	/*reserved*/{ 0, 0, 0, 0, 0, 0 },
133 	/*recovery_time_limit*/{0, 0},
134 };
135 
136 const static struct scsi_da_verify_recovery_page verify_er_page_changeable = {
137 	/*page_code*/SMS_VERIFY_ERROR_RECOVERY_PAGE,
138 	/*page_length*/sizeof(struct scsi_da_verify_recovery_page) - 2,
139 	/*byte3*/SMS_VER_PER,
140 	/*read_retry_count*/0,
141 	/*reserved*/{ 0, 0, 0, 0, 0, 0 },
142 	/*recovery_time_limit*/{0, 0},
143 };
144 
145 const static struct scsi_caching_page caching_page_default = {
146 	/*page_code*/SMS_CACHING_PAGE,
147 	/*page_length*/sizeof(struct scsi_caching_page) - 2,
148 	/*flags1*/ SCP_DISC | SCP_WCE,
149 	/*ret_priority*/ 0,
150 	/*disable_pf_transfer_len*/ {0xff, 0xff},
151 	/*min_prefetch*/ {0, 0},
152 	/*max_prefetch*/ {0xff, 0xff},
153 	/*max_pf_ceiling*/ {0xff, 0xff},
154 	/*flags2*/ 0,
155 	/*cache_segments*/ 0,
156 	/*cache_seg_size*/ {0, 0},
157 	/*reserved*/ 0,
158 	/*non_cache_seg_size*/ {0, 0, 0}
159 };
160 
161 const static struct scsi_caching_page caching_page_changeable = {
162 	/*page_code*/SMS_CACHING_PAGE,
163 	/*page_length*/sizeof(struct scsi_caching_page) - 2,
164 	/*flags1*/ SCP_WCE | SCP_RCD,
165 	/*ret_priority*/ 0,
166 	/*disable_pf_transfer_len*/ {0, 0},
167 	/*min_prefetch*/ {0, 0},
168 	/*max_prefetch*/ {0, 0},
169 	/*max_pf_ceiling*/ {0, 0},
170 	/*flags2*/ 0,
171 	/*cache_segments*/ 0,
172 	/*cache_seg_size*/ {0, 0},
173 	/*reserved*/ 0,
174 	/*non_cache_seg_size*/ {0, 0, 0}
175 };
176 
177 const static struct scsi_control_page control_page_default = {
178 	/*page_code*/SMS_CONTROL_MODE_PAGE,
179 	/*page_length*/sizeof(struct scsi_control_page) - 2,
180 	/*rlec*/0,
181 	/*queue_flags*/SCP_QUEUE_ALG_RESTRICTED,
182 	/*eca_and_aen*/0,
183 	/*flags4*/SCP_TAS,
184 	/*aen_holdoff_period*/{0, 0},
185 	/*busy_timeout_period*/{0, 0},
186 	/*extended_selftest_completion_time*/{0, 0}
187 };
188 
189 const static struct scsi_control_page control_page_changeable = {
190 	/*page_code*/SMS_CONTROL_MODE_PAGE,
191 	/*page_length*/sizeof(struct scsi_control_page) - 2,
192 	/*rlec*/SCP_DSENSE,
193 	/*queue_flags*/SCP_QUEUE_ALG_MASK | SCP_NUAR,
194 	/*eca_and_aen*/SCP_SWP,
195 	/*flags4*/0,
196 	/*aen_holdoff_period*/{0, 0},
197 	/*busy_timeout_period*/{0, 0},
198 	/*extended_selftest_completion_time*/{0, 0}
199 };
200 
201 #define CTL_CEM_LEN	(sizeof(struct scsi_control_ext_page) - 4)
202 
203 const static struct scsi_control_ext_page control_ext_page_default = {
204 	/*page_code*/SMS_CONTROL_MODE_PAGE | SMPH_SPF,
205 	/*subpage_code*/0x01,
206 	/*page_length*/{CTL_CEM_LEN >> 8, CTL_CEM_LEN},
207 	/*flags*/0,
208 	/*prio*/0,
209 	/*max_sense*/0
210 };
211 
212 const static struct scsi_control_ext_page control_ext_page_changeable = {
213 	/*page_code*/SMS_CONTROL_MODE_PAGE | SMPH_SPF,
214 	/*subpage_code*/0x01,
215 	/*page_length*/{CTL_CEM_LEN >> 8, CTL_CEM_LEN},
216 	/*flags*/0,
217 	/*prio*/0,
218 	/*max_sense*/0xff
219 };
220 
221 const static struct scsi_info_exceptions_page ie_page_default = {
222 	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
223 	/*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
224 	/*info_flags*/SIEP_FLAGS_EWASC,
225 	/*mrie*/SIEP_MRIE_NO,
226 	/*interval_timer*/{0, 0, 0, 0},
227 	/*report_count*/{0, 0, 0, 1}
228 };
229 
230 const static struct scsi_info_exceptions_page ie_page_changeable = {
231 	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
232 	/*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
233 	/*info_flags*/SIEP_FLAGS_EWASC | SIEP_FLAGS_DEXCPT | SIEP_FLAGS_TEST |
234 	    SIEP_FLAGS_LOGERR,
235 	/*mrie*/0x0f,
236 	/*interval_timer*/{0xff, 0xff, 0xff, 0xff},
237 	/*report_count*/{0xff, 0xff, 0xff, 0xff}
238 };
239 
240 #define CTL_LBPM_LEN	(sizeof(struct ctl_logical_block_provisioning_page) - 4)
241 
242 const static struct ctl_logical_block_provisioning_page lbp_page_default = {{
243 	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
244 	/*subpage_code*/0x02,
245 	/*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
246 	/*flags*/0,
247 	/*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
248 	/*descr*/{}},
249 	{{/*flags*/0,
250 	  /*resource*/0x01,
251 	  /*reserved*/{0, 0},
252 	  /*count*/{0, 0, 0, 0}},
253 	 {/*flags*/0,
254 	  /*resource*/0x02,
255 	  /*reserved*/{0, 0},
256 	  /*count*/{0, 0, 0, 0}},
257 	 {/*flags*/0,
258 	  /*resource*/0xf1,
259 	  /*reserved*/{0, 0},
260 	  /*count*/{0, 0, 0, 0}},
261 	 {/*flags*/0,
262 	  /*resource*/0xf2,
263 	  /*reserved*/{0, 0},
264 	  /*count*/{0, 0, 0, 0}}
265 	}
266 };
267 
268 const static struct ctl_logical_block_provisioning_page lbp_page_changeable = {{
269 	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
270 	/*subpage_code*/0x02,
271 	/*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
272 	/*flags*/SLBPP_SITUA,
273 	/*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
274 	/*descr*/{}},
275 	{{/*flags*/0,
276 	  /*resource*/0,
277 	  /*reserved*/{0, 0},
278 	  /*count*/{0, 0, 0, 0}},
279 	 {/*flags*/0,
280 	  /*resource*/0,
281 	  /*reserved*/{0, 0},
282 	  /*count*/{0, 0, 0, 0}},
283 	 {/*flags*/0,
284 	  /*resource*/0,
285 	  /*reserved*/{0, 0},
286 	  /*count*/{0, 0, 0, 0}},
287 	 {/*flags*/0,
288 	  /*resource*/0,
289 	  /*reserved*/{0, 0},
290 	  /*count*/{0, 0, 0, 0}}
291 	}
292 };
293 
294 const static struct scsi_cddvd_capabilities_page cddvd_page_default = {
295 	/*page_code*/SMS_CDDVD_CAPS_PAGE,
296 	/*page_length*/sizeof(struct scsi_cddvd_capabilities_page) - 2,
297 	/*caps1*/0x3f,
298 	/*caps2*/0x00,
299 	/*caps3*/0xf0,
300 	/*caps4*/0x00,
301 	/*caps5*/0x29,
302 	/*caps6*/0x00,
303 	/*obsolete*/{0, 0},
304 	/*nvol_levels*/{0, 0},
305 	/*buffer_size*/{8, 0},
306 	/*obsolete2*/{0, 0},
307 	/*reserved*/0,
308 	/*digital*/0,
309 	/*obsolete3*/0,
310 	/*copy_management*/0,
311 	/*reserved2*/0,
312 	/*rotation_control*/0,
313 	/*cur_write_speed*/0,
314 	/*num_speed_descr*/0,
315 };
316 
317 const static struct scsi_cddvd_capabilities_page cddvd_page_changeable = {
318 	/*page_code*/SMS_CDDVD_CAPS_PAGE,
319 	/*page_length*/sizeof(struct scsi_cddvd_capabilities_page) - 2,
320 	/*caps1*/0,
321 	/*caps2*/0,
322 	/*caps3*/0,
323 	/*caps4*/0,
324 	/*caps5*/0,
325 	/*caps6*/0,
326 	/*obsolete*/{0, 0},
327 	/*nvol_levels*/{0, 0},
328 	/*buffer_size*/{0, 0},
329 	/*obsolete2*/{0, 0},
330 	/*reserved*/0,
331 	/*digital*/0,
332 	/*obsolete3*/0,
333 	/*copy_management*/0,
334 	/*reserved2*/0,
335 	/*rotation_control*/0,
336 	/*cur_write_speed*/0,
337 	/*num_speed_descr*/0,
338 };
339 
340 SYSCTL_NODE(_kern_cam, OID_AUTO, ctl, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
341     "CAM Target Layer");
342 static int worker_threads = -1;
343 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, worker_threads, CTLFLAG_RDTUN,
344     &worker_threads, 1, "Number of worker threads");
345 static int ctl_debug = CTL_DEBUG_NONE;
346 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, debug, CTLFLAG_RWTUN,
347     &ctl_debug, 0, "Enabled debug flags");
348 static int ctl_lun_map_size = 1024;
349 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, lun_map_size, CTLFLAG_RWTUN,
350     &ctl_lun_map_size, 0, "Size of per-port LUN map (max LUN + 1)");
351 #ifdef  CTL_TIME_IO
352 static int ctl_time_io_secs = CTL_TIME_IO_DEFAULT_SECS;
353 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, time_io_secs, CTLFLAG_RWTUN,
354     &ctl_time_io_secs, 0, "Log requests taking more seconds");
355 #endif
356 
357 /*
358  * Maximum number of LUNs we support.  MUST be a power of 2.
359  */
360 #define	CTL_DEFAULT_MAX_LUNS	1024
361 static int ctl_max_luns = CTL_DEFAULT_MAX_LUNS;
362 TUNABLE_INT("kern.cam.ctl.max_luns", &ctl_max_luns);
363 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, max_luns, CTLFLAG_RDTUN,
364     &ctl_max_luns, CTL_DEFAULT_MAX_LUNS, "Maximum number of LUNs");
365 
366 /*
367  * Maximum number of ports registered at one time.
368  */
369 #define	CTL_DEFAULT_MAX_PORTS		1024
370 static int ctl_max_ports = CTL_DEFAULT_MAX_PORTS;
371 TUNABLE_INT("kern.cam.ctl.max_ports", &ctl_max_ports);
372 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, max_ports, CTLFLAG_RDTUN,
373     &ctl_max_ports, CTL_DEFAULT_MAX_LUNS, "Maximum number of ports");
374 
375 /*
376  * Maximum number of initiators we support.
377  */
378 #define	CTL_MAX_INITIATORS	(CTL_MAX_INIT_PER_PORT * ctl_max_ports)
379 
380 /*
381  * Supported pages (0x00), Serial number (0x80), Device ID (0x83),
382  * Extended INQUIRY Data (0x86), Mode Page Policy (0x87),
383  * SCSI Ports (0x88), Third-party Copy (0x8F), SCSI Feature Sets (0x92),
384  * Block limits (0xB0), Block Device Characteristics (0xB1) and
385  * Logical Block Provisioning (0xB2)
386  */
387 #define SCSI_EVPD_NUM_SUPPORTED_PAGES	11
388 
389 static void ctl_isc_event_handler(ctl_ha_channel chanel, ctl_ha_event event,
390 				  int param);
391 static void ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest);
392 static void ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest);
393 static int ctl_init(void);
394 static int ctl_shutdown(void);
395 static int ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td);
396 static int ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td);
397 static void ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio);
398 static void ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
399 			      struct ctl_ooa *ooa_hdr,
400 			      struct ctl_ooa_entry *kern_entries);
401 static int ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
402 		     struct thread *td);
403 static int ctl_enable_lun(struct ctl_lun *lun);
404 static int ctl_disable_lun(struct ctl_lun *lun);
405 static int ctl_free_lun(struct ctl_lun *lun);
406 
407 static int ctl_do_mode_select(union ctl_io *io);
408 static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
409 			   uint64_t res_key, uint64_t sa_res_key,
410 			   uint8_t type, uint32_t residx,
411 			   struct ctl_scsiio *ctsio,
412 			   struct scsi_per_res_out *cdb,
413 			   struct scsi_per_res_out_parms* param);
414 static void ctl_pro_preempt_other(struct ctl_lun *lun,
415 				  union ctl_ha_msg *msg);
416 static void ctl_hndl_per_res_out_on_other_sc(union ctl_io *io);
417 static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
418 static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
419 static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
420 static int ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len);
421 static int ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len);
422 static int ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio,
423 					 int alloc_len);
424 static int ctl_inquiry_evpd_sfs(struct ctl_scsiio *ctsio, int alloc_len);
425 static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
426 					 int alloc_len);
427 static int ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len);
428 static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
429 static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
430 static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
431 static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len);
432 static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2,
433     bool seq);
434 static ctl_action ctl_seq_check(union ctl_io *io1, union ctl_io *io2);
435 static ctl_action ctl_check_for_blockage(struct ctl_lun *lun,
436     union ctl_io *pending_io, const uint8_t *serialize_row,
437     union ctl_io *ooa_io);
438 static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
439 				union ctl_io **starting_io);
440 static void ctl_try_unblock_io(struct ctl_lun *lun, union ctl_io *io,
441     bool skip);
442 static void ctl_try_unblock_others(struct ctl_lun *lun, union ctl_io *io,
443     bool skip);
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 void ctl_failover_lun(union ctl_io *io);
448 static void ctl_scsiio_precheck(struct ctl_scsiio *ctsio);
449 static int ctl_scsiio(struct ctl_scsiio *ctsio);
450 
451 static int ctl_target_reset(union ctl_io *io);
452 static void ctl_do_lun_reset(struct ctl_lun *lun, uint32_t initidx,
453 			 ctl_ua_type ua_type);
454 static int ctl_lun_reset(union ctl_io *io);
455 static int ctl_abort_task(union ctl_io *io);
456 static int ctl_abort_task_set(union ctl_io *io);
457 static int ctl_query_task(union ctl_io *io, int task_set);
458 static void ctl_i_t_nexus_loss(struct ctl_softc *softc, uint32_t initidx,
459 			      ctl_ua_type ua_type);
460 static int ctl_i_t_nexus_reset(union ctl_io *io);
461 static int ctl_query_async_event(union ctl_io *io);
462 static void ctl_run_task(union ctl_io *io);
463 #ifdef CTL_IO_DELAY
464 static void ctl_datamove_timer_wakeup(void *arg);
465 static void ctl_done_timer_wakeup(void *arg);
466 #endif /* CTL_IO_DELAY */
467 
468 static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
469 static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
470 static int ctl_datamove_remote_dm_write_cb(union ctl_io *io, bool samethr);
471 static void ctl_datamove_remote_write(union ctl_io *io);
472 static int ctl_datamove_remote_dm_read_cb(union ctl_io *io, bool samethr);
473 static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
474 static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
475 static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
476 				    ctl_ha_dt_cb callback);
477 static void ctl_datamove_remote_read(union ctl_io *io);
478 static void ctl_datamove_remote(union ctl_io *io);
479 static void ctl_process_done(union ctl_io *io);
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 static int ctl_ha_init(void);
493 static int ctl_ha_shutdown(void);
494 
495 static uint64_t ctl_get_prkey(struct ctl_lun *lun, uint32_t residx);
496 static void ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx);
497 static void ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx);
498 static void ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key);
499 
500 /*
501  * Load the serialization table.  This isn't very pretty, but is probably
502  * the easiest way to do it.
503  */
504 #include "ctl_ser_table.c"
505 
506 /*
507  * We only need to define open, close and ioctl routines for this driver.
508  */
509 static struct cdevsw ctl_cdevsw = {
510 	.d_version =	D_VERSION,
511 	.d_flags =	0,
512 	.d_open =	ctl_open,
513 	.d_close =	ctl_close,
514 	.d_ioctl =	ctl_ioctl,
515 	.d_name =	"ctl",
516 };
517 
518 MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
519 
520 static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
521 
522 static moduledata_t ctl_moduledata = {
523 	"ctl",
524 	ctl_module_event_handler,
525 	NULL
526 };
527 
528 DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
529 MODULE_VERSION(ctl, 1);
530 
531 static struct ctl_frontend ha_frontend =
532 {
533 	.name = "ha",
534 	.init = ctl_ha_init,
535 	.shutdown = ctl_ha_shutdown,
536 };
537 
538 static int
539 ctl_ha_init(void)
540 {
541 	struct ctl_softc *softc = control_softc;
542 
543 	if (ctl_pool_create(softc, "othersc", CTL_POOL_ENTRIES_OTHER_SC,
544 	                    &softc->othersc_pool) != 0)
545 		return (ENOMEM);
546 	if (ctl_ha_msg_init(softc) != CTL_HA_STATUS_SUCCESS) {
547 		ctl_pool_free(softc->othersc_pool);
548 		return (EIO);
549 	}
550 	if (ctl_ha_msg_register(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
551 	    != CTL_HA_STATUS_SUCCESS) {
552 		ctl_ha_msg_destroy(softc);
553 		ctl_pool_free(softc->othersc_pool);
554 		return (EIO);
555 	}
556 	return (0);
557 };
558 
559 static int
560 ctl_ha_shutdown(void)
561 {
562 	struct ctl_softc *softc = control_softc;
563 	struct ctl_port *port;
564 
565 	ctl_ha_msg_shutdown(softc);
566 	if (ctl_ha_msg_deregister(CTL_HA_CHAN_CTL) != CTL_HA_STATUS_SUCCESS)
567 		return (EIO);
568 	if (ctl_ha_msg_destroy(softc) != CTL_HA_STATUS_SUCCESS)
569 		return (EIO);
570 	ctl_pool_free(softc->othersc_pool);
571 	while ((port = STAILQ_FIRST(&ha_frontend.port_list)) != NULL) {
572 		ctl_port_deregister(port);
573 		free(port->port_name, M_CTL);
574 		free(port, M_CTL);
575 	}
576 	return (0);
577 };
578 
579 static void
580 ctl_ha_datamove(union ctl_io *io)
581 {
582 	struct ctl_lun *lun = CTL_LUN(io);
583 	struct ctl_sg_entry *sgl;
584 	union ctl_ha_msg msg;
585 	uint32_t sg_entries_sent;
586 	int do_sg_copy, i, j;
587 
588 	memset(&msg.dt, 0, sizeof(msg.dt));
589 	msg.hdr.msg_type = CTL_MSG_DATAMOVE;
590 	msg.hdr.original_sc = io->io_hdr.remote_io;
591 	msg.hdr.serializing_sc = io;
592 	msg.hdr.nexus = io->io_hdr.nexus;
593 	msg.hdr.status = io->io_hdr.status;
594 	msg.dt.flags = io->io_hdr.flags;
595 
596 	/*
597 	 * We convert everything into a S/G list here.  We can't
598 	 * pass by reference, only by value between controllers.
599 	 * So we can't pass a pointer to the S/G list, only as many
600 	 * S/G entries as we can fit in here.  If it's possible for
601 	 * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
602 	 * then we need to break this up into multiple transfers.
603 	 */
604 	if (io->scsiio.kern_sg_entries == 0) {
605 		msg.dt.kern_sg_entries = 1;
606 #if 0
607 		if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
608 			msg.dt.sg_list[0].addr = io->scsiio.kern_data_ptr;
609 		} else {
610 			/* XXX KDM use busdma here! */
611 			msg.dt.sg_list[0].addr =
612 			    (void *)vtophys(io->scsiio.kern_data_ptr);
613 		}
614 #else
615 		KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
616 		    ("HA does not support BUS_ADDR"));
617 		msg.dt.sg_list[0].addr = io->scsiio.kern_data_ptr;
618 #endif
619 		msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
620 		do_sg_copy = 0;
621 	} else {
622 		msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
623 		do_sg_copy = 1;
624 	}
625 
626 	msg.dt.kern_data_len = io->scsiio.kern_data_len;
627 	msg.dt.kern_total_len = io->scsiio.kern_total_len;
628 	msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
629 	msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
630 	msg.dt.sg_sequence = 0;
631 
632 	/*
633 	 * Loop until we've sent all of the S/G entries.  On the
634 	 * other end, we'll recompose these S/G entries into one
635 	 * contiguous list before processing.
636 	 */
637 	for (sg_entries_sent = 0; sg_entries_sent < msg.dt.kern_sg_entries;
638 	    msg.dt.sg_sequence++) {
639 		msg.dt.cur_sg_entries = MIN((sizeof(msg.dt.sg_list) /
640 		    sizeof(msg.dt.sg_list[0])),
641 		    msg.dt.kern_sg_entries - sg_entries_sent);
642 		if (do_sg_copy != 0) {
643 			sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
644 			for (i = sg_entries_sent, j = 0;
645 			     i < msg.dt.cur_sg_entries; i++, j++) {
646 #if 0
647 				if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
648 					msg.dt.sg_list[j].addr = sgl[i].addr;
649 				} else {
650 					/* XXX KDM use busdma here! */
651 					msg.dt.sg_list[j].addr =
652 					    (void *)vtophys(sgl[i].addr);
653 				}
654 #else
655 				KASSERT((io->io_hdr.flags &
656 				    CTL_FLAG_BUS_ADDR) == 0,
657 				    ("HA does not support BUS_ADDR"));
658 				msg.dt.sg_list[j].addr = sgl[i].addr;
659 #endif
660 				msg.dt.sg_list[j].len = sgl[i].len;
661 			}
662 		}
663 
664 		sg_entries_sent += msg.dt.cur_sg_entries;
665 		msg.dt.sg_last = (sg_entries_sent >= msg.dt.kern_sg_entries);
666 		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
667 		    sizeof(msg.dt) - sizeof(msg.dt.sg_list) +
668 		    sizeof(struct ctl_sg_entry) * msg.dt.cur_sg_entries,
669 		    M_WAITOK) > CTL_HA_STATUS_SUCCESS) {
670 			io->io_hdr.port_status = 31341;
671 			ctl_datamove_done(io, true);
672 			return;
673 		}
674 		msg.dt.sent_sg_entries = sg_entries_sent;
675 	}
676 
677 	/*
678 	 * Officially handover the request from us to peer.
679 	 * If failover has just happened, then we must return error.
680 	 * If failover happen just after, then it is not our problem.
681 	 */
682 	if (lun)
683 		mtx_lock(&lun->lun_lock);
684 	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
685 		if (lun)
686 			mtx_unlock(&lun->lun_lock);
687 		io->io_hdr.port_status = 31342;
688 		ctl_datamove_done(io, true);
689 		return;
690 	}
691 	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
692 	io->io_hdr.flags |= CTL_FLAG_DMA_INPROG;
693 	if (lun)
694 		mtx_unlock(&lun->lun_lock);
695 }
696 
697 static void
698 ctl_ha_done(union ctl_io *io)
699 {
700 	union ctl_ha_msg msg;
701 
702 	if (io->io_hdr.io_type == CTL_IO_SCSI) {
703 		memset(&msg, 0, sizeof(msg));
704 		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
705 		msg.hdr.original_sc = io->io_hdr.remote_io;
706 		msg.hdr.nexus = io->io_hdr.nexus;
707 		msg.hdr.status = io->io_hdr.status;
708 		msg.scsi.scsi_status = io->scsiio.scsi_status;
709 		msg.scsi.tag_num = io->scsiio.tag_num;
710 		msg.scsi.tag_type = io->scsiio.tag_type;
711 		msg.scsi.sense_len = io->scsiio.sense_len;
712 		memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
713 		    io->scsiio.sense_len);
714 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
715 		    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
716 		    msg.scsi.sense_len, M_WAITOK);
717 	}
718 	ctl_free_io(io);
719 }
720 
721 static void
722 ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
723 			    union ctl_ha_msg *msg_info)
724 {
725 	struct ctl_scsiio *ctsio;
726 
727 	if (msg_info->hdr.original_sc == NULL) {
728 		printf("%s: original_sc == NULL!\n", __func__);
729 		/* XXX KDM now what? */
730 		return;
731 	}
732 
733 	ctsio = &msg_info->hdr.original_sc->scsiio;
734 	ctsio->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
735 	ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
736 	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
737 	ctsio->io_hdr.status = msg_info->hdr.status;
738 	ctsio->scsi_status = msg_info->scsi.scsi_status;
739 	ctsio->sense_len = msg_info->scsi.sense_len;
740 	memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
741 	       msg_info->scsi.sense_len);
742 	ctl_enqueue_isc((union ctl_io *)ctsio);
743 }
744 
745 static void
746 ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
747 				union ctl_ha_msg *msg_info)
748 {
749 	struct ctl_scsiio *ctsio;
750 
751 	if (msg_info->hdr.serializing_sc == NULL) {
752 		printf("%s: serializing_sc == NULL!\n", __func__);
753 		/* XXX KDM now what? */
754 		return;
755 	}
756 
757 	ctsio = &msg_info->hdr.serializing_sc->scsiio;
758 	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
759 	ctl_enqueue_isc((union ctl_io *)ctsio);
760 }
761 
762 void
763 ctl_isc_announce_lun(struct ctl_lun *lun)
764 {
765 	struct ctl_softc *softc = lun->ctl_softc;
766 	union ctl_ha_msg *msg;
767 	struct ctl_ha_msg_lun_pr_key pr_key;
768 	int i, k;
769 
770 	if (softc->ha_link != CTL_HA_LINK_ONLINE)
771 		return;
772 	mtx_lock(&lun->lun_lock);
773 	i = sizeof(msg->lun);
774 	if (lun->lun_devid)
775 		i += lun->lun_devid->len;
776 	i += sizeof(pr_key) * lun->pr_key_count;
777 alloc:
778 	mtx_unlock(&lun->lun_lock);
779 	msg = malloc(i, M_CTL, M_WAITOK);
780 	mtx_lock(&lun->lun_lock);
781 	k = sizeof(msg->lun);
782 	if (lun->lun_devid)
783 		k += lun->lun_devid->len;
784 	k += sizeof(pr_key) * lun->pr_key_count;
785 	if (i < k) {
786 		free(msg, M_CTL);
787 		i = k;
788 		goto alloc;
789 	}
790 	bzero(&msg->lun, sizeof(msg->lun));
791 	msg->hdr.msg_type = CTL_MSG_LUN_SYNC;
792 	msg->hdr.nexus.targ_lun = lun->lun;
793 	msg->hdr.nexus.targ_mapped_lun = lun->lun;
794 	msg->lun.flags = lun->flags;
795 	msg->lun.pr_generation = lun->pr_generation;
796 	msg->lun.pr_res_idx = lun->pr_res_idx;
797 	msg->lun.pr_res_type = lun->pr_res_type;
798 	msg->lun.pr_key_count = lun->pr_key_count;
799 	i = 0;
800 	if (lun->lun_devid) {
801 		msg->lun.lun_devid_len = lun->lun_devid->len;
802 		memcpy(&msg->lun.data[i], lun->lun_devid->data,
803 		    msg->lun.lun_devid_len);
804 		i += msg->lun.lun_devid_len;
805 	}
806 	for (k = 0; k < CTL_MAX_INITIATORS; k++) {
807 		if ((pr_key.pr_key = ctl_get_prkey(lun, k)) == 0)
808 			continue;
809 		pr_key.pr_iid = k;
810 		memcpy(&msg->lun.data[i], &pr_key, sizeof(pr_key));
811 		i += sizeof(pr_key);
812 	}
813 	mtx_unlock(&lun->lun_lock);
814 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->lun, sizeof(msg->lun) + i,
815 	    M_WAITOK);
816 	free(msg, M_CTL);
817 
818 	if (lun->flags & CTL_LUN_PRIMARY_SC) {
819 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
820 			ctl_isc_announce_mode(lun, -1,
821 			    lun->mode_pages.index[i].page_code & SMPH_PC_MASK,
822 			    lun->mode_pages.index[i].subpage);
823 		}
824 	}
825 }
826 
827 void
828 ctl_isc_announce_port(struct ctl_port *port)
829 {
830 	struct ctl_softc *softc = port->ctl_softc;
831 	union ctl_ha_msg *msg;
832 	int i;
833 
834 	if (port->targ_port < softc->port_min ||
835 	    port->targ_port >= softc->port_max ||
836 	    softc->ha_link != CTL_HA_LINK_ONLINE)
837 		return;
838 	i = sizeof(msg->port) + strlen(port->port_name) + 1;
839 	if (port->lun_map)
840 		i += port->lun_map_size * sizeof(uint32_t);
841 	if (port->port_devid)
842 		i += port->port_devid->len;
843 	if (port->target_devid)
844 		i += port->target_devid->len;
845 	if (port->init_devid)
846 		i += port->init_devid->len;
847 	msg = malloc(i, M_CTL, M_WAITOK);
848 	bzero(&msg->port, sizeof(msg->port));
849 	msg->hdr.msg_type = CTL_MSG_PORT_SYNC;
850 	msg->hdr.nexus.targ_port = port->targ_port;
851 	msg->port.port_type = port->port_type;
852 	msg->port.physical_port = port->physical_port;
853 	msg->port.virtual_port = port->virtual_port;
854 	msg->port.status = port->status;
855 	i = 0;
856 	msg->port.name_len = sprintf(&msg->port.data[i],
857 	    "%d:%s", softc->ha_id, port->port_name) + 1;
858 	i += msg->port.name_len;
859 	if (port->lun_map) {
860 		msg->port.lun_map_len = port->lun_map_size * sizeof(uint32_t);
861 		memcpy(&msg->port.data[i], port->lun_map,
862 		    msg->port.lun_map_len);
863 		i += msg->port.lun_map_len;
864 	}
865 	if (port->port_devid) {
866 		msg->port.port_devid_len = port->port_devid->len;
867 		memcpy(&msg->port.data[i], port->port_devid->data,
868 		    msg->port.port_devid_len);
869 		i += msg->port.port_devid_len;
870 	}
871 	if (port->target_devid) {
872 		msg->port.target_devid_len = port->target_devid->len;
873 		memcpy(&msg->port.data[i], port->target_devid->data,
874 		    msg->port.target_devid_len);
875 		i += msg->port.target_devid_len;
876 	}
877 	if (port->init_devid) {
878 		msg->port.init_devid_len = port->init_devid->len;
879 		memcpy(&msg->port.data[i], port->init_devid->data,
880 		    msg->port.init_devid_len);
881 		i += msg->port.init_devid_len;
882 	}
883 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->port, sizeof(msg->port) + i,
884 	    M_WAITOK);
885 	free(msg, M_CTL);
886 }
887 
888 void
889 ctl_isc_announce_iid(struct ctl_port *port, int iid)
890 {
891 	struct ctl_softc *softc = port->ctl_softc;
892 	union ctl_ha_msg *msg;
893 	int i, l;
894 
895 	if (port->targ_port < softc->port_min ||
896 	    port->targ_port >= softc->port_max ||
897 	    softc->ha_link != CTL_HA_LINK_ONLINE)
898 		return;
899 	mtx_lock(&softc->ctl_lock);
900 	i = sizeof(msg->iid);
901 	l = 0;
902 	if (port->wwpn_iid[iid].name)
903 		l = strlen(port->wwpn_iid[iid].name) + 1;
904 	i += l;
905 	msg = malloc(i, M_CTL, M_NOWAIT);
906 	if (msg == NULL) {
907 		mtx_unlock(&softc->ctl_lock);
908 		return;
909 	}
910 	bzero(&msg->iid, sizeof(msg->iid));
911 	msg->hdr.msg_type = CTL_MSG_IID_SYNC;
912 	msg->hdr.nexus.targ_port = port->targ_port;
913 	msg->hdr.nexus.initid = iid;
914 	msg->iid.in_use = port->wwpn_iid[iid].in_use;
915 	msg->iid.name_len = l;
916 	msg->iid.wwpn = port->wwpn_iid[iid].wwpn;
917 	if (port->wwpn_iid[iid].name)
918 		strlcpy(msg->iid.data, port->wwpn_iid[iid].name, l);
919 	mtx_unlock(&softc->ctl_lock);
920 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->iid, i, M_NOWAIT);
921 	free(msg, M_CTL);
922 }
923 
924 void
925 ctl_isc_announce_mode(struct ctl_lun *lun, uint32_t initidx,
926     uint8_t page, uint8_t subpage)
927 {
928 	struct ctl_softc *softc = lun->ctl_softc;
929 	union ctl_ha_msg *msg;
930 	u_int i, l;
931 
932 	if (softc->ha_link != CTL_HA_LINK_ONLINE)
933 		return;
934 	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
935 		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) ==
936 		    page && lun->mode_pages.index[i].subpage == subpage)
937 			break;
938 	}
939 	if (i == CTL_NUM_MODE_PAGES)
940 		return;
941 
942 	/* Don't try to replicate pages not present on this device. */
943 	if (lun->mode_pages.index[i].page_data == NULL)
944 		return;
945 
946 	l = sizeof(msg->mode) + lun->mode_pages.index[i].page_len;
947 	msg = malloc(l, M_CTL, M_WAITOK | M_ZERO);
948 	msg->hdr.msg_type = CTL_MSG_MODE_SYNC;
949 	msg->hdr.nexus.targ_port = initidx / CTL_MAX_INIT_PER_PORT;
950 	msg->hdr.nexus.initid = initidx % CTL_MAX_INIT_PER_PORT;
951 	msg->hdr.nexus.targ_lun = lun->lun;
952 	msg->hdr.nexus.targ_mapped_lun = lun->lun;
953 	msg->mode.page_code = page;
954 	msg->mode.subpage = subpage;
955 	msg->mode.page_len = lun->mode_pages.index[i].page_len;
956 	memcpy(msg->mode.data, lun->mode_pages.index[i].page_data,
957 	    msg->mode.page_len);
958 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->mode, l, M_WAITOK);
959 	free(msg, M_CTL);
960 }
961 
962 static void
963 ctl_isc_ha_link_up(struct ctl_softc *softc)
964 {
965 	struct ctl_port *port;
966 	struct ctl_lun *lun;
967 	union ctl_ha_msg msg;
968 	int i;
969 
970 	/* Announce this node parameters to peer for validation. */
971 	msg.login.msg_type = CTL_MSG_LOGIN;
972 	msg.login.version = CTL_HA_VERSION;
973 	msg.login.ha_mode = softc->ha_mode;
974 	msg.login.ha_id = softc->ha_id;
975 	msg.login.max_luns = ctl_max_luns;
976 	msg.login.max_ports = ctl_max_ports;
977 	msg.login.max_init_per_port = CTL_MAX_INIT_PER_PORT;
978 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg.login, sizeof(msg.login),
979 	    M_WAITOK);
980 
981 	STAILQ_FOREACH(port, &softc->port_list, links) {
982 		ctl_isc_announce_port(port);
983 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
984 			if (port->wwpn_iid[i].in_use)
985 				ctl_isc_announce_iid(port, i);
986 		}
987 	}
988 	STAILQ_FOREACH(lun, &softc->lun_list, links)
989 		ctl_isc_announce_lun(lun);
990 }
991 
992 static void
993 ctl_isc_ha_link_down(struct ctl_softc *softc)
994 {
995 	struct ctl_port *port;
996 	struct ctl_lun *lun;
997 	union ctl_io *io;
998 	int i;
999 
1000 	mtx_lock(&softc->ctl_lock);
1001 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
1002 		mtx_lock(&lun->lun_lock);
1003 		if (lun->flags & CTL_LUN_PEER_SC_PRIMARY) {
1004 			lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
1005 			ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
1006 		}
1007 		mtx_unlock(&lun->lun_lock);
1008 
1009 		mtx_unlock(&softc->ctl_lock);
1010 		io = ctl_alloc_io(softc->othersc_pool);
1011 		mtx_lock(&softc->ctl_lock);
1012 		ctl_zero_io(io);
1013 		io->io_hdr.msg_type = CTL_MSG_FAILOVER;
1014 		io->io_hdr.nexus.targ_mapped_lun = lun->lun;
1015 		ctl_enqueue_isc(io);
1016 	}
1017 
1018 	STAILQ_FOREACH(port, &softc->port_list, links) {
1019 		if (port->targ_port >= softc->port_min &&
1020 		    port->targ_port < softc->port_max)
1021 			continue;
1022 		port->status &= ~CTL_PORT_STATUS_ONLINE;
1023 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1024 			port->wwpn_iid[i].in_use = 0;
1025 			free(port->wwpn_iid[i].name, M_CTL);
1026 			port->wwpn_iid[i].name = NULL;
1027 		}
1028 	}
1029 	mtx_unlock(&softc->ctl_lock);
1030 }
1031 
1032 static void
1033 ctl_isc_ua(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1034 {
1035 	struct ctl_lun *lun;
1036 	uint32_t iid;
1037 
1038 	if (len < sizeof(msg->ua)) {
1039 		printf("%s: Received truncated message %d < %zu\n",
1040 		    __func__, len, sizeof(msg->ua));
1041 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1042 		return;
1043 	}
1044 
1045 	mtx_lock(&softc->ctl_lock);
1046 	if (msg->hdr.nexus.targ_mapped_lun >= ctl_max_luns ||
1047 	    (lun = softc->ctl_luns[msg->hdr.nexus.targ_mapped_lun]) == NULL) {
1048 		mtx_unlock(&softc->ctl_lock);
1049 		return;
1050 	}
1051 	mtx_lock(&lun->lun_lock);
1052 	mtx_unlock(&softc->ctl_lock);
1053 	if (msg->ua.ua_type == CTL_UA_THIN_PROV_THRES && msg->ua.ua_set)
1054 		memcpy(lun->ua_tpt_info, msg->ua.ua_info, 8);
1055 	iid = ctl_get_initindex(&msg->hdr.nexus);
1056 	if (msg->ua.ua_all) {
1057 		if (msg->ua.ua_set)
1058 			ctl_est_ua_all(lun, iid, msg->ua.ua_type);
1059 		else
1060 			ctl_clr_ua_all(lun, iid, msg->ua.ua_type);
1061 	} else {
1062 		if (msg->ua.ua_set)
1063 			ctl_est_ua(lun, iid, msg->ua.ua_type);
1064 		else
1065 			ctl_clr_ua(lun, iid, msg->ua.ua_type);
1066 	}
1067 	mtx_unlock(&lun->lun_lock);
1068 }
1069 
1070 static void
1071 ctl_isc_lun_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1072 {
1073 	struct ctl_lun *lun;
1074 	struct ctl_ha_msg_lun_pr_key pr_key;
1075 	int i, k;
1076 	ctl_lun_flags oflags;
1077 	uint32_t targ_lun;
1078 
1079 	if (len < offsetof(struct ctl_ha_msg_lun, data[0])) {
1080 		printf("%s: Received truncated message %d < %zu\n",
1081 		    __func__, len, offsetof(struct ctl_ha_msg_lun, data[0]));
1082 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1083 		return;
1084 	}
1085 	i = msg->lun.lun_devid_len + msg->lun.pr_key_count * sizeof(pr_key);
1086 	if (len < offsetof(struct ctl_ha_msg_lun, data[i])) {
1087 		printf("%s: Received truncated message data %d < %zu\n",
1088 		    __func__, len, offsetof(struct ctl_ha_msg_lun, data[i]));
1089 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1090 		return;
1091 	}
1092 
1093 	targ_lun = msg->hdr.nexus.targ_mapped_lun;
1094 	mtx_lock(&softc->ctl_lock);
1095 	if (targ_lun >= ctl_max_luns ||
1096 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
1097 		mtx_unlock(&softc->ctl_lock);
1098 		return;
1099 	}
1100 	mtx_lock(&lun->lun_lock);
1101 	mtx_unlock(&softc->ctl_lock);
1102 	if (lun->flags & CTL_LUN_DISABLED) {
1103 		mtx_unlock(&lun->lun_lock);
1104 		return;
1105 	}
1106 	i = (lun->lun_devid != NULL) ? lun->lun_devid->len : 0;
1107 	if (msg->lun.lun_devid_len != i || (i > 0 &&
1108 	    memcmp(&msg->lun.data[0], lun->lun_devid->data, i) != 0)) {
1109 		mtx_unlock(&lun->lun_lock);
1110 		printf("%s: Received conflicting HA LUN %d\n",
1111 		    __func__, targ_lun);
1112 		return;
1113 	} else {
1114 		/* Record whether peer is primary. */
1115 		oflags = lun->flags;
1116 		if ((msg->lun.flags & CTL_LUN_PRIMARY_SC) &&
1117 		    (msg->lun.flags & CTL_LUN_DISABLED) == 0)
1118 			lun->flags |= CTL_LUN_PEER_SC_PRIMARY;
1119 		else
1120 			lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
1121 		if (oflags != lun->flags)
1122 			ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
1123 
1124 		/* If peer is primary and we are not -- use data */
1125 		if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
1126 		    (lun->flags & CTL_LUN_PEER_SC_PRIMARY)) {
1127 			lun->pr_generation = msg->lun.pr_generation;
1128 			lun->pr_res_idx = msg->lun.pr_res_idx;
1129 			lun->pr_res_type = msg->lun.pr_res_type;
1130 			lun->pr_key_count = msg->lun.pr_key_count;
1131 			for (k = 0; k < CTL_MAX_INITIATORS; k++)
1132 				ctl_clr_prkey(lun, k);
1133 			for (k = 0; k < msg->lun.pr_key_count; k++) {
1134 				memcpy(&pr_key, &msg->lun.data[i],
1135 				    sizeof(pr_key));
1136 				ctl_alloc_prkey(lun, pr_key.pr_iid);
1137 				ctl_set_prkey(lun, pr_key.pr_iid,
1138 				    pr_key.pr_key);
1139 				i += sizeof(pr_key);
1140 			}
1141 		}
1142 
1143 		mtx_unlock(&lun->lun_lock);
1144 		CTL_DEBUG_PRINT(("%s: Known LUN %d, peer is %s\n",
1145 		    __func__, targ_lun,
1146 		    (msg->lun.flags & CTL_LUN_PRIMARY_SC) ?
1147 		    "primary" : "secondary"));
1148 
1149 		/* If we are primary but peer doesn't know -- notify */
1150 		if ((lun->flags & CTL_LUN_PRIMARY_SC) &&
1151 		    (msg->lun.flags & CTL_LUN_PEER_SC_PRIMARY) == 0)
1152 			ctl_isc_announce_lun(lun);
1153 	}
1154 }
1155 
1156 static void
1157 ctl_isc_port_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1158 {
1159 	struct ctl_port *port;
1160 	struct ctl_lun *lun;
1161 	int i, new;
1162 
1163 	if (len < offsetof(struct ctl_ha_msg_port, data[0])) {
1164 		printf("%s: Received truncated message %d < %zu\n",
1165 		    __func__, len, offsetof(struct ctl_ha_msg_port, data[0]));
1166 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1167 		return;
1168 	}
1169 	i = msg->port.name_len + msg->port.lun_map_len +
1170 	    msg->port.port_devid_len + msg->port.target_devid_len +
1171 	    msg->port.init_devid_len;
1172 	if (len < offsetof(struct ctl_ha_msg_port, data[i])) {
1173 		printf("%s: Received truncated message data %d < %zu\n",
1174 		    __func__, len, offsetof(struct ctl_ha_msg_port, data[i]));
1175 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1176 		return;
1177 	}
1178 
1179 	port = softc->ctl_ports[msg->hdr.nexus.targ_port];
1180 	if (port == NULL) {
1181 		CTL_DEBUG_PRINT(("%s: New port %d\n", __func__,
1182 		    msg->hdr.nexus.targ_port));
1183 		new = 1;
1184 		port = malloc(sizeof(*port), M_CTL, M_WAITOK | M_ZERO);
1185 		port->frontend = &ha_frontend;
1186 		port->targ_port = msg->hdr.nexus.targ_port;
1187 		port->fe_datamove = ctl_ha_datamove;
1188 		port->fe_done = ctl_ha_done;
1189 	} else if (port->frontend == &ha_frontend) {
1190 		CTL_DEBUG_PRINT(("%s: Updated port %d\n", __func__,
1191 		    msg->hdr.nexus.targ_port));
1192 		new = 0;
1193 	} else {
1194 		printf("%s: Received conflicting HA port %d\n",
1195 		    __func__, msg->hdr.nexus.targ_port);
1196 		return;
1197 	}
1198 	port->port_type = msg->port.port_type;
1199 	port->physical_port = msg->port.physical_port;
1200 	port->virtual_port = msg->port.virtual_port;
1201 	port->status = msg->port.status;
1202 	i = 0;
1203 	free(port->port_name, M_CTL);
1204 	port->port_name = strndup(&msg->port.data[i], msg->port.name_len,
1205 	    M_CTL);
1206 	i += msg->port.name_len;
1207 	if (msg->port.lun_map_len != 0) {
1208 		if (port->lun_map == NULL ||
1209 		    port->lun_map_size * sizeof(uint32_t) <
1210 		    msg->port.lun_map_len) {
1211 			port->lun_map_size = 0;
1212 			free(port->lun_map, M_CTL);
1213 			port->lun_map = malloc(msg->port.lun_map_len,
1214 			    M_CTL, M_WAITOK);
1215 		}
1216 		memcpy(port->lun_map, &msg->port.data[i], msg->port.lun_map_len);
1217 		port->lun_map_size = msg->port.lun_map_len / sizeof(uint32_t);
1218 		i += msg->port.lun_map_len;
1219 	} else {
1220 		port->lun_map_size = 0;
1221 		free(port->lun_map, M_CTL);
1222 		port->lun_map = NULL;
1223 	}
1224 	if (msg->port.port_devid_len != 0) {
1225 		if (port->port_devid == NULL ||
1226 		    port->port_devid->len < msg->port.port_devid_len) {
1227 			free(port->port_devid, M_CTL);
1228 			port->port_devid = malloc(sizeof(struct ctl_devid) +
1229 			    msg->port.port_devid_len, M_CTL, M_WAITOK);
1230 		}
1231 		memcpy(port->port_devid->data, &msg->port.data[i],
1232 		    msg->port.port_devid_len);
1233 		port->port_devid->len = msg->port.port_devid_len;
1234 		i += msg->port.port_devid_len;
1235 	} else {
1236 		free(port->port_devid, M_CTL);
1237 		port->port_devid = NULL;
1238 	}
1239 	if (msg->port.target_devid_len != 0) {
1240 		if (port->target_devid == NULL ||
1241 		    port->target_devid->len < msg->port.target_devid_len) {
1242 			free(port->target_devid, M_CTL);
1243 			port->target_devid = malloc(sizeof(struct ctl_devid) +
1244 			    msg->port.target_devid_len, M_CTL, M_WAITOK);
1245 		}
1246 		memcpy(port->target_devid->data, &msg->port.data[i],
1247 		    msg->port.target_devid_len);
1248 		port->target_devid->len = msg->port.target_devid_len;
1249 		i += msg->port.target_devid_len;
1250 	} else {
1251 		free(port->target_devid, M_CTL);
1252 		port->target_devid = NULL;
1253 	}
1254 	if (msg->port.init_devid_len != 0) {
1255 		if (port->init_devid == NULL ||
1256 		    port->init_devid->len < msg->port.init_devid_len) {
1257 			free(port->init_devid, M_CTL);
1258 			port->init_devid = malloc(sizeof(struct ctl_devid) +
1259 			    msg->port.init_devid_len, M_CTL, M_WAITOK);
1260 		}
1261 		memcpy(port->init_devid->data, &msg->port.data[i],
1262 		    msg->port.init_devid_len);
1263 		port->init_devid->len = msg->port.init_devid_len;
1264 		i += msg->port.init_devid_len;
1265 	} else {
1266 		free(port->init_devid, M_CTL);
1267 		port->init_devid = NULL;
1268 	}
1269 	if (new) {
1270 		if (ctl_port_register(port) != 0) {
1271 			printf("%s: ctl_port_register() failed with error\n",
1272 			    __func__);
1273 		}
1274 	}
1275 	mtx_lock(&softc->ctl_lock);
1276 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
1277 		if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
1278 			continue;
1279 		mtx_lock(&lun->lun_lock);
1280 		ctl_est_ua_all(lun, -1, CTL_UA_INQ_CHANGE);
1281 		mtx_unlock(&lun->lun_lock);
1282 	}
1283 	mtx_unlock(&softc->ctl_lock);
1284 }
1285 
1286 static void
1287 ctl_isc_iid_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1288 {
1289 	struct ctl_port *port;
1290 	int i, iid;
1291 
1292 	if (len < offsetof(struct ctl_ha_msg_iid, data[0])) {
1293 		printf("%s: Received truncated message %d < %zu\n",
1294 		    __func__, len, offsetof(struct ctl_ha_msg_iid, data[0]));
1295 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1296 		return;
1297 	}
1298 	i = msg->iid.name_len;
1299 	if (len < offsetof(struct ctl_ha_msg_iid, data[i])) {
1300 		printf("%s: Received truncated message data %d < %zu\n",
1301 		    __func__, len, offsetof(struct ctl_ha_msg_iid, data[i]));
1302 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1303 		return;
1304 	}
1305 
1306 	port = softc->ctl_ports[msg->hdr.nexus.targ_port];
1307 	if (port == NULL) {
1308 		printf("%s: Received IID for unknown port %d\n",
1309 		    __func__, msg->hdr.nexus.targ_port);
1310 		return;
1311 	}
1312 	iid = msg->hdr.nexus.initid;
1313 	if (port->wwpn_iid[iid].in_use != 0 &&
1314 	    msg->iid.in_use == 0)
1315 		ctl_i_t_nexus_loss(softc, iid, CTL_UA_POWERON);
1316 	port->wwpn_iid[iid].in_use = msg->iid.in_use;
1317 	port->wwpn_iid[iid].wwpn = msg->iid.wwpn;
1318 	free(port->wwpn_iid[iid].name, M_CTL);
1319 	if (msg->iid.name_len) {
1320 		port->wwpn_iid[iid].name = strndup(&msg->iid.data[0],
1321 		    msg->iid.name_len, M_CTL);
1322 	} else
1323 		port->wwpn_iid[iid].name = NULL;
1324 }
1325 
1326 static void
1327 ctl_isc_login(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1328 {
1329 
1330 	if (len < sizeof(msg->login)) {
1331 		printf("%s: Received truncated message %d < %zu\n",
1332 		    __func__, len, sizeof(msg->login));
1333 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1334 		return;
1335 	}
1336 
1337 	if (msg->login.version != CTL_HA_VERSION) {
1338 		printf("CTL HA peers have different versions %d != %d\n",
1339 		    msg->login.version, CTL_HA_VERSION);
1340 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1341 		return;
1342 	}
1343 	if (msg->login.ha_mode != softc->ha_mode) {
1344 		printf("CTL HA peers have different ha_mode %d != %d\n",
1345 		    msg->login.ha_mode, softc->ha_mode);
1346 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1347 		return;
1348 	}
1349 	if (msg->login.ha_id == softc->ha_id) {
1350 		printf("CTL HA peers have same ha_id %d\n", msg->login.ha_id);
1351 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1352 		return;
1353 	}
1354 	if (msg->login.max_luns != ctl_max_luns ||
1355 	    msg->login.max_ports != ctl_max_ports ||
1356 	    msg->login.max_init_per_port != CTL_MAX_INIT_PER_PORT) {
1357 		printf("CTL HA peers have different limits\n");
1358 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1359 		return;
1360 	}
1361 }
1362 
1363 static void
1364 ctl_isc_mode_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1365 {
1366 	struct ctl_lun *lun;
1367 	u_int i;
1368 	uint32_t initidx, targ_lun;
1369 
1370 	if (len < offsetof(struct ctl_ha_msg_mode, data[0])) {
1371 		printf("%s: Received truncated message %d < %zu\n",
1372 		    __func__, len, offsetof(struct ctl_ha_msg_mode, data[0]));
1373 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1374 		return;
1375 	}
1376 	i = msg->mode.page_len;
1377 	if (len < offsetof(struct ctl_ha_msg_mode, data[i])) {
1378 		printf("%s: Received truncated message data %d < %zu\n",
1379 		    __func__, len, offsetof(struct ctl_ha_msg_mode, data[i]));
1380 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1381 		return;
1382 	}
1383 
1384 	targ_lun = msg->hdr.nexus.targ_mapped_lun;
1385 	mtx_lock(&softc->ctl_lock);
1386 	if (targ_lun >= ctl_max_luns ||
1387 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
1388 		mtx_unlock(&softc->ctl_lock);
1389 		return;
1390 	}
1391 	mtx_lock(&lun->lun_lock);
1392 	mtx_unlock(&softc->ctl_lock);
1393 	if (lun->flags & CTL_LUN_DISABLED) {
1394 		mtx_unlock(&lun->lun_lock);
1395 		return;
1396 	}
1397 	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
1398 		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) ==
1399 		    msg->mode.page_code &&
1400 		    lun->mode_pages.index[i].subpage == msg->mode.subpage)
1401 			break;
1402 	}
1403 	if (i == CTL_NUM_MODE_PAGES) {
1404 		mtx_unlock(&lun->lun_lock);
1405 		return;
1406 	}
1407 	memcpy(lun->mode_pages.index[i].page_data, msg->mode.data,
1408 	    min(lun->mode_pages.index[i].page_len, msg->mode.page_len));
1409 	initidx = ctl_get_initindex(&msg->hdr.nexus);
1410 	if (initidx != -1)
1411 		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
1412 	mtx_unlock(&lun->lun_lock);
1413 }
1414 
1415 /*
1416  * ISC (Inter Shelf Communication) event handler.  Events from the HA
1417  * subsystem come in here.
1418  */
1419 static void
1420 ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
1421 {
1422 	struct ctl_softc *softc = control_softc;
1423 	union ctl_io *io;
1424 	struct ctl_prio *presio;
1425 	ctl_ha_status isc_status;
1426 
1427 	CTL_DEBUG_PRINT(("CTL: Isc Msg event %d\n", event));
1428 	if (event == CTL_HA_EVT_MSG_RECV) {
1429 		union ctl_ha_msg *msg, msgbuf;
1430 
1431 		if (param > sizeof(msgbuf))
1432 			msg = malloc(param, M_CTL, M_WAITOK);
1433 		else
1434 			msg = &msgbuf;
1435 		isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, msg, param,
1436 		    M_WAITOK);
1437 		if (isc_status != CTL_HA_STATUS_SUCCESS) {
1438 			printf("%s: Error receiving message: %d\n",
1439 			    __func__, isc_status);
1440 			if (msg != &msgbuf)
1441 				free(msg, M_CTL);
1442 			return;
1443 		}
1444 
1445 		CTL_DEBUG_PRINT(("CTL: msg_type %d len %d\n",
1446 		    msg->hdr.msg_type, param));
1447 		switch (msg->hdr.msg_type) {
1448 		case CTL_MSG_SERIALIZE:
1449 			io = ctl_alloc_io(softc->othersc_pool);
1450 			ctl_zero_io(io);
1451 			// populate ctsio from msg
1452 			io->io_hdr.io_type = CTL_IO_SCSI;
1453 			io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
1454 			io->io_hdr.remote_io = msg->hdr.original_sc;
1455 			io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
1456 					    CTL_FLAG_IO_ACTIVE;
1457 			/*
1458 			 * If we're in serialization-only mode, we don't
1459 			 * want to go through full done processing.  Thus
1460 			 * the COPY flag.
1461 			 *
1462 			 * XXX KDM add another flag that is more specific.
1463 			 */
1464 			if (softc->ha_mode != CTL_HA_MODE_XFER)
1465 				io->io_hdr.flags |= CTL_FLAG_INT_COPY;
1466 			io->io_hdr.nexus = msg->hdr.nexus;
1467 			io->scsiio.priority = msg->scsi.priority;
1468 			io->scsiio.tag_num = msg->scsi.tag_num;
1469 			io->scsiio.tag_type = msg->scsi.tag_type;
1470 #ifdef CTL_TIME_IO
1471 			io->io_hdr.start_time = time_uptime;
1472 			getbinuptime(&io->io_hdr.start_bt);
1473 #endif /* CTL_TIME_IO */
1474 			io->scsiio.cdb_len = msg->scsi.cdb_len;
1475 			memcpy(io->scsiio.cdb, msg->scsi.cdb,
1476 			       CTL_MAX_CDBLEN);
1477 			if (softc->ha_mode == CTL_HA_MODE_XFER) {
1478 				const struct ctl_cmd_entry *entry;
1479 
1480 				entry = ctl_get_cmd_entry(&io->scsiio, NULL);
1481 				io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
1482 				io->io_hdr.flags |=
1483 					entry->flags & CTL_FLAG_DATA_MASK;
1484 			}
1485 			ctl_enqueue_isc(io);
1486 			break;
1487 
1488 		/* Performed on the Originating SC, XFER mode only */
1489 		case CTL_MSG_DATAMOVE: {
1490 			struct ctl_sg_entry *sgl;
1491 			int i, j;
1492 
1493 			io = msg->hdr.original_sc;
1494 			if (io == NULL) {
1495 				printf("%s: original_sc == NULL!\n", __func__);
1496 				/* XXX KDM do something here */
1497 				break;
1498 			}
1499 			io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
1500 			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1501 			/*
1502 			 * Keep track of this, we need to send it back over
1503 			 * when the datamove is complete.
1504 			 */
1505 			io->io_hdr.remote_io = msg->hdr.serializing_sc;
1506 			if (msg->hdr.status == CTL_SUCCESS)
1507 				io->io_hdr.status = msg->hdr.status;
1508 
1509 			if (msg->dt.sg_sequence == 0) {
1510 #ifdef CTL_TIME_IO
1511 				getbinuptime(&io->io_hdr.dma_start_bt);
1512 #endif
1513 				i = msg->dt.kern_sg_entries +
1514 				    msg->dt.kern_data_len /
1515 				    CTL_HA_DATAMOVE_SEGMENT + 1;
1516 				sgl = malloc(sizeof(*sgl) * i, M_CTL,
1517 				    M_WAITOK | M_ZERO);
1518 				CTL_RSGL(io) = sgl;
1519 				CTL_LSGL(io) = &sgl[msg->dt.kern_sg_entries];
1520 
1521 				io->scsiio.kern_data_ptr = (uint8_t *)sgl;
1522 
1523 				io->scsiio.kern_sg_entries =
1524 					msg->dt.kern_sg_entries;
1525 				io->scsiio.rem_sg_entries =
1526 					msg->dt.kern_sg_entries;
1527 				io->scsiio.kern_data_len =
1528 					msg->dt.kern_data_len;
1529 				io->scsiio.kern_total_len =
1530 					msg->dt.kern_total_len;
1531 				io->scsiio.kern_data_resid =
1532 					msg->dt.kern_data_resid;
1533 				io->scsiio.kern_rel_offset =
1534 					msg->dt.kern_rel_offset;
1535 				io->io_hdr.flags &= ~CTL_FLAG_BUS_ADDR;
1536 				io->io_hdr.flags |= msg->dt.flags &
1537 				    CTL_FLAG_BUS_ADDR;
1538 			} else
1539 				sgl = (struct ctl_sg_entry *)
1540 					io->scsiio.kern_data_ptr;
1541 
1542 			for (i = msg->dt.sent_sg_entries, j = 0;
1543 			     i < (msg->dt.sent_sg_entries +
1544 			     msg->dt.cur_sg_entries); i++, j++) {
1545 				sgl[i].addr = msg->dt.sg_list[j].addr;
1546 				sgl[i].len = msg->dt.sg_list[j].len;
1547 			}
1548 
1549 			/*
1550 			 * If this is the last piece of the I/O, we've got
1551 			 * the full S/G list.  Queue processing in the thread.
1552 			 * Otherwise wait for the next piece.
1553 			 */
1554 			if (msg->dt.sg_last != 0)
1555 				ctl_enqueue_isc(io);
1556 			break;
1557 		}
1558 		/* Performed on the Serializing (primary) SC, XFER mode only */
1559 		case CTL_MSG_DATAMOVE_DONE: {
1560 			if (msg->hdr.serializing_sc == NULL) {
1561 				printf("%s: serializing_sc == NULL!\n",
1562 				       __func__);
1563 				/* XXX KDM now what? */
1564 				break;
1565 			}
1566 			/*
1567 			 * We grab the sense information here in case
1568 			 * there was a failure, so we can return status
1569 			 * back to the initiator.
1570 			 */
1571 			io = msg->hdr.serializing_sc;
1572 			io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
1573 			io->io_hdr.flags &= ~CTL_FLAG_DMA_INPROG;
1574 			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1575 			io->io_hdr.port_status = msg->scsi.port_status;
1576 			io->scsiio.kern_data_resid = msg->scsi.kern_data_resid;
1577 			if (msg->hdr.status != CTL_STATUS_NONE) {
1578 				io->io_hdr.status = msg->hdr.status;
1579 				io->scsiio.scsi_status = msg->scsi.scsi_status;
1580 				io->scsiio.sense_len = msg->scsi.sense_len;
1581 				memcpy(&io->scsiio.sense_data,
1582 				    &msg->scsi.sense_data,
1583 				    msg->scsi.sense_len);
1584 				if (msg->hdr.status == CTL_SUCCESS)
1585 					io->io_hdr.flags |= CTL_FLAG_STATUS_SENT;
1586 			}
1587 			ctl_enqueue_isc(io);
1588 			break;
1589 		}
1590 
1591 		/* Preformed on Originating SC, SER_ONLY mode */
1592 		case CTL_MSG_R2R:
1593 			io = msg->hdr.original_sc;
1594 			if (io == NULL) {
1595 				printf("%s: original_sc == NULL!\n",
1596 				    __func__);
1597 				break;
1598 			}
1599 			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1600 			io->io_hdr.msg_type = CTL_MSG_R2R;
1601 			io->io_hdr.remote_io = msg->hdr.serializing_sc;
1602 			ctl_enqueue_isc(io);
1603 			break;
1604 
1605 		/*
1606 		 * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
1607 		 * mode.
1608 		 * Performed on the Originating (i.e. secondary) SC in XFER
1609 		 * mode
1610 		 */
1611 		case CTL_MSG_FINISH_IO:
1612 			if (softc->ha_mode == CTL_HA_MODE_XFER)
1613 				ctl_isc_handler_finish_xfer(softc, msg);
1614 			else
1615 				ctl_isc_handler_finish_ser_only(softc, msg);
1616 			break;
1617 
1618 		/* Preformed on Originating SC */
1619 		case CTL_MSG_BAD_JUJU:
1620 			io = msg->hdr.original_sc;
1621 			if (io == NULL) {
1622 				printf("%s: Bad JUJU!, original_sc is NULL!\n",
1623 				       __func__);
1624 				break;
1625 			}
1626 			ctl_copy_sense_data(msg, io);
1627 			/*
1628 			 * IO should have already been cleaned up on other
1629 			 * SC so clear this flag so we won't send a message
1630 			 * back to finish the IO there.
1631 			 */
1632 			io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
1633 			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1634 
1635 			/* io = msg->hdr.serializing_sc; */
1636 			io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
1637 			ctl_enqueue_isc(io);
1638 			break;
1639 
1640 		/* Handle resets sent from the other side */
1641 		case CTL_MSG_MANAGE_TASKS: {
1642 			struct ctl_taskio *taskio;
1643 			taskio = (struct ctl_taskio *)ctl_alloc_io(
1644 			    softc->othersc_pool);
1645 			ctl_zero_io((union ctl_io *)taskio);
1646 			taskio->io_hdr.io_type = CTL_IO_TASK;
1647 			taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1648 			taskio->io_hdr.nexus = msg->hdr.nexus;
1649 			taskio->task_action = msg->task.task_action;
1650 			taskio->tag_num = msg->task.tag_num;
1651 			taskio->tag_type = msg->task.tag_type;
1652 #ifdef CTL_TIME_IO
1653 			taskio->io_hdr.start_time = time_uptime;
1654 			getbinuptime(&taskio->io_hdr.start_bt);
1655 #endif /* CTL_TIME_IO */
1656 			ctl_run_task((union ctl_io *)taskio);
1657 			break;
1658 		}
1659 		/* Persistent Reserve action which needs attention */
1660 		case CTL_MSG_PERS_ACTION:
1661 			presio = (struct ctl_prio *)ctl_alloc_io(
1662 			    softc->othersc_pool);
1663 			ctl_zero_io((union ctl_io *)presio);
1664 			presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
1665 			presio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1666 			presio->io_hdr.nexus = msg->hdr.nexus;
1667 			presio->pr_msg = msg->pr;
1668 			ctl_enqueue_isc((union ctl_io *)presio);
1669 			break;
1670 		case CTL_MSG_UA:
1671 			ctl_isc_ua(softc, msg, param);
1672 			break;
1673 		case CTL_MSG_PORT_SYNC:
1674 			ctl_isc_port_sync(softc, msg, param);
1675 			break;
1676 		case CTL_MSG_LUN_SYNC:
1677 			ctl_isc_lun_sync(softc, msg, param);
1678 			break;
1679 		case CTL_MSG_IID_SYNC:
1680 			ctl_isc_iid_sync(softc, msg, param);
1681 			break;
1682 		case CTL_MSG_LOGIN:
1683 			ctl_isc_login(softc, msg, param);
1684 			break;
1685 		case CTL_MSG_MODE_SYNC:
1686 			ctl_isc_mode_sync(softc, msg, param);
1687 			break;
1688 		default:
1689 			printf("Received HA message of unknown type %d\n",
1690 			    msg->hdr.msg_type);
1691 			ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1692 			break;
1693 		}
1694 		if (msg != &msgbuf)
1695 			free(msg, M_CTL);
1696 	} else if (event == CTL_HA_EVT_LINK_CHANGE) {
1697 		printf("CTL: HA link status changed from %d to %d\n",
1698 		    softc->ha_link, param);
1699 		if (param == softc->ha_link)
1700 			return;
1701 		if (softc->ha_link == CTL_HA_LINK_ONLINE) {
1702 			softc->ha_link = param;
1703 			ctl_isc_ha_link_down(softc);
1704 		} else {
1705 			softc->ha_link = param;
1706 			if (softc->ha_link == CTL_HA_LINK_ONLINE)
1707 				ctl_isc_ha_link_up(softc);
1708 		}
1709 		return;
1710 	} else {
1711 		printf("ctl_isc_event_handler: Unknown event %d\n", event);
1712 		return;
1713 	}
1714 }
1715 
1716 static void
1717 ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
1718 {
1719 
1720 	memcpy(&dest->scsiio.sense_data, &src->scsi.sense_data,
1721 	    src->scsi.sense_len);
1722 	dest->scsiio.scsi_status = src->scsi.scsi_status;
1723 	dest->scsiio.sense_len = src->scsi.sense_len;
1724 	dest->io_hdr.status = src->hdr.status;
1725 }
1726 
1727 static void
1728 ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest)
1729 {
1730 
1731 	memcpy(&dest->scsi.sense_data, &src->scsiio.sense_data,
1732 	    src->scsiio.sense_len);
1733 	dest->scsi.scsi_status = src->scsiio.scsi_status;
1734 	dest->scsi.sense_len = src->scsiio.sense_len;
1735 	dest->hdr.status = src->io_hdr.status;
1736 }
1737 
1738 void
1739 ctl_est_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1740 {
1741 	struct ctl_softc *softc = lun->ctl_softc;
1742 	ctl_ua_type *pu;
1743 
1744 	if (initidx < softc->init_min || initidx >= softc->init_max)
1745 		return;
1746 	mtx_assert(&lun->lun_lock, MA_OWNED);
1747 	pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1748 	if (pu == NULL)
1749 		return;
1750 	pu[initidx % CTL_MAX_INIT_PER_PORT] |= ua;
1751 }
1752 
1753 void
1754 ctl_est_ua_port(struct ctl_lun *lun, int port, uint32_t except, ctl_ua_type ua)
1755 {
1756 	int i;
1757 
1758 	mtx_assert(&lun->lun_lock, MA_OWNED);
1759 	if (lun->pending_ua[port] == NULL)
1760 		return;
1761 	for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1762 		if (port * CTL_MAX_INIT_PER_PORT + i == except)
1763 			continue;
1764 		lun->pending_ua[port][i] |= ua;
1765 	}
1766 }
1767 
1768 void
1769 ctl_est_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1770 {
1771 	struct ctl_softc *softc = lun->ctl_softc;
1772 	int i;
1773 
1774 	mtx_assert(&lun->lun_lock, MA_OWNED);
1775 	for (i = softc->port_min; i < softc->port_max; i++)
1776 		ctl_est_ua_port(lun, i, except, ua);
1777 }
1778 
1779 void
1780 ctl_clr_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1781 {
1782 	struct ctl_softc *softc = lun->ctl_softc;
1783 	ctl_ua_type *pu;
1784 
1785 	if (initidx < softc->init_min || initidx >= softc->init_max)
1786 		return;
1787 	mtx_assert(&lun->lun_lock, MA_OWNED);
1788 	pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1789 	if (pu == NULL)
1790 		return;
1791 	pu[initidx % CTL_MAX_INIT_PER_PORT] &= ~ua;
1792 }
1793 
1794 void
1795 ctl_clr_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1796 {
1797 	struct ctl_softc *softc = lun->ctl_softc;
1798 	int i, j;
1799 
1800 	mtx_assert(&lun->lun_lock, MA_OWNED);
1801 	for (i = softc->port_min; i < softc->port_max; i++) {
1802 		if (lun->pending_ua[i] == NULL)
1803 			continue;
1804 		for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
1805 			if (i * CTL_MAX_INIT_PER_PORT + j == except)
1806 				continue;
1807 			lun->pending_ua[i][j] &= ~ua;
1808 		}
1809 	}
1810 }
1811 
1812 void
1813 ctl_clr_ua_allluns(struct ctl_softc *ctl_softc, uint32_t initidx,
1814     ctl_ua_type ua_type)
1815 {
1816 	struct ctl_lun *lun;
1817 
1818 	mtx_assert(&ctl_softc->ctl_lock, MA_OWNED);
1819 	STAILQ_FOREACH(lun, &ctl_softc->lun_list, links) {
1820 		mtx_lock(&lun->lun_lock);
1821 		ctl_clr_ua(lun, initidx, ua_type);
1822 		mtx_unlock(&lun->lun_lock);
1823 	}
1824 }
1825 
1826 static int
1827 ctl_ha_role_sysctl(SYSCTL_HANDLER_ARGS)
1828 {
1829 	struct ctl_softc *softc = (struct ctl_softc *)arg1;
1830 	struct ctl_lun *lun;
1831 	struct ctl_lun_req ireq;
1832 	int error, value;
1833 
1834 	value = (softc->flags & CTL_FLAG_ACTIVE_SHELF) ? 0 : 1;
1835 	error = sysctl_handle_int(oidp, &value, 0, req);
1836 	if ((error != 0) || (req->newptr == NULL))
1837 		return (error);
1838 
1839 	mtx_lock(&softc->ctl_lock);
1840 	if (value == 0)
1841 		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1842 	else
1843 		softc->flags &= ~CTL_FLAG_ACTIVE_SHELF;
1844 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
1845 		mtx_unlock(&softc->ctl_lock);
1846 		bzero(&ireq, sizeof(ireq));
1847 		ireq.reqtype = CTL_LUNREQ_MODIFY;
1848 		ireq.reqdata.modify.lun_id = lun->lun;
1849 		lun->backend->ioctl(NULL, CTL_LUN_REQ, (caddr_t)&ireq, 0,
1850 		    curthread);
1851 		if (ireq.status != CTL_LUN_OK) {
1852 			printf("%s: CTL_LUNREQ_MODIFY returned %d '%s'\n",
1853 			    __func__, ireq.status, ireq.error_str);
1854 		}
1855 		mtx_lock(&softc->ctl_lock);
1856 	}
1857 	mtx_unlock(&softc->ctl_lock);
1858 	return (0);
1859 }
1860 
1861 static int
1862 ctl_init(void)
1863 {
1864 	struct make_dev_args args;
1865 	struct ctl_softc *softc;
1866 	int i, error;
1867 
1868 	softc = control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
1869 			       M_WAITOK | M_ZERO);
1870 
1871 	make_dev_args_init(&args);
1872 	args.mda_devsw = &ctl_cdevsw;
1873 	args.mda_uid = UID_ROOT;
1874 	args.mda_gid = GID_OPERATOR;
1875 	args.mda_mode = 0600;
1876 	args.mda_si_drv1 = softc;
1877 	args.mda_si_drv2 = NULL;
1878 	error = make_dev_s(&args, &softc->dev, "cam/ctl");
1879 	if (error != 0) {
1880 		free(softc, M_DEVBUF);
1881 		control_softc = NULL;
1882 		return (error);
1883 	}
1884 
1885 	sysctl_ctx_init(&softc->sysctl_ctx);
1886 	softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
1887 		SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
1888 		CTLFLAG_RD | CTLFLAG_MPSAFE, 0, "CAM Target Layer");
1889 
1890 	if (softc->sysctl_tree == NULL) {
1891 		printf("%s: unable to allocate sysctl tree\n", __func__);
1892 		destroy_dev(softc->dev);
1893 		free(softc, M_DEVBUF);
1894 		control_softc = NULL;
1895 		return (ENOMEM);
1896 	}
1897 
1898 	mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
1899 	softc->io_zone = uma_zcreate("CTL IO", sizeof(union ctl_io),
1900 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1901 	softc->flags = 0;
1902 
1903 	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1904 	    OID_AUTO, "ha_mode", CTLFLAG_RDTUN, (int *)&softc->ha_mode, 0,
1905 	    "HA mode (0 - act/stby, 1 - serialize only, 2 - xfer)");
1906 
1907 	if (ctl_max_luns <= 0 || powerof2(ctl_max_luns) == 0) {
1908 		printf("Bad value %d for kern.cam.ctl.max_luns, must be a power of two, using %d\n",
1909 		    ctl_max_luns, CTL_DEFAULT_MAX_LUNS);
1910 		ctl_max_luns = CTL_DEFAULT_MAX_LUNS;
1911 	}
1912 	softc->ctl_luns = malloc(sizeof(struct ctl_lun *) * ctl_max_luns,
1913 	    M_DEVBUF, M_WAITOK | M_ZERO);
1914 	softc->ctl_lun_mask = malloc(sizeof(uint32_t) *
1915 	    ((ctl_max_luns + 31) / 32), M_DEVBUF, M_WAITOK | M_ZERO);
1916 	if (ctl_max_ports <= 0 || powerof2(ctl_max_ports) == 0) {
1917 		printf("Bad value %d for kern.cam.ctl.max_ports, must be a power of two, using %d\n",
1918 		    ctl_max_ports, CTL_DEFAULT_MAX_PORTS);
1919 		ctl_max_ports = CTL_DEFAULT_MAX_PORTS;
1920 	}
1921 	softc->ctl_port_mask = malloc(sizeof(uint32_t) *
1922 	  ((ctl_max_ports + 31) / 32), M_DEVBUF, M_WAITOK | M_ZERO);
1923 	softc->ctl_ports = malloc(sizeof(struct ctl_port *) * ctl_max_ports,
1924 	     M_DEVBUF, M_WAITOK | M_ZERO);
1925 
1926 	/*
1927 	 * In Copan's HA scheme, the "master" and "slave" roles are
1928 	 * figured out through the slot the controller is in.  Although it
1929 	 * is an active/active system, someone has to be in charge.
1930 	 */
1931 	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1932 	    OID_AUTO, "ha_id", CTLFLAG_RDTUN, &softc->ha_id, 0,
1933 	    "HA head ID (0 - no HA)");
1934 	if (softc->ha_id == 0 || softc->ha_id > NUM_HA_SHELVES) {
1935 		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1936 		softc->is_single = 1;
1937 		softc->port_cnt = ctl_max_ports;
1938 		softc->port_min = 0;
1939 	} else {
1940 		softc->port_cnt = ctl_max_ports / NUM_HA_SHELVES;
1941 		softc->port_min = (softc->ha_id - 1) * softc->port_cnt;
1942 	}
1943 	softc->port_max = softc->port_min + softc->port_cnt;
1944 	softc->init_min = softc->port_min * CTL_MAX_INIT_PER_PORT;
1945 	softc->init_max = softc->port_max * CTL_MAX_INIT_PER_PORT;
1946 
1947 	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1948 	    OID_AUTO, "ha_link", CTLFLAG_RD, (int *)&softc->ha_link, 0,
1949 	    "HA link state (0 - offline, 1 - unknown, 2 - online)");
1950 
1951 	STAILQ_INIT(&softc->lun_list);
1952 	STAILQ_INIT(&softc->fe_list);
1953 	STAILQ_INIT(&softc->port_list);
1954 	STAILQ_INIT(&softc->be_list);
1955 	ctl_tpc_init(softc);
1956 
1957 	if (worker_threads <= 0)
1958 		worker_threads = max(1, mp_ncpus / 4);
1959 	if (worker_threads > CTL_MAX_THREADS)
1960 		worker_threads = CTL_MAX_THREADS;
1961 
1962 	for (i = 0; i < worker_threads; i++) {
1963 		struct ctl_thread *thr = &softc->threads[i];
1964 
1965 		mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1966 		thr->ctl_softc = softc;
1967 		STAILQ_INIT(&thr->incoming_queue);
1968 		STAILQ_INIT(&thr->rtr_queue);
1969 		STAILQ_INIT(&thr->done_queue);
1970 		STAILQ_INIT(&thr->isc_queue);
1971 
1972 		error = kproc_kthread_add(ctl_work_thread, thr,
1973 		    &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1974 		if (error != 0) {
1975 			printf("error creating CTL work thread!\n");
1976 			return (error);
1977 		}
1978 	}
1979 	error = kproc_kthread_add(ctl_thresh_thread, softc,
1980 	    &softc->ctl_proc, &softc->thresh_thread, 0, 0, "ctl", "thresh");
1981 	if (error != 0) {
1982 		printf("error creating CTL threshold thread!\n");
1983 		return (error);
1984 	}
1985 
1986 	SYSCTL_ADD_PROC(&softc->sysctl_ctx,SYSCTL_CHILDREN(softc->sysctl_tree),
1987 	    OID_AUTO, "ha_role",
1988 	    CTLTYPE_INT | CTLFLAG_RWTUN | CTLFLAG_MPSAFE,
1989 	    softc, 0, ctl_ha_role_sysctl, "I", "HA role for this head");
1990 
1991 	if (softc->is_single == 0) {
1992 		if (ctl_frontend_register(&ha_frontend) != 0)
1993 			softc->is_single = 1;
1994 	}
1995 	return (0);
1996 }
1997 
1998 static int
1999 ctl_shutdown(void)
2000 {
2001 	struct ctl_softc *softc = control_softc;
2002 	int i;
2003 
2004 	if (softc->is_single == 0)
2005 		ctl_frontend_deregister(&ha_frontend);
2006 
2007 	destroy_dev(softc->dev);
2008 
2009 	/* Shutdown CTL threads. */
2010 	softc->shutdown = 1;
2011 	for (i = 0; i < worker_threads; i++) {
2012 		struct ctl_thread *thr = &softc->threads[i];
2013 		while (thr->thread != NULL) {
2014 			wakeup(thr);
2015 			if (thr->thread != NULL)
2016 				pause("CTL thr shutdown", 1);
2017 		}
2018 		mtx_destroy(&thr->queue_lock);
2019 	}
2020 	while (softc->thresh_thread != NULL) {
2021 		wakeup(softc->thresh_thread);
2022 		if (softc->thresh_thread != NULL)
2023 			pause("CTL thr shutdown", 1);
2024 	}
2025 
2026 	ctl_tpc_shutdown(softc);
2027 	uma_zdestroy(softc->io_zone);
2028 	mtx_destroy(&softc->ctl_lock);
2029 
2030 	free(softc->ctl_luns, M_DEVBUF);
2031 	free(softc->ctl_lun_mask, M_DEVBUF);
2032 	free(softc->ctl_port_mask, M_DEVBUF);
2033 	free(softc->ctl_ports, M_DEVBUF);
2034 
2035 	sysctl_ctx_free(&softc->sysctl_ctx);
2036 
2037 	free(softc, M_DEVBUF);
2038 	control_softc = NULL;
2039 	return (0);
2040 }
2041 
2042 static int
2043 ctl_module_event_handler(module_t mod, int what, void *arg)
2044 {
2045 
2046 	switch (what) {
2047 	case MOD_LOAD:
2048 		return (ctl_init());
2049 	case MOD_UNLOAD:
2050 		return (ctl_shutdown());
2051 	default:
2052 		return (EOPNOTSUPP);
2053 	}
2054 }
2055 
2056 /*
2057  * XXX KDM should we do some access checks here?  Bump a reference count to
2058  * prevent a CTL module from being unloaded while someone has it open?
2059  */
2060 static int
2061 ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
2062 {
2063 	return (0);
2064 }
2065 
2066 static int
2067 ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
2068 {
2069 	return (0);
2070 }
2071 
2072 /*
2073  * Remove an initiator by port number and initiator ID.
2074  * Returns 0 for success, -1 for failure.
2075  */
2076 int
2077 ctl_remove_initiator(struct ctl_port *port, int iid)
2078 {
2079 	struct ctl_softc *softc = port->ctl_softc;
2080 	int last;
2081 
2082 	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
2083 
2084 	if (iid > CTL_MAX_INIT_PER_PORT) {
2085 		printf("%s: initiator ID %u > maximun %u!\n",
2086 		       __func__, iid, CTL_MAX_INIT_PER_PORT);
2087 		return (-1);
2088 	}
2089 
2090 	mtx_lock(&softc->ctl_lock);
2091 	last = (--port->wwpn_iid[iid].in_use == 0);
2092 	port->wwpn_iid[iid].last_use = time_uptime;
2093 	mtx_unlock(&softc->ctl_lock);
2094 	if (last)
2095 		ctl_i_t_nexus_loss(softc, iid, CTL_UA_POWERON);
2096 	ctl_isc_announce_iid(port, iid);
2097 
2098 	return (0);
2099 }
2100 
2101 /*
2102  * Add an initiator to the initiator map.
2103  * Returns iid for success, < 0 for failure.
2104  */
2105 int
2106 ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
2107 {
2108 	struct ctl_softc *softc = port->ctl_softc;
2109 	time_t best_time;
2110 	int i, best;
2111 
2112 	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
2113 
2114 	if (iid >= CTL_MAX_INIT_PER_PORT) {
2115 		printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
2116 		       __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
2117 		free(name, M_CTL);
2118 		return (-1);
2119 	}
2120 
2121 	mtx_lock(&softc->ctl_lock);
2122 
2123 	if (iid < 0 && (wwpn != 0 || name != NULL)) {
2124 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2125 			if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
2126 				iid = i;
2127 				break;
2128 			}
2129 			if (name != NULL && port->wwpn_iid[i].name != NULL &&
2130 			    strcmp(name, port->wwpn_iid[i].name) == 0) {
2131 				iid = i;
2132 				break;
2133 			}
2134 		}
2135 	}
2136 
2137 	if (iid < 0) {
2138 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2139 			if (port->wwpn_iid[i].in_use == 0 &&
2140 			    port->wwpn_iid[i].wwpn == 0 &&
2141 			    port->wwpn_iid[i].name == NULL) {
2142 				iid = i;
2143 				break;
2144 			}
2145 		}
2146 	}
2147 
2148 	if (iid < 0) {
2149 		best = -1;
2150 		best_time = INT32_MAX;
2151 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2152 			if (port->wwpn_iid[i].in_use == 0) {
2153 				if (port->wwpn_iid[i].last_use < best_time) {
2154 					best = i;
2155 					best_time = port->wwpn_iid[i].last_use;
2156 				}
2157 			}
2158 		}
2159 		iid = best;
2160 	}
2161 
2162 	if (iid < 0) {
2163 		mtx_unlock(&softc->ctl_lock);
2164 		free(name, M_CTL);
2165 		return (-2);
2166 	}
2167 
2168 	if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
2169 		/*
2170 		 * This is not an error yet.
2171 		 */
2172 		if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
2173 #if 0
2174 			printf("%s: port %d iid %u WWPN %#jx arrived"
2175 			    " again\n", __func__, port->targ_port,
2176 			    iid, (uintmax_t)wwpn);
2177 #endif
2178 			goto take;
2179 		}
2180 		if (name != NULL && port->wwpn_iid[iid].name != NULL &&
2181 		    strcmp(name, port->wwpn_iid[iid].name) == 0) {
2182 #if 0
2183 			printf("%s: port %d iid %u name '%s' arrived"
2184 			    " again\n", __func__, port->targ_port,
2185 			    iid, name);
2186 #endif
2187 			goto take;
2188 		}
2189 
2190 		/*
2191 		 * This is an error, but what do we do about it?  The
2192 		 * driver is telling us we have a new WWPN for this
2193 		 * initiator ID, so we pretty much need to use it.
2194 		 */
2195 		printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
2196 		    " but WWPN %#jx '%s' is still at that address\n",
2197 		    __func__, port->targ_port, iid, wwpn, name,
2198 		    (uintmax_t)port->wwpn_iid[iid].wwpn,
2199 		    port->wwpn_iid[iid].name);
2200 	}
2201 take:
2202 	free(port->wwpn_iid[iid].name, M_CTL);
2203 	port->wwpn_iid[iid].name = name;
2204 	port->wwpn_iid[iid].wwpn = wwpn;
2205 	port->wwpn_iid[iid].in_use++;
2206 	mtx_unlock(&softc->ctl_lock);
2207 	ctl_isc_announce_iid(port, iid);
2208 
2209 	return (iid);
2210 }
2211 
2212 static int
2213 ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
2214 {
2215 	int len;
2216 
2217 	switch (port->port_type) {
2218 	case CTL_PORT_FC:
2219 	{
2220 		struct scsi_transportid_fcp *id =
2221 		    (struct scsi_transportid_fcp *)buf;
2222 		if (port->wwpn_iid[iid].wwpn == 0)
2223 			return (0);
2224 		memset(id, 0, sizeof(*id));
2225 		id->format_protocol = SCSI_PROTO_FC;
2226 		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
2227 		return (sizeof(*id));
2228 	}
2229 	case CTL_PORT_ISCSI:
2230 	{
2231 		struct scsi_transportid_iscsi_port *id =
2232 		    (struct scsi_transportid_iscsi_port *)buf;
2233 		if (port->wwpn_iid[iid].name == NULL)
2234 			return (0);
2235 		memset(id, 0, 256);
2236 		id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
2237 		    SCSI_PROTO_ISCSI;
2238 		len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
2239 		len = roundup2(min(len, 252), 4);
2240 		scsi_ulto2b(len, id->additional_length);
2241 		return (sizeof(*id) + len);
2242 	}
2243 	case CTL_PORT_SAS:
2244 	{
2245 		struct scsi_transportid_sas *id =
2246 		    (struct scsi_transportid_sas *)buf;
2247 		if (port->wwpn_iid[iid].wwpn == 0)
2248 			return (0);
2249 		memset(id, 0, sizeof(*id));
2250 		id->format_protocol = SCSI_PROTO_SAS;
2251 		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
2252 		return (sizeof(*id));
2253 	}
2254 	default:
2255 	{
2256 		struct scsi_transportid_spi *id =
2257 		    (struct scsi_transportid_spi *)buf;
2258 		memset(id, 0, sizeof(*id));
2259 		id->format_protocol = SCSI_PROTO_SPI;
2260 		scsi_ulto2b(iid, id->scsi_addr);
2261 		scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
2262 		return (sizeof(*id));
2263 	}
2264 	}
2265 }
2266 
2267 /*
2268  * Serialize a command that went down the "wrong" side, and so was sent to
2269  * this controller for execution.  The logic is a little different than the
2270  * standard case in ctl_scsiio_precheck().  Errors in this case need to get
2271  * sent back to the other side, but in the success case, we execute the
2272  * command on this side (XFER mode) or tell the other side to execute it
2273  * (SER_ONLY mode).
2274  */
2275 static void
2276 ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
2277 {
2278 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
2279 	struct ctl_port *port = CTL_PORT(ctsio);
2280 	union ctl_ha_msg msg_info;
2281 	struct ctl_lun *lun;
2282 	const struct ctl_cmd_entry *entry;
2283 	union ctl_io *bio;
2284 	uint32_t targ_lun;
2285 
2286 	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
2287 
2288 	/* Make sure that we know about this port. */
2289 	if (port == NULL || (port->status & CTL_PORT_STATUS_ONLINE) == 0) {
2290 		ctl_set_internal_failure(ctsio, /*sks_valid*/ 0,
2291 					 /*retry_count*/ 1);
2292 		goto badjuju;
2293 	}
2294 
2295 	/* Make sure that we know about this LUN. */
2296 	mtx_lock(&softc->ctl_lock);
2297 	if (targ_lun >= ctl_max_luns ||
2298 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
2299 		mtx_unlock(&softc->ctl_lock);
2300 
2301 		/*
2302 		 * The other node would not send this request to us unless
2303 		 * received announce that we are primary node for this LUN.
2304 		 * If this LUN does not exist now, it is probably result of
2305 		 * a race, so respond to initiator in the most opaque way.
2306 		 */
2307 		ctl_set_busy(ctsio);
2308 		goto badjuju;
2309 	}
2310 	mtx_lock(&lun->lun_lock);
2311 	mtx_unlock(&softc->ctl_lock);
2312 
2313 	/*
2314 	 * If the LUN is invalid, pretend that it doesn't exist.
2315 	 * It will go away as soon as all pending I/Os completed.
2316 	 */
2317 	if (lun->flags & CTL_LUN_DISABLED) {
2318 		mtx_unlock(&lun->lun_lock);
2319 		ctl_set_busy(ctsio);
2320 		goto badjuju;
2321 	}
2322 
2323 	entry = ctl_get_cmd_entry(ctsio, NULL);
2324 	ctsio->seridx = entry->seridx;
2325 	if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
2326 		mtx_unlock(&lun->lun_lock);
2327 		goto badjuju;
2328 	}
2329 
2330 	CTL_LUN(ctsio) = lun;
2331 	CTL_BACKEND_LUN(ctsio) = lun->be_lun;
2332 
2333 	/*
2334 	 * Every I/O goes into the OOA queue for a
2335 	 * particular LUN, and stays there until completion.
2336 	 */
2337 #ifdef CTL_TIME_IO
2338 	if (LIST_EMPTY(&lun->ooa_queue))
2339 		lun->idle_time += getsbinuptime() - lun->last_busy;
2340 #endif
2341 	LIST_INSERT_HEAD(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2342 
2343 	bio = (union ctl_io *)LIST_NEXT(&ctsio->io_hdr, ooa_links);
2344 	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio, &bio)) {
2345 	case CTL_ACTION_PASS:
2346 	case CTL_ACTION_SKIP:
2347 		if (softc->ha_mode == CTL_HA_MODE_XFER) {
2348 			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
2349 			ctl_enqueue_rtr((union ctl_io *)ctsio);
2350 			mtx_unlock(&lun->lun_lock);
2351 		} else {
2352 			ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
2353 			mtx_unlock(&lun->lun_lock);
2354 
2355 			/* send msg back to other side */
2356 			msg_info.hdr.original_sc = ctsio->io_hdr.remote_io;
2357 			msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
2358 			msg_info.hdr.msg_type = CTL_MSG_R2R;
2359 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2360 			    sizeof(msg_info.hdr), M_WAITOK);
2361 		}
2362 		break;
2363 	case CTL_ACTION_BLOCK:
2364 		ctsio->io_hdr.blocker = bio;
2365 		TAILQ_INSERT_TAIL(&bio->io_hdr.blocked_queue, &ctsio->io_hdr,
2366 				  blocked_links);
2367 		mtx_unlock(&lun->lun_lock);
2368 		break;
2369 	case CTL_ACTION_OVERLAP:
2370 		LIST_REMOVE(&ctsio->io_hdr, ooa_links);
2371 		mtx_unlock(&lun->lun_lock);
2372 		ctl_set_overlapped_cmd(ctsio);
2373 		goto badjuju;
2374 	case CTL_ACTION_OVERLAP_TAG:
2375 		LIST_REMOVE(&ctsio->io_hdr, ooa_links);
2376 		mtx_unlock(&lun->lun_lock);
2377 		ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
2378 badjuju:
2379 		ctl_copy_sense_data_back((union ctl_io *)ctsio, &msg_info);
2380 		msg_info.hdr.original_sc = ctsio->io_hdr.remote_io;
2381 		msg_info.hdr.serializing_sc = NULL;
2382 		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
2383 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2384 		    sizeof(msg_info.scsi), M_WAITOK);
2385 		ctl_free_io((union ctl_io *)ctsio);
2386 		break;
2387 	default:
2388 		__assert_unreachable();
2389 	}
2390 }
2391 
2392 /*
2393  * Returns 0 for success, errno for failure.
2394  */
2395 static void
2396 ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2397 		   struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2398 {
2399 	struct ctl_io_hdr *ioh;
2400 
2401 	mtx_lock(&lun->lun_lock);
2402 	ioh = LIST_FIRST(&lun->ooa_queue);
2403 	if (ioh == NULL) {
2404 		mtx_unlock(&lun->lun_lock);
2405 		return;
2406 	}
2407 	while (LIST_NEXT(ioh, ooa_links) != NULL)
2408 		ioh = LIST_NEXT(ioh, ooa_links);
2409 	for ( ; ioh; ioh = LIST_PREV(ioh, &lun->ooa_queue, ctl_io_hdr, ooa_links)) {
2410 		union ctl_io *io = (union ctl_io *)ioh;
2411 		struct ctl_ooa_entry *entry;
2412 
2413 		/*
2414 		 * If we've got more than we can fit, just count the
2415 		 * remaining entries.
2416 		 */
2417 		if (*cur_fill_num >= ooa_hdr->alloc_num) {
2418 			(*cur_fill_num)++;
2419 			continue;
2420 		}
2421 
2422 		entry = &kern_entries[*cur_fill_num];
2423 
2424 		entry->tag_num = io->scsiio.tag_num;
2425 		entry->tag_type = io->scsiio.tag_type;
2426 		entry->lun_num = lun->lun;
2427 #ifdef CTL_TIME_IO
2428 		entry->start_bt = io->io_hdr.start_bt;
2429 #endif
2430 		bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2431 		entry->cdb_len = io->scsiio.cdb_len;
2432 		if (io->io_hdr.blocker != NULL)
2433 			entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2434 
2435 		if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2436 			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2437 
2438 		if (io->io_hdr.flags & CTL_FLAG_ABORT)
2439 			entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2440 
2441 		if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2442 			entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2443 
2444 		if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2445 			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2446 
2447 		if (io->io_hdr.flags & CTL_FLAG_STATUS_QUEUED)
2448 			entry->cmd_flags |= CTL_OOACMD_FLAG_STATUS_QUEUED;
2449 
2450 		if (io->io_hdr.flags & CTL_FLAG_STATUS_SENT)
2451 			entry->cmd_flags |= CTL_OOACMD_FLAG_STATUS_SENT;
2452 		(*cur_fill_num)++;
2453 	}
2454 	mtx_unlock(&lun->lun_lock);
2455 }
2456 
2457 /*
2458  * Escape characters that are illegal or not recommended in XML.
2459  */
2460 int
2461 ctl_sbuf_printf_esc(struct sbuf *sb, char *str, int size)
2462 {
2463 	char *end = str + size;
2464 	int retval;
2465 
2466 	retval = 0;
2467 
2468 	for (; *str && str < end; str++) {
2469 		switch (*str) {
2470 		case '&':
2471 			retval = sbuf_cat(sb, "&amp;");
2472 			break;
2473 		case '>':
2474 			retval = sbuf_cat(sb, "&gt;");
2475 			break;
2476 		case '<':
2477 			retval = sbuf_cat(sb, "&lt;");
2478 			break;
2479 		default:
2480 			retval = sbuf_putc(sb, *str);
2481 			break;
2482 		}
2483 
2484 		if (retval != 0)
2485 			break;
2486 	}
2487 
2488 	return (retval);
2489 }
2490 
2491 static void
2492 ctl_id_sbuf(struct ctl_devid *id, struct sbuf *sb)
2493 {
2494 	struct scsi_vpd_id_descriptor *desc;
2495 	int i;
2496 
2497 	if (id == NULL || id->len < 4)
2498 		return;
2499 	desc = (struct scsi_vpd_id_descriptor *)id->data;
2500 	switch (desc->id_type & SVPD_ID_TYPE_MASK) {
2501 	case SVPD_ID_TYPE_T10:
2502 		sbuf_cat(sb, "t10.");
2503 		break;
2504 	case SVPD_ID_TYPE_EUI64:
2505 		sbuf_cat(sb, "eui.");
2506 		break;
2507 	case SVPD_ID_TYPE_NAA:
2508 		sbuf_cat(sb, "naa.");
2509 		break;
2510 	case SVPD_ID_TYPE_SCSI_NAME:
2511 		break;
2512 	}
2513 	switch (desc->proto_codeset & SVPD_ID_CODESET_MASK) {
2514 	case SVPD_ID_CODESET_BINARY:
2515 		for (i = 0; i < desc->length; i++)
2516 			sbuf_printf(sb, "%02x", desc->identifier[i]);
2517 		break;
2518 	case SVPD_ID_CODESET_ASCII:
2519 		sbuf_printf(sb, "%.*s", (int)desc->length,
2520 		    (char *)desc->identifier);
2521 		break;
2522 	case SVPD_ID_CODESET_UTF8:
2523 		sbuf_cat(sb, (char *)desc->identifier);
2524 		break;
2525 	}
2526 }
2527 
2528 static int
2529 ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2530 	  struct thread *td)
2531 {
2532 	struct ctl_softc *softc = dev->si_drv1;
2533 	struct ctl_port *port;
2534 	struct ctl_lun *lun;
2535 	int retval;
2536 
2537 	retval = 0;
2538 
2539 	switch (cmd) {
2540 	case CTL_IO:
2541 		retval = ctl_ioctl_io(dev, cmd, addr, flag, td);
2542 		break;
2543 	case CTL_ENABLE_PORT:
2544 	case CTL_DISABLE_PORT:
2545 	case CTL_SET_PORT_WWNS: {
2546 		struct ctl_port *port;
2547 		struct ctl_port_entry *entry;
2548 
2549 		entry = (struct ctl_port_entry *)addr;
2550 
2551 		mtx_lock(&softc->ctl_lock);
2552 		STAILQ_FOREACH(port, &softc->port_list, links) {
2553 			int action, done;
2554 
2555 			if (port->targ_port < softc->port_min ||
2556 			    port->targ_port >= softc->port_max)
2557 				continue;
2558 
2559 			action = 0;
2560 			done = 0;
2561 			if ((entry->port_type == CTL_PORT_NONE)
2562 			 && (entry->targ_port == port->targ_port)) {
2563 				/*
2564 				 * If the user only wants to enable or
2565 				 * disable or set WWNs on a specific port,
2566 				 * do the operation and we're done.
2567 				 */
2568 				action = 1;
2569 				done = 1;
2570 			} else if (entry->port_type & port->port_type) {
2571 				/*
2572 				 * Compare the user's type mask with the
2573 				 * particular frontend type to see if we
2574 				 * have a match.
2575 				 */
2576 				action = 1;
2577 				done = 0;
2578 
2579 				/*
2580 				 * Make sure the user isn't trying to set
2581 				 * WWNs on multiple ports at the same time.
2582 				 */
2583 				if (cmd == CTL_SET_PORT_WWNS) {
2584 					printf("%s: Can't set WWNs on "
2585 					       "multiple ports\n", __func__);
2586 					retval = EINVAL;
2587 					break;
2588 				}
2589 			}
2590 			if (action == 0)
2591 				continue;
2592 
2593 			/*
2594 			 * XXX KDM we have to drop the lock here, because
2595 			 * the online/offline operations can potentially
2596 			 * block.  We need to reference count the frontends
2597 			 * so they can't go away,
2598 			 */
2599 			if (cmd == CTL_ENABLE_PORT) {
2600 				mtx_unlock(&softc->ctl_lock);
2601 				ctl_port_online(port);
2602 				mtx_lock(&softc->ctl_lock);
2603 			} else if (cmd == CTL_DISABLE_PORT) {
2604 				mtx_unlock(&softc->ctl_lock);
2605 				ctl_port_offline(port);
2606 				mtx_lock(&softc->ctl_lock);
2607 			} else if (cmd == CTL_SET_PORT_WWNS) {
2608 				ctl_port_set_wwns(port,
2609 				    (entry->flags & CTL_PORT_WWNN_VALID) ?
2610 				    1 : 0, entry->wwnn,
2611 				    (entry->flags & CTL_PORT_WWPN_VALID) ?
2612 				    1 : 0, entry->wwpn);
2613 			}
2614 			if (done != 0)
2615 				break;
2616 		}
2617 		mtx_unlock(&softc->ctl_lock);
2618 		break;
2619 	}
2620 	case CTL_GET_OOA: {
2621 		struct ctl_ooa *ooa_hdr;
2622 		struct ctl_ooa_entry *entries;
2623 		uint32_t cur_fill_num;
2624 
2625 		ooa_hdr = (struct ctl_ooa *)addr;
2626 
2627 		if ((ooa_hdr->alloc_len == 0)
2628 		 || (ooa_hdr->alloc_num == 0)) {
2629 			printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2630 			       "must be non-zero\n", __func__,
2631 			       ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2632 			retval = EINVAL;
2633 			break;
2634 		}
2635 
2636 		if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2637 		    sizeof(struct ctl_ooa_entry))) {
2638 			printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2639 			       "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2640 			       __func__, ooa_hdr->alloc_len,
2641 			       ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2642 			retval = EINVAL;
2643 			break;
2644 		}
2645 
2646 		entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2647 		if (entries == NULL) {
2648 			printf("%s: could not allocate %d bytes for OOA "
2649 			       "dump\n", __func__, ooa_hdr->alloc_len);
2650 			retval = ENOMEM;
2651 			break;
2652 		}
2653 
2654 		mtx_lock(&softc->ctl_lock);
2655 		if ((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0 &&
2656 		    (ooa_hdr->lun_num >= ctl_max_luns ||
2657 		     softc->ctl_luns[ooa_hdr->lun_num] == NULL)) {
2658 			mtx_unlock(&softc->ctl_lock);
2659 			free(entries, M_CTL);
2660 			printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2661 			       __func__, (uintmax_t)ooa_hdr->lun_num);
2662 			retval = EINVAL;
2663 			break;
2664 		}
2665 
2666 		cur_fill_num = 0;
2667 
2668 		if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2669 			STAILQ_FOREACH(lun, &softc->lun_list, links) {
2670 				ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2671 				    ooa_hdr, entries);
2672 			}
2673 		} else {
2674 			lun = softc->ctl_luns[ooa_hdr->lun_num];
2675 			ctl_ioctl_fill_ooa(lun, &cur_fill_num, ooa_hdr,
2676 			    entries);
2677 		}
2678 		mtx_unlock(&softc->ctl_lock);
2679 
2680 		ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2681 		ooa_hdr->fill_len = ooa_hdr->fill_num *
2682 			sizeof(struct ctl_ooa_entry);
2683 		retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2684 		if (retval != 0) {
2685 			printf("%s: error copying out %d bytes for OOA dump\n",
2686 			       __func__, ooa_hdr->fill_len);
2687 		}
2688 
2689 		getbinuptime(&ooa_hdr->cur_bt);
2690 
2691 		if (cur_fill_num > ooa_hdr->alloc_num) {
2692 			ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2693 			ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2694 		} else {
2695 			ooa_hdr->dropped_num = 0;
2696 			ooa_hdr->status = CTL_OOA_OK;
2697 		}
2698 
2699 		free(entries, M_CTL);
2700 		break;
2701 	}
2702 	case CTL_DELAY_IO: {
2703 		struct ctl_io_delay_info *delay_info;
2704 
2705 		delay_info = (struct ctl_io_delay_info *)addr;
2706 
2707 #ifdef CTL_IO_DELAY
2708 		mtx_lock(&softc->ctl_lock);
2709 		if (delay_info->lun_id >= ctl_max_luns ||
2710 		    (lun = softc->ctl_luns[delay_info->lun_id]) == NULL) {
2711 			mtx_unlock(&softc->ctl_lock);
2712 			delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2713 			break;
2714 		}
2715 		mtx_lock(&lun->lun_lock);
2716 		mtx_unlock(&softc->ctl_lock);
2717 		delay_info->status = CTL_DELAY_STATUS_OK;
2718 		switch (delay_info->delay_type) {
2719 		case CTL_DELAY_TYPE_CONT:
2720 		case CTL_DELAY_TYPE_ONESHOT:
2721 			break;
2722 		default:
2723 			delay_info->status = CTL_DELAY_STATUS_INVALID_TYPE;
2724 			break;
2725 		}
2726 		switch (delay_info->delay_loc) {
2727 		case CTL_DELAY_LOC_DATAMOVE:
2728 			lun->delay_info.datamove_type = delay_info->delay_type;
2729 			lun->delay_info.datamove_delay = delay_info->delay_secs;
2730 			break;
2731 		case CTL_DELAY_LOC_DONE:
2732 			lun->delay_info.done_type = delay_info->delay_type;
2733 			lun->delay_info.done_delay = delay_info->delay_secs;
2734 			break;
2735 		default:
2736 			delay_info->status = CTL_DELAY_STATUS_INVALID_LOC;
2737 			break;
2738 		}
2739 		mtx_unlock(&lun->lun_lock);
2740 #else
2741 		delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2742 #endif /* CTL_IO_DELAY */
2743 		break;
2744 	}
2745 	case CTL_ERROR_INJECT: {
2746 		struct ctl_error_desc *err_desc, *new_err_desc;
2747 
2748 		err_desc = (struct ctl_error_desc *)addr;
2749 
2750 		new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2751 				      M_WAITOK | M_ZERO);
2752 		bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2753 
2754 		mtx_lock(&softc->ctl_lock);
2755 		if (err_desc->lun_id >= ctl_max_luns ||
2756 		    (lun = softc->ctl_luns[err_desc->lun_id]) == NULL) {
2757 			mtx_unlock(&softc->ctl_lock);
2758 			free(new_err_desc, M_CTL);
2759 			printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
2760 			       __func__, (uintmax_t)err_desc->lun_id);
2761 			retval = EINVAL;
2762 			break;
2763 		}
2764 		mtx_lock(&lun->lun_lock);
2765 		mtx_unlock(&softc->ctl_lock);
2766 
2767 		/*
2768 		 * We could do some checking here to verify the validity
2769 		 * of the request, but given the complexity of error
2770 		 * injection requests, the checking logic would be fairly
2771 		 * complex.
2772 		 *
2773 		 * For now, if the request is invalid, it just won't get
2774 		 * executed and might get deleted.
2775 		 */
2776 		STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
2777 
2778 		/*
2779 		 * XXX KDM check to make sure the serial number is unique,
2780 		 * in case we somehow manage to wrap.  That shouldn't
2781 		 * happen for a very long time, but it's the right thing to
2782 		 * do.
2783 		 */
2784 		new_err_desc->serial = lun->error_serial;
2785 		err_desc->serial = lun->error_serial;
2786 		lun->error_serial++;
2787 
2788 		mtx_unlock(&lun->lun_lock);
2789 		break;
2790 	}
2791 	case CTL_ERROR_INJECT_DELETE: {
2792 		struct ctl_error_desc *delete_desc, *desc, *desc2;
2793 		int delete_done;
2794 
2795 		delete_desc = (struct ctl_error_desc *)addr;
2796 		delete_done = 0;
2797 
2798 		mtx_lock(&softc->ctl_lock);
2799 		if (delete_desc->lun_id >= ctl_max_luns ||
2800 		    (lun = softc->ctl_luns[delete_desc->lun_id]) == NULL) {
2801 			mtx_unlock(&softc->ctl_lock);
2802 			printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
2803 			       __func__, (uintmax_t)delete_desc->lun_id);
2804 			retval = EINVAL;
2805 			break;
2806 		}
2807 		mtx_lock(&lun->lun_lock);
2808 		mtx_unlock(&softc->ctl_lock);
2809 		STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
2810 			if (desc->serial != delete_desc->serial)
2811 				continue;
2812 
2813 			STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
2814 				      links);
2815 			free(desc, M_CTL);
2816 			delete_done = 1;
2817 		}
2818 		mtx_unlock(&lun->lun_lock);
2819 		if (delete_done == 0) {
2820 			printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
2821 			       "error serial %ju on LUN %u\n", __func__,
2822 			       delete_desc->serial, delete_desc->lun_id);
2823 			retval = EINVAL;
2824 			break;
2825 		}
2826 		break;
2827 	}
2828 	case CTL_DUMP_STRUCTS: {
2829 		int j, k;
2830 		struct ctl_port *port;
2831 		struct ctl_frontend *fe;
2832 
2833 		mtx_lock(&softc->ctl_lock);
2834 		printf("CTL Persistent Reservation information start:\n");
2835 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
2836 			mtx_lock(&lun->lun_lock);
2837 			if ((lun->flags & CTL_LUN_DISABLED) != 0) {
2838 				mtx_unlock(&lun->lun_lock);
2839 				continue;
2840 			}
2841 
2842 			for (j = 0; j < ctl_max_ports; j++) {
2843 				if (lun->pr_keys[j] == NULL)
2844 					continue;
2845 				for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
2846 					if (lun->pr_keys[j][k] == 0)
2847 						continue;
2848 					printf("  LUN %ju port %d iid %d key "
2849 					       "%#jx\n", lun->lun, j, k,
2850 					       (uintmax_t)lun->pr_keys[j][k]);
2851 				}
2852 			}
2853 			mtx_unlock(&lun->lun_lock);
2854 		}
2855 		printf("CTL Persistent Reservation information end\n");
2856 		printf("CTL Ports:\n");
2857 		STAILQ_FOREACH(port, &softc->port_list, links) {
2858 			printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
2859 			       "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
2860 			       port->frontend->name, port->port_type,
2861 			       port->physical_port, port->virtual_port,
2862 			       (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
2863 			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
2864 				if (port->wwpn_iid[j].in_use == 0 &&
2865 				    port->wwpn_iid[j].wwpn == 0 &&
2866 				    port->wwpn_iid[j].name == NULL)
2867 					continue;
2868 
2869 				printf("    iid %u use %d WWPN %#jx '%s'\n",
2870 				    j, port->wwpn_iid[j].in_use,
2871 				    (uintmax_t)port->wwpn_iid[j].wwpn,
2872 				    port->wwpn_iid[j].name);
2873 			}
2874 		}
2875 		printf("CTL Port information end\n");
2876 		mtx_unlock(&softc->ctl_lock);
2877 		/*
2878 		 * XXX KDM calling this without a lock.  We'd likely want
2879 		 * to drop the lock before calling the frontend's dump
2880 		 * routine anyway.
2881 		 */
2882 		printf("CTL Frontends:\n");
2883 		STAILQ_FOREACH(fe, &softc->fe_list, links) {
2884 			printf("  Frontend '%s'\n", fe->name);
2885 			if (fe->fe_dump != NULL)
2886 				fe->fe_dump();
2887 		}
2888 		printf("CTL Frontend information end\n");
2889 		break;
2890 	}
2891 	case CTL_LUN_REQ: {
2892 		struct ctl_lun_req *lun_req;
2893 		struct ctl_backend_driver *backend;
2894 		void *packed;
2895 		nvlist_t *tmp_args_nvl;
2896 		size_t packed_len;
2897 
2898 		lun_req = (struct ctl_lun_req *)addr;
2899 		tmp_args_nvl = lun_req->args_nvl;
2900 
2901 		backend = ctl_backend_find(lun_req->backend);
2902 		if (backend == NULL) {
2903 			lun_req->status = CTL_LUN_ERROR;
2904 			snprintf(lun_req->error_str,
2905 				 sizeof(lun_req->error_str),
2906 				 "Backend \"%s\" not found.",
2907 				 lun_req->backend);
2908 			break;
2909 		}
2910 
2911 		if (lun_req->args != NULL) {
2912 			if (lun_req->args_len > CTL_MAX_ARGS_LEN) {
2913 				lun_req->status = CTL_LUN_ERROR;
2914 				snprintf(lun_req->error_str, sizeof(lun_req->error_str),
2915 				    "Too big args.");
2916 				break;
2917 			}
2918 			packed = malloc(lun_req->args_len, M_CTL, M_WAITOK);
2919 			if (copyin(lun_req->args, packed, lun_req->args_len) != 0) {
2920 				free(packed, M_CTL);
2921 				lun_req->status = CTL_LUN_ERROR;
2922 				snprintf(lun_req->error_str, sizeof(lun_req->error_str),
2923 				    "Cannot copyin args.");
2924 				break;
2925 			}
2926 			lun_req->args_nvl = nvlist_unpack(packed,
2927 			    lun_req->args_len, 0);
2928 			free(packed, M_CTL);
2929 
2930 			if (lun_req->args_nvl == NULL) {
2931 				lun_req->status = CTL_LUN_ERROR;
2932 				snprintf(lun_req->error_str, sizeof(lun_req->error_str),
2933 				    "Cannot unpack args nvlist.");
2934 				break;
2935 			}
2936 		} else
2937 			lun_req->args_nvl = nvlist_create(0);
2938 
2939 		lun_req->result_nvl = NULL;
2940 		retval = backend->ioctl(dev, cmd, addr, flag, td);
2941 		nvlist_destroy(lun_req->args_nvl);
2942 		lun_req->args_nvl = tmp_args_nvl;
2943 
2944 		if (lun_req->result_nvl != NULL) {
2945 			if (lun_req->result != NULL) {
2946 				packed = nvlist_pack(lun_req->result_nvl,
2947 				    &packed_len);
2948 				if (packed == NULL) {
2949 					lun_req->status = CTL_LUN_ERROR;
2950 					snprintf(lun_req->error_str,
2951 					    sizeof(lun_req->error_str),
2952 					    "Cannot pack result nvlist.");
2953 					break;
2954 				}
2955 
2956 				if (packed_len > lun_req->result_len) {
2957 					lun_req->status = CTL_LUN_ERROR;
2958 					snprintf(lun_req->error_str,
2959 					    sizeof(lun_req->error_str),
2960 					    "Result nvlist too large.");
2961 					free(packed, M_NVLIST);
2962 					break;
2963 				}
2964 
2965 				if (copyout(packed, lun_req->result, packed_len)) {
2966 					lun_req->status = CTL_LUN_ERROR;
2967 					snprintf(lun_req->error_str,
2968 					    sizeof(lun_req->error_str),
2969 					    "Cannot copyout() the result.");
2970 					free(packed, M_NVLIST);
2971 					break;
2972 				}
2973 
2974 				lun_req->result_len = packed_len;
2975 				free(packed, M_NVLIST);
2976 			}
2977 
2978 			nvlist_destroy(lun_req->result_nvl);
2979 		}
2980 		break;
2981 	}
2982 	case CTL_LUN_LIST: {
2983 		struct sbuf *sb;
2984 		struct ctl_lun_list *list;
2985 		const char *name, *value;
2986 		void *cookie;
2987 		int type;
2988 
2989 		list = (struct ctl_lun_list *)addr;
2990 
2991 		/*
2992 		 * Allocate a fixed length sbuf here, based on the length
2993 		 * of the user's buffer.  We could allocate an auto-extending
2994 		 * buffer, and then tell the user how much larger our
2995 		 * amount of data is than his buffer, but that presents
2996 		 * some problems:
2997 		 *
2998 		 * 1.  The sbuf(9) routines use a blocking malloc, and so
2999 		 *     we can't hold a lock while calling them with an
3000 		 *     auto-extending buffer.
3001  		 *
3002 		 * 2.  There is not currently a LUN reference counting
3003 		 *     mechanism, outside of outstanding transactions on
3004 		 *     the LUN's OOA queue.  So a LUN could go away on us
3005 		 *     while we're getting the LUN number, backend-specific
3006 		 *     information, etc.  Thus, given the way things
3007 		 *     currently work, we need to hold the CTL lock while
3008 		 *     grabbing LUN information.
3009 		 *
3010 		 * So, from the user's standpoint, the best thing to do is
3011 		 * allocate what he thinks is a reasonable buffer length,
3012 		 * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
3013 		 * double the buffer length and try again.  (And repeat
3014 		 * that until he succeeds.)
3015 		 */
3016 		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3017 		if (sb == NULL) {
3018 			list->status = CTL_LUN_LIST_ERROR;
3019 			snprintf(list->error_str, sizeof(list->error_str),
3020 				 "Unable to allocate %d bytes for LUN list",
3021 				 list->alloc_len);
3022 			break;
3023 		}
3024 
3025 		sbuf_cat(sb, "<ctllunlist>\n");
3026 
3027 		mtx_lock(&softc->ctl_lock);
3028 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
3029 			mtx_lock(&lun->lun_lock);
3030 			retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3031 					     (uintmax_t)lun->lun);
3032 
3033 			/*
3034 			 * Bail out as soon as we see that we've overfilled
3035 			 * the buffer.
3036 			 */
3037 			if (retval != 0)
3038 				break;
3039 
3040 			retval = sbuf_printf(sb, "\t<backend_type>%s"
3041 					     "</backend_type>\n",
3042 					     (lun->backend == NULL) ?  "none" :
3043 					     lun->backend->name);
3044 
3045 			if (retval != 0)
3046 				break;
3047 
3048 			retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3049 					     lun->be_lun->lun_type);
3050 
3051 			if (retval != 0)
3052 				break;
3053 
3054 			if (lun->backend == NULL) {
3055 				retval = sbuf_cat(sb, "</lun>\n");
3056 				if (retval != 0)
3057 					break;
3058 				continue;
3059 			}
3060 
3061 			retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3062 					     (lun->be_lun->maxlba > 0) ?
3063 					     lun->be_lun->maxlba + 1 : 0);
3064 
3065 			if (retval != 0)
3066 				break;
3067 
3068 			retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3069 					     lun->be_lun->blocksize);
3070 
3071 			if (retval != 0)
3072 				break;
3073 
3074 			retval = sbuf_cat(sb, "\t<serial_number>");
3075 
3076 			if (retval != 0)
3077 				break;
3078 
3079 			retval = ctl_sbuf_printf_esc(sb,
3080 			    lun->be_lun->serial_num,
3081 			    sizeof(lun->be_lun->serial_num));
3082 
3083 			if (retval != 0)
3084 				break;
3085 
3086 			retval = sbuf_cat(sb, "</serial_number>\n");
3087 
3088 			if (retval != 0)
3089 				break;
3090 
3091 			retval = sbuf_cat(sb, "\t<device_id>");
3092 
3093 			if (retval != 0)
3094 				break;
3095 
3096 			retval = ctl_sbuf_printf_esc(sb,
3097 			    lun->be_lun->device_id,
3098 			    sizeof(lun->be_lun->device_id));
3099 
3100 			if (retval != 0)
3101 				break;
3102 
3103 			retval = sbuf_cat(sb, "</device_id>\n");
3104 
3105 			if (retval != 0)
3106 				break;
3107 
3108 			if (lun->backend->lun_info != NULL) {
3109 				retval = lun->backend->lun_info(lun->be_lun, sb);
3110 				if (retval != 0)
3111 					break;
3112 			}
3113 
3114 			cookie = NULL;
3115 			while ((name = nvlist_next(lun->be_lun->options, &type,
3116 			    &cookie)) != NULL) {
3117 				sbuf_printf(sb, "\t<%s>", name);
3118 
3119 				if (type == NV_TYPE_STRING) {
3120 					value = dnvlist_get_string(
3121 					    lun->be_lun->options, name, NULL);
3122 					if (value != NULL)
3123 						sbuf_cat(sb, value);
3124 				}
3125 
3126 				sbuf_printf(sb, "</%s>\n", name);
3127 			}
3128 
3129 			retval = sbuf_cat(sb, "</lun>\n");
3130 
3131 			if (retval != 0)
3132 				break;
3133 			mtx_unlock(&lun->lun_lock);
3134 		}
3135 		if (lun != NULL)
3136 			mtx_unlock(&lun->lun_lock);
3137 		mtx_unlock(&softc->ctl_lock);
3138 
3139 		if ((retval != 0)
3140 		 || ((retval = sbuf_cat(sb, "</ctllunlist>\n")) != 0)) {
3141 			retval = 0;
3142 			sbuf_delete(sb);
3143 			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3144 			snprintf(list->error_str, sizeof(list->error_str),
3145 				 "Out of space, %d bytes is too small",
3146 				 list->alloc_len);
3147 			break;
3148 		}
3149 
3150 		sbuf_finish(sb);
3151 
3152 		retval = copyout(sbuf_data(sb), list->lun_xml,
3153 				 sbuf_len(sb) + 1);
3154 
3155 		list->fill_len = sbuf_len(sb) + 1;
3156 		list->status = CTL_LUN_LIST_OK;
3157 		sbuf_delete(sb);
3158 		break;
3159 	}
3160 	case CTL_ISCSI: {
3161 		struct ctl_iscsi *ci;
3162 		struct ctl_frontend *fe;
3163 
3164 		ci = (struct ctl_iscsi *)addr;
3165 
3166 		fe = ctl_frontend_find("iscsi");
3167 		if (fe == NULL) {
3168 			ci->status = CTL_ISCSI_ERROR;
3169 			snprintf(ci->error_str, sizeof(ci->error_str),
3170 			    "Frontend \"iscsi\" not found.");
3171 			break;
3172 		}
3173 
3174 		retval = fe->ioctl(dev, cmd, addr, flag, td);
3175 		break;
3176 	}
3177 	case CTL_PORT_REQ: {
3178 		struct ctl_req *req;
3179 		struct ctl_frontend *fe;
3180 		void *packed;
3181 		nvlist_t *tmp_args_nvl;
3182 		size_t packed_len;
3183 
3184 		req = (struct ctl_req *)addr;
3185 		tmp_args_nvl = req->args_nvl;
3186 
3187 		fe = ctl_frontend_find(req->driver);
3188 		if (fe == NULL) {
3189 			req->status = CTL_LUN_ERROR;
3190 			snprintf(req->error_str, sizeof(req->error_str),
3191 			    "Frontend \"%s\" not found.", req->driver);
3192 			break;
3193 		}
3194 
3195 		if (req->args != NULL) {
3196 			if (req->args_len > CTL_MAX_ARGS_LEN) {
3197 				req->status = CTL_LUN_ERROR;
3198 				snprintf(req->error_str, sizeof(req->error_str),
3199 				    "Too big args.");
3200 				break;
3201 			}
3202 			packed = malloc(req->args_len, M_CTL, M_WAITOK);
3203 			if (copyin(req->args, packed, req->args_len) != 0) {
3204 				free(packed, M_CTL);
3205 				req->status = CTL_LUN_ERROR;
3206 				snprintf(req->error_str, sizeof(req->error_str),
3207 				    "Cannot copyin args.");
3208 				break;
3209 			}
3210 			req->args_nvl = nvlist_unpack(packed,
3211 			    req->args_len, 0);
3212 			free(packed, M_CTL);
3213 
3214 			if (req->args_nvl == NULL) {
3215 				req->status = CTL_LUN_ERROR;
3216 				snprintf(req->error_str, sizeof(req->error_str),
3217 				    "Cannot unpack args nvlist.");
3218 				break;
3219 			}
3220 		} else
3221 			req->args_nvl = nvlist_create(0);
3222 
3223 		req->result_nvl = NULL;
3224 		if (fe->ioctl)
3225 			retval = fe->ioctl(dev, cmd, addr, flag, td);
3226 		else
3227 			retval = ENODEV;
3228 
3229 		nvlist_destroy(req->args_nvl);
3230 		req->args_nvl = tmp_args_nvl;
3231 
3232 		if (req->result_nvl != NULL) {
3233 			if (req->result != NULL) {
3234 				packed = nvlist_pack(req->result_nvl,
3235 				    &packed_len);
3236 				if (packed == NULL) {
3237 					req->status = CTL_LUN_ERROR;
3238 					snprintf(req->error_str,
3239 					    sizeof(req->error_str),
3240 					    "Cannot pack result nvlist.");
3241 					break;
3242 				}
3243 
3244 				if (packed_len > req->result_len) {
3245 					req->status = CTL_LUN_ERROR;
3246 					snprintf(req->error_str,
3247 					    sizeof(req->error_str),
3248 					    "Result nvlist too large.");
3249 					free(packed, M_NVLIST);
3250 					break;
3251 				}
3252 
3253 				if (copyout(packed, req->result, packed_len)) {
3254 					req->status = CTL_LUN_ERROR;
3255 					snprintf(req->error_str,
3256 					    sizeof(req->error_str),
3257 					    "Cannot copyout() the result.");
3258 					free(packed, M_NVLIST);
3259 					break;
3260 				}
3261 
3262 				req->result_len = packed_len;
3263 				free(packed, M_NVLIST);
3264 			}
3265 
3266 			nvlist_destroy(req->result_nvl);
3267 		}
3268 		break;
3269 	}
3270 	case CTL_PORT_LIST: {
3271 		struct sbuf *sb;
3272 		struct ctl_port *port;
3273 		struct ctl_lun_list *list;
3274 		const char *name, *value;
3275 		void *cookie;
3276 		int j, type;
3277 		uint32_t plun;
3278 
3279 		list = (struct ctl_lun_list *)addr;
3280 
3281 		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3282 		if (sb == NULL) {
3283 			list->status = CTL_LUN_LIST_ERROR;
3284 			snprintf(list->error_str, sizeof(list->error_str),
3285 				 "Unable to allocate %d bytes for LUN list",
3286 				 list->alloc_len);
3287 			break;
3288 		}
3289 
3290 		sbuf_cat(sb, "<ctlportlist>\n");
3291 
3292 		mtx_lock(&softc->ctl_lock);
3293 		STAILQ_FOREACH(port, &softc->port_list, links) {
3294 			retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3295 					     (uintmax_t)port->targ_port);
3296 
3297 			/*
3298 			 * Bail out as soon as we see that we've overfilled
3299 			 * the buffer.
3300 			 */
3301 			if (retval != 0)
3302 				break;
3303 
3304 			retval = sbuf_printf(sb, "\t<frontend_type>%s"
3305 			    "</frontend_type>\n", port->frontend->name);
3306 			if (retval != 0)
3307 				break;
3308 
3309 			retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3310 					     port->port_type);
3311 			if (retval != 0)
3312 				break;
3313 
3314 			retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3315 			    (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3316 			if (retval != 0)
3317 				break;
3318 
3319 			retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3320 			    port->port_name);
3321 			if (retval != 0)
3322 				break;
3323 
3324 			retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3325 			    port->physical_port);
3326 			if (retval != 0)
3327 				break;
3328 
3329 			retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3330 			    port->virtual_port);
3331 			if (retval != 0)
3332 				break;
3333 
3334 			if (port->target_devid != NULL) {
3335 				sbuf_cat(sb, "\t<target>");
3336 				ctl_id_sbuf(port->target_devid, sb);
3337 				sbuf_cat(sb, "</target>\n");
3338 			}
3339 
3340 			if (port->port_devid != NULL) {
3341 				sbuf_cat(sb, "\t<port>");
3342 				ctl_id_sbuf(port->port_devid, sb);
3343 				sbuf_cat(sb, "</port>\n");
3344 			}
3345 
3346 			if (port->port_info != NULL) {
3347 				retval = port->port_info(port->onoff_arg, sb);
3348 				if (retval != 0)
3349 					break;
3350 			}
3351 
3352 			cookie = NULL;
3353 			while ((name = nvlist_next(port->options, &type,
3354 			    &cookie)) != NULL) {
3355 				sbuf_printf(sb, "\t<%s>", name);
3356 
3357 				if (type == NV_TYPE_STRING) {
3358 					value = dnvlist_get_string(port->options,
3359 					    name, NULL);
3360 					if (value != NULL)
3361 						sbuf_printf(sb, "%s", value);
3362 				}
3363 
3364 				sbuf_printf(sb, "</%s>\n", name);
3365 			}
3366 
3367 			if (port->lun_map != NULL) {
3368 				sbuf_cat(sb, "\t<lun_map>on</lun_map>\n");
3369 				for (j = 0; j < port->lun_map_size; j++) {
3370 					plun = ctl_lun_map_from_port(port, j);
3371 					if (plun == UINT32_MAX)
3372 						continue;
3373 					sbuf_printf(sb,
3374 					    "\t<lun id=\"%u\">%u</lun>\n",
3375 					    j, plun);
3376 				}
3377 			}
3378 
3379 			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3380 				if (port->wwpn_iid[j].in_use == 0 ||
3381 				    (port->wwpn_iid[j].wwpn == 0 &&
3382 				     port->wwpn_iid[j].name == NULL))
3383 					continue;
3384 
3385 				if (port->wwpn_iid[j].name != NULL)
3386 					retval = sbuf_printf(sb,
3387 					    "\t<initiator id=\"%u\">%s</initiator>\n",
3388 					    j, port->wwpn_iid[j].name);
3389 				else
3390 					retval = sbuf_printf(sb,
3391 					    "\t<initiator id=\"%u\">naa.%08jx</initiator>\n",
3392 					    j, port->wwpn_iid[j].wwpn);
3393 				if (retval != 0)
3394 					break;
3395 			}
3396 			if (retval != 0)
3397 				break;
3398 
3399 			retval = sbuf_cat(sb, "</targ_port>\n");
3400 			if (retval != 0)
3401 				break;
3402 		}
3403 		mtx_unlock(&softc->ctl_lock);
3404 
3405 		if ((retval != 0)
3406 		 || ((retval = sbuf_cat(sb, "</ctlportlist>\n")) != 0)) {
3407 			retval = 0;
3408 			sbuf_delete(sb);
3409 			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3410 			snprintf(list->error_str, sizeof(list->error_str),
3411 				 "Out of space, %d bytes is too small",
3412 				 list->alloc_len);
3413 			break;
3414 		}
3415 
3416 		sbuf_finish(sb);
3417 
3418 		retval = copyout(sbuf_data(sb), list->lun_xml,
3419 				 sbuf_len(sb) + 1);
3420 
3421 		list->fill_len = sbuf_len(sb) + 1;
3422 		list->status = CTL_LUN_LIST_OK;
3423 		sbuf_delete(sb);
3424 		break;
3425 	}
3426 	case CTL_LUN_MAP: {
3427 		struct ctl_lun_map *lm  = (struct ctl_lun_map *)addr;
3428 		struct ctl_port *port;
3429 
3430 		mtx_lock(&softc->ctl_lock);
3431 		if (lm->port < softc->port_min ||
3432 		    lm->port >= softc->port_max ||
3433 		    (port = softc->ctl_ports[lm->port]) == NULL) {
3434 			mtx_unlock(&softc->ctl_lock);
3435 			return (ENXIO);
3436 		}
3437 		if (port->status & CTL_PORT_STATUS_ONLINE) {
3438 			STAILQ_FOREACH(lun, &softc->lun_list, links) {
3439 				if (ctl_lun_map_to_port(port, lun->lun) ==
3440 				    UINT32_MAX)
3441 					continue;
3442 				mtx_lock(&lun->lun_lock);
3443 				ctl_est_ua_port(lun, lm->port, -1,
3444 				    CTL_UA_LUN_CHANGE);
3445 				mtx_unlock(&lun->lun_lock);
3446 			}
3447 		}
3448 		mtx_unlock(&softc->ctl_lock); // XXX: port_enable sleeps
3449 		if (lm->plun != UINT32_MAX) {
3450 			if (lm->lun == UINT32_MAX)
3451 				retval = ctl_lun_map_unset(port, lm->plun);
3452 			else if (lm->lun < ctl_max_luns &&
3453 			    softc->ctl_luns[lm->lun] != NULL)
3454 				retval = ctl_lun_map_set(port, lm->plun, lm->lun);
3455 			else
3456 				return (ENXIO);
3457 		} else {
3458 			if (lm->lun == UINT32_MAX)
3459 				retval = ctl_lun_map_deinit(port);
3460 			else
3461 				retval = ctl_lun_map_init(port);
3462 		}
3463 		if (port->status & CTL_PORT_STATUS_ONLINE)
3464 			ctl_isc_announce_port(port);
3465 		break;
3466 	}
3467 	case CTL_GET_LUN_STATS: {
3468 		struct ctl_get_io_stats *stats = (struct ctl_get_io_stats *)addr;
3469 		int i;
3470 
3471 		/*
3472 		 * XXX KDM no locking here.  If the LUN list changes,
3473 		 * things can blow up.
3474 		 */
3475 		i = 0;
3476 		stats->status = CTL_SS_OK;
3477 		stats->fill_len = 0;
3478 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
3479 			if (lun->lun < stats->first_item)
3480 				continue;
3481 			if (stats->fill_len + sizeof(lun->stats) >
3482 			    stats->alloc_len) {
3483 				stats->status = CTL_SS_NEED_MORE_SPACE;
3484 				break;
3485 			}
3486 			retval = copyout(&lun->stats, &stats->stats[i++],
3487 					 sizeof(lun->stats));
3488 			if (retval != 0)
3489 				break;
3490 			stats->fill_len += sizeof(lun->stats);
3491 		}
3492 		stats->num_items = softc->num_luns;
3493 		stats->flags = CTL_STATS_FLAG_NONE;
3494 #ifdef CTL_TIME_IO
3495 		stats->flags |= CTL_STATS_FLAG_TIME_VALID;
3496 #endif
3497 		getnanouptime(&stats->timestamp);
3498 		break;
3499 	}
3500 	case CTL_GET_PORT_STATS: {
3501 		struct ctl_get_io_stats *stats = (struct ctl_get_io_stats *)addr;
3502 		int i;
3503 
3504 		/*
3505 		 * XXX KDM no locking here.  If the LUN list changes,
3506 		 * things can blow up.
3507 		 */
3508 		i = 0;
3509 		stats->status = CTL_SS_OK;
3510 		stats->fill_len = 0;
3511 		STAILQ_FOREACH(port, &softc->port_list, links) {
3512 			if (port->targ_port < stats->first_item)
3513 				continue;
3514 			if (stats->fill_len + sizeof(port->stats) >
3515 			    stats->alloc_len) {
3516 				stats->status = CTL_SS_NEED_MORE_SPACE;
3517 				break;
3518 			}
3519 			retval = copyout(&port->stats, &stats->stats[i++],
3520 					 sizeof(port->stats));
3521 			if (retval != 0)
3522 				break;
3523 			stats->fill_len += sizeof(port->stats);
3524 		}
3525 		stats->num_items = softc->num_ports;
3526 		stats->flags = CTL_STATS_FLAG_NONE;
3527 #ifdef CTL_TIME_IO
3528 		stats->flags |= CTL_STATS_FLAG_TIME_VALID;
3529 #endif
3530 		getnanouptime(&stats->timestamp);
3531 		break;
3532 	}
3533 	default: {
3534 		/* XXX KDM should we fix this? */
3535 #if 0
3536 		struct ctl_backend_driver *backend;
3537 		unsigned int type;
3538 		int found;
3539 
3540 		found = 0;
3541 
3542 		/*
3543 		 * We encode the backend type as the ioctl type for backend
3544 		 * ioctls.  So parse it out here, and then search for a
3545 		 * backend of this type.
3546 		 */
3547 		type = _IOC_TYPE(cmd);
3548 
3549 		STAILQ_FOREACH(backend, &softc->be_list, links) {
3550 			if (backend->type == type) {
3551 				found = 1;
3552 				break;
3553 			}
3554 		}
3555 		if (found == 0) {
3556 			printf("ctl: unknown ioctl command %#lx or backend "
3557 			       "%d\n", cmd, type);
3558 			retval = EINVAL;
3559 			break;
3560 		}
3561 		retval = backend->ioctl(dev, cmd, addr, flag, td);
3562 #endif
3563 		retval = ENOTTY;
3564 		break;
3565 	}
3566 	}
3567 	return (retval);
3568 }
3569 
3570 uint32_t
3571 ctl_get_initindex(struct ctl_nexus *nexus)
3572 {
3573 	return (nexus->initid + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3574 }
3575 
3576 int
3577 ctl_lun_map_init(struct ctl_port *port)
3578 {
3579 	struct ctl_softc *softc = port->ctl_softc;
3580 	struct ctl_lun *lun;
3581 	int size = ctl_lun_map_size;
3582 	uint32_t i;
3583 
3584 	if (port->lun_map == NULL || port->lun_map_size < size) {
3585 		port->lun_map_size = 0;
3586 		free(port->lun_map, M_CTL);
3587 		port->lun_map = malloc(size * sizeof(uint32_t),
3588 		    M_CTL, M_NOWAIT);
3589 	}
3590 	if (port->lun_map == NULL)
3591 		return (ENOMEM);
3592 	for (i = 0; i < size; i++)
3593 		port->lun_map[i] = UINT32_MAX;
3594 	port->lun_map_size = size;
3595 	if (port->status & CTL_PORT_STATUS_ONLINE) {
3596 		if (port->lun_disable != NULL) {
3597 			STAILQ_FOREACH(lun, &softc->lun_list, links)
3598 				port->lun_disable(port->targ_lun_arg, lun->lun);
3599 		}
3600 		ctl_isc_announce_port(port);
3601 	}
3602 	return (0);
3603 }
3604 
3605 int
3606 ctl_lun_map_deinit(struct ctl_port *port)
3607 {
3608 	struct ctl_softc *softc = port->ctl_softc;
3609 	struct ctl_lun *lun;
3610 
3611 	if (port->lun_map == NULL)
3612 		return (0);
3613 	port->lun_map_size = 0;
3614 	free(port->lun_map, M_CTL);
3615 	port->lun_map = NULL;
3616 	if (port->status & CTL_PORT_STATUS_ONLINE) {
3617 		if (port->lun_enable != NULL) {
3618 			STAILQ_FOREACH(lun, &softc->lun_list, links)
3619 				port->lun_enable(port->targ_lun_arg, lun->lun);
3620 		}
3621 		ctl_isc_announce_port(port);
3622 	}
3623 	return (0);
3624 }
3625 
3626 int
3627 ctl_lun_map_set(struct ctl_port *port, uint32_t plun, uint32_t glun)
3628 {
3629 	int status;
3630 	uint32_t old;
3631 
3632 	if (port->lun_map == NULL) {
3633 		status = ctl_lun_map_init(port);
3634 		if (status != 0)
3635 			return (status);
3636 	}
3637 	if (plun >= port->lun_map_size)
3638 		return (EINVAL);
3639 	old = port->lun_map[plun];
3640 	port->lun_map[plun] = glun;
3641 	if ((port->status & CTL_PORT_STATUS_ONLINE) && old == UINT32_MAX) {
3642 		if (port->lun_enable != NULL)
3643 			port->lun_enable(port->targ_lun_arg, plun);
3644 		ctl_isc_announce_port(port);
3645 	}
3646 	return (0);
3647 }
3648 
3649 int
3650 ctl_lun_map_unset(struct ctl_port *port, uint32_t plun)
3651 {
3652 	uint32_t old;
3653 
3654 	if (port->lun_map == NULL || plun >= port->lun_map_size)
3655 		return (0);
3656 	old = port->lun_map[plun];
3657 	port->lun_map[plun] = UINT32_MAX;
3658 	if ((port->status & CTL_PORT_STATUS_ONLINE) && old != UINT32_MAX) {
3659 		if (port->lun_disable != NULL)
3660 			port->lun_disable(port->targ_lun_arg, plun);
3661 		ctl_isc_announce_port(port);
3662 	}
3663 	return (0);
3664 }
3665 
3666 uint32_t
3667 ctl_lun_map_from_port(struct ctl_port *port, uint32_t lun_id)
3668 {
3669 
3670 	if (port == NULL)
3671 		return (UINT32_MAX);
3672 	if (port->lun_map == NULL)
3673 		return (lun_id);
3674 	if (lun_id > port->lun_map_size)
3675 		return (UINT32_MAX);
3676 	return (port->lun_map[lun_id]);
3677 }
3678 
3679 uint32_t
3680 ctl_lun_map_to_port(struct ctl_port *port, uint32_t lun_id)
3681 {
3682 	uint32_t i;
3683 
3684 	if (port == NULL)
3685 		return (UINT32_MAX);
3686 	if (port->lun_map == NULL)
3687 		return (lun_id);
3688 	for (i = 0; i < port->lun_map_size; i++) {
3689 		if (port->lun_map[i] == lun_id)
3690 			return (i);
3691 	}
3692 	return (UINT32_MAX);
3693 }
3694 
3695 uint32_t
3696 ctl_decode_lun(uint64_t encoded)
3697 {
3698 	uint8_t lun[8];
3699 	uint32_t result = 0xffffffff;
3700 
3701 	be64enc(lun, encoded);
3702 	switch (lun[0] & RPL_LUNDATA_ATYP_MASK) {
3703 	case RPL_LUNDATA_ATYP_PERIPH:
3704 		if ((lun[0] & 0x3f) == 0 && lun[2] == 0 && lun[3] == 0 &&
3705 		    lun[4] == 0 && lun[5] == 0 && lun[6] == 0 && lun[7] == 0)
3706 			result = lun[1];
3707 		break;
3708 	case RPL_LUNDATA_ATYP_FLAT:
3709 		if (lun[2] == 0 && lun[3] == 0 && lun[4] == 0 && lun[5] == 0 &&
3710 		    lun[6] == 0 && lun[7] == 0)
3711 			result = ((lun[0] & 0x3f) << 8) + lun[1];
3712 		break;
3713 	case RPL_LUNDATA_ATYP_EXTLUN:
3714 		switch (lun[0] & RPL_LUNDATA_EXT_EAM_MASK) {
3715 		case 0x02:
3716 			switch (lun[0] & RPL_LUNDATA_EXT_LEN_MASK) {
3717 			case 0x00:
3718 				result = lun[1];
3719 				break;
3720 			case 0x10:
3721 				result = (lun[1] << 16) + (lun[2] << 8) +
3722 				    lun[3];
3723 				break;
3724 			case 0x20:
3725 				if (lun[1] == 0 && lun[6] == 0 && lun[7] == 0)
3726 					result = (lun[2] << 24) +
3727 					    (lun[3] << 16) + (lun[4] << 8) +
3728 					    lun[5];
3729 				break;
3730 			}
3731 			break;
3732 		case RPL_LUNDATA_EXT_EAM_NOT_SPEC:
3733 			result = 0xffffffff;
3734 			break;
3735 		}
3736 		break;
3737 	}
3738 	return (result);
3739 }
3740 
3741 uint64_t
3742 ctl_encode_lun(uint32_t decoded)
3743 {
3744 	uint64_t l = decoded;
3745 
3746 	if (l <= 0xff)
3747 		return (((uint64_t)RPL_LUNDATA_ATYP_PERIPH << 56) | (l << 48));
3748 	if (l <= 0x3fff)
3749 		return (((uint64_t)RPL_LUNDATA_ATYP_FLAT << 56) | (l << 48));
3750 	if (l <= 0xffffff)
3751 		return (((uint64_t)(RPL_LUNDATA_ATYP_EXTLUN | 0x12) << 56) |
3752 		    (l << 32));
3753 	return ((((uint64_t)RPL_LUNDATA_ATYP_EXTLUN | 0x22) << 56) | (l << 16));
3754 }
3755 
3756 int
3757 ctl_ffz(uint32_t *mask, uint32_t first, uint32_t last)
3758 {
3759 	int i;
3760 
3761 	for (i = first; i < last; i++) {
3762 		if ((mask[i / 32] & (1 << (i % 32))) == 0)
3763 			return (i);
3764 	}
3765 	return (-1);
3766 }
3767 
3768 int
3769 ctl_set_mask(uint32_t *mask, uint32_t bit)
3770 {
3771 	uint32_t chunk, piece;
3772 
3773 	chunk = bit >> 5;
3774 	piece = bit % (sizeof(uint32_t) * 8);
3775 
3776 	if ((mask[chunk] & (1 << piece)) != 0)
3777 		return (-1);
3778 	else
3779 		mask[chunk] |= (1 << piece);
3780 
3781 	return (0);
3782 }
3783 
3784 int
3785 ctl_clear_mask(uint32_t *mask, uint32_t bit)
3786 {
3787 	uint32_t chunk, piece;
3788 
3789 	chunk = bit >> 5;
3790 	piece = bit % (sizeof(uint32_t) * 8);
3791 
3792 	if ((mask[chunk] & (1 << piece)) == 0)
3793 		return (-1);
3794 	else
3795 		mask[chunk] &= ~(1 << piece);
3796 
3797 	return (0);
3798 }
3799 
3800 int
3801 ctl_is_set(uint32_t *mask, uint32_t bit)
3802 {
3803 	uint32_t chunk, piece;
3804 
3805 	chunk = bit >> 5;
3806 	piece = bit % (sizeof(uint32_t) * 8);
3807 
3808 	if ((mask[chunk] & (1 << piece)) == 0)
3809 		return (0);
3810 	else
3811 		return (1);
3812 }
3813 
3814 static uint64_t
3815 ctl_get_prkey(struct ctl_lun *lun, uint32_t residx)
3816 {
3817 	uint64_t *t;
3818 
3819 	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3820 	if (t == NULL)
3821 		return (0);
3822 	return (t[residx % CTL_MAX_INIT_PER_PORT]);
3823 }
3824 
3825 static void
3826 ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx)
3827 {
3828 	uint64_t *t;
3829 
3830 	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3831 	if (t == NULL)
3832 		return;
3833 	t[residx % CTL_MAX_INIT_PER_PORT] = 0;
3834 }
3835 
3836 static void
3837 ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx)
3838 {
3839 	uint64_t *p;
3840 	u_int i;
3841 
3842 	i = residx/CTL_MAX_INIT_PER_PORT;
3843 	if (lun->pr_keys[i] != NULL)
3844 		return;
3845 	mtx_unlock(&lun->lun_lock);
3846 	p = malloc(sizeof(uint64_t) * CTL_MAX_INIT_PER_PORT, M_CTL,
3847 	    M_WAITOK | M_ZERO);
3848 	mtx_lock(&lun->lun_lock);
3849 	if (lun->pr_keys[i] == NULL)
3850 		lun->pr_keys[i] = p;
3851 	else
3852 		free(p, M_CTL);
3853 }
3854 
3855 static void
3856 ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key)
3857 {
3858 	uint64_t *t;
3859 
3860 	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3861 	KASSERT(t != NULL, ("prkey %d is not allocated", residx));
3862 	t[residx % CTL_MAX_INIT_PER_PORT] = key;
3863 }
3864 
3865 /*
3866  * ctl_softc, pool_name, total_ctl_io are passed in.
3867  * npool is passed out.
3868  */
3869 int
3870 ctl_pool_create(struct ctl_softc *ctl_softc, const char *pool_name,
3871 		uint32_t total_ctl_io, void **npool)
3872 {
3873 	struct ctl_io_pool *pool;
3874 
3875 	pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3876 					    M_NOWAIT | M_ZERO);
3877 	if (pool == NULL)
3878 		return (ENOMEM);
3879 
3880 	snprintf(pool->name, sizeof(pool->name), "CTL IO %s", pool_name);
3881 	pool->ctl_softc = ctl_softc;
3882 #ifdef IO_POOLS
3883 	pool->zone = uma_zsecond_create(pool->name, NULL,
3884 	    NULL, NULL, NULL, ctl_softc->io_zone);
3885 	/* uma_prealloc(pool->zone, total_ctl_io); */
3886 #else
3887 	pool->zone = ctl_softc->io_zone;
3888 #endif
3889 
3890 	*npool = pool;
3891 	return (0);
3892 }
3893 
3894 void
3895 ctl_pool_free(struct ctl_io_pool *pool)
3896 {
3897 
3898 	if (pool == NULL)
3899 		return;
3900 
3901 #ifdef IO_POOLS
3902 	uma_zdestroy(pool->zone);
3903 #endif
3904 	free(pool, M_CTL);
3905 }
3906 
3907 union ctl_io *
3908 ctl_alloc_io(void *pool_ref)
3909 {
3910 	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3911 	union ctl_io *io;
3912 
3913 	io = uma_zalloc(pool->zone, M_WAITOK);
3914 	if (io != NULL) {
3915 		io->io_hdr.pool = pool_ref;
3916 		CTL_SOFTC(io) = pool->ctl_softc;
3917 		TAILQ_INIT(&io->io_hdr.blocked_queue);
3918 	}
3919 	return (io);
3920 }
3921 
3922 union ctl_io *
3923 ctl_alloc_io_nowait(void *pool_ref)
3924 {
3925 	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3926 	union ctl_io *io;
3927 
3928 	io = uma_zalloc(pool->zone, M_NOWAIT);
3929 	if (io != NULL) {
3930 		io->io_hdr.pool = pool_ref;
3931 		CTL_SOFTC(io) = pool->ctl_softc;
3932 		TAILQ_INIT(&io->io_hdr.blocked_queue);
3933 	}
3934 	return (io);
3935 }
3936 
3937 void
3938 ctl_free_io(union ctl_io *io)
3939 {
3940 	struct ctl_io_pool *pool;
3941 
3942 	if (io == NULL)
3943 		return;
3944 
3945 	pool = (struct ctl_io_pool *)io->io_hdr.pool;
3946 	uma_zfree(pool->zone, io);
3947 }
3948 
3949 void
3950 ctl_zero_io(union ctl_io *io)
3951 {
3952 	struct ctl_io_pool *pool;
3953 
3954 	if (io == NULL)
3955 		return;
3956 
3957 	/*
3958 	 * May need to preserve linked list pointers at some point too.
3959 	 */
3960 	pool = io->io_hdr.pool;
3961 	memset(io, 0, sizeof(*io));
3962 	io->io_hdr.pool = pool;
3963 	CTL_SOFTC(io) = pool->ctl_softc;
3964 	TAILQ_INIT(&io->io_hdr.blocked_queue);
3965 }
3966 
3967 int
3968 ctl_expand_number(const char *buf, uint64_t *num)
3969 {
3970 	char *endptr;
3971 	uint64_t number;
3972 	unsigned shift;
3973 
3974 	number = strtoq(buf, &endptr, 0);
3975 
3976 	switch (tolower((unsigned char)*endptr)) {
3977 	case 'e':
3978 		shift = 60;
3979 		break;
3980 	case 'p':
3981 		shift = 50;
3982 		break;
3983 	case 't':
3984 		shift = 40;
3985 		break;
3986 	case 'g':
3987 		shift = 30;
3988 		break;
3989 	case 'm':
3990 		shift = 20;
3991 		break;
3992 	case 'k':
3993 		shift = 10;
3994 		break;
3995 	case 'b':
3996 	case '\0': /* No unit. */
3997 		*num = number;
3998 		return (0);
3999 	default:
4000 		/* Unrecognized unit. */
4001 		return (-1);
4002 	}
4003 
4004 	if ((number << shift) >> shift != number) {
4005 		/* Overflow */
4006 		return (-1);
4007 	}
4008 	*num = number << shift;
4009 	return (0);
4010 }
4011 
4012 /*
4013  * This routine could be used in the future to load default and/or saved
4014  * mode page parameters for a particuar lun.
4015  */
4016 static int
4017 ctl_init_page_index(struct ctl_lun *lun)
4018 {
4019 	int i, page_code;
4020 	struct ctl_page_index *page_index;
4021 	const char *value;
4022 	uint64_t ival;
4023 
4024 	memcpy(&lun->mode_pages.index, page_index_template,
4025 	       sizeof(page_index_template));
4026 
4027 	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
4028 		page_index = &lun->mode_pages.index[i];
4029 		if (lun->be_lun->lun_type == T_DIRECT &&
4030 		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
4031 			continue;
4032 		if (lun->be_lun->lun_type == T_PROCESSOR &&
4033 		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
4034 			continue;
4035 		if (lun->be_lun->lun_type == T_CDROM &&
4036 		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
4037 			continue;
4038 
4039 		page_code = page_index->page_code & SMPH_PC_MASK;
4040 		switch (page_code) {
4041 		case SMS_RW_ERROR_RECOVERY_PAGE: {
4042 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4043 			    ("subpage %#x for page %#x is incorrect!",
4044 			    page_index->subpage, page_code));
4045 			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT],
4046 			       &rw_er_page_default,
4047 			       sizeof(rw_er_page_default));
4048 			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CHANGEABLE],
4049 			       &rw_er_page_changeable,
4050 			       sizeof(rw_er_page_changeable));
4051 			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_DEFAULT],
4052 			       &rw_er_page_default,
4053 			       sizeof(rw_er_page_default));
4054 			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_SAVED],
4055 			       &rw_er_page_default,
4056 			       sizeof(rw_er_page_default));
4057 			page_index->page_data =
4058 				(uint8_t *)lun->mode_pages.rw_er_page;
4059 			break;
4060 		}
4061 		case SMS_VERIFY_ERROR_RECOVERY_PAGE: {
4062 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4063 			    ("subpage %#x for page %#x is incorrect!",
4064 			    page_index->subpage, page_code));
4065 			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_CURRENT],
4066 			       &verify_er_page_default,
4067 			       sizeof(verify_er_page_default));
4068 			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_CHANGEABLE],
4069 			       &verify_er_page_changeable,
4070 			       sizeof(verify_er_page_changeable));
4071 			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_DEFAULT],
4072 			       &verify_er_page_default,
4073 			       sizeof(verify_er_page_default));
4074 			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_SAVED],
4075 			       &verify_er_page_default,
4076 			       sizeof(verify_er_page_default));
4077 			page_index->page_data =
4078 				(uint8_t *)lun->mode_pages.verify_er_page;
4079 			break;
4080 		}
4081 		case SMS_CACHING_PAGE: {
4082 			struct scsi_caching_page *caching_page;
4083 
4084 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4085 			    ("subpage %#x for page %#x is incorrect!",
4086 			    page_index->subpage, page_code));
4087 			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4088 			       &caching_page_default,
4089 			       sizeof(caching_page_default));
4090 			memcpy(&lun->mode_pages.caching_page[
4091 			       CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4092 			       sizeof(caching_page_changeable));
4093 			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4094 			       &caching_page_default,
4095 			       sizeof(caching_page_default));
4096 			caching_page = &lun->mode_pages.caching_page[
4097 			    CTL_PAGE_SAVED];
4098 			value = dnvlist_get_string(lun->be_lun->options,
4099 			    "writecache", NULL);
4100 			if (value != NULL && strcmp(value, "off") == 0)
4101 				caching_page->flags1 &= ~SCP_WCE;
4102 			value = dnvlist_get_string(lun->be_lun->options,
4103 			    "readcache", NULL);
4104 			if (value != NULL && strcmp(value, "off") == 0)
4105 				caching_page->flags1 |= SCP_RCD;
4106 			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4107 			       &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4108 			       sizeof(caching_page_default));
4109 			page_index->page_data =
4110 				(uint8_t *)lun->mode_pages.caching_page;
4111 			break;
4112 		}
4113 		case SMS_CONTROL_MODE_PAGE: {
4114 			switch (page_index->subpage) {
4115 			case SMS_SUBPAGE_PAGE_0: {
4116 				struct scsi_control_page *control_page;
4117 
4118 				memcpy(&lun->mode_pages.control_page[
4119 				    CTL_PAGE_DEFAULT],
4120 				       &control_page_default,
4121 				       sizeof(control_page_default));
4122 				memcpy(&lun->mode_pages.control_page[
4123 				    CTL_PAGE_CHANGEABLE],
4124 				       &control_page_changeable,
4125 				       sizeof(control_page_changeable));
4126 				memcpy(&lun->mode_pages.control_page[
4127 				    CTL_PAGE_SAVED],
4128 				       &control_page_default,
4129 				       sizeof(control_page_default));
4130 				control_page = &lun->mode_pages.control_page[
4131 				    CTL_PAGE_SAVED];
4132 				value = dnvlist_get_string(lun->be_lun->options,
4133 				    "reordering", NULL);
4134 				if (value != NULL &&
4135 				    strcmp(value, "unrestricted") == 0) {
4136 					control_page->queue_flags &=
4137 					    ~SCP_QUEUE_ALG_MASK;
4138 					control_page->queue_flags |=
4139 					    SCP_QUEUE_ALG_UNRESTRICTED;
4140 				}
4141 				memcpy(&lun->mode_pages.control_page[
4142 				    CTL_PAGE_CURRENT],
4143 				       &lun->mode_pages.control_page[
4144 				    CTL_PAGE_SAVED],
4145 				       sizeof(control_page_default));
4146 				page_index->page_data =
4147 				    (uint8_t *)lun->mode_pages.control_page;
4148 				break;
4149 			}
4150 			case 0x01:
4151 				memcpy(&lun->mode_pages.control_ext_page[
4152 				    CTL_PAGE_DEFAULT],
4153 				       &control_ext_page_default,
4154 				       sizeof(control_ext_page_default));
4155 				memcpy(&lun->mode_pages.control_ext_page[
4156 				    CTL_PAGE_CHANGEABLE],
4157 				       &control_ext_page_changeable,
4158 				       sizeof(control_ext_page_changeable));
4159 				memcpy(&lun->mode_pages.control_ext_page[
4160 				    CTL_PAGE_SAVED],
4161 				       &control_ext_page_default,
4162 				       sizeof(control_ext_page_default));
4163 				memcpy(&lun->mode_pages.control_ext_page[
4164 				    CTL_PAGE_CURRENT],
4165 				       &lun->mode_pages.control_ext_page[
4166 				    CTL_PAGE_SAVED],
4167 				       sizeof(control_ext_page_default));
4168 				page_index->page_data =
4169 				    (uint8_t *)lun->mode_pages.control_ext_page;
4170 				break;
4171 			default:
4172 				panic("subpage %#x for page %#x is incorrect!",
4173 				      page_index->subpage, page_code);
4174 			}
4175 			break;
4176 		}
4177 		case SMS_INFO_EXCEPTIONS_PAGE: {
4178 			switch (page_index->subpage) {
4179 			case SMS_SUBPAGE_PAGE_0:
4180 				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_CURRENT],
4181 				       &ie_page_default,
4182 				       sizeof(ie_page_default));
4183 				memcpy(&lun->mode_pages.ie_page[
4184 				       CTL_PAGE_CHANGEABLE], &ie_page_changeable,
4185 				       sizeof(ie_page_changeable));
4186 				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_DEFAULT],
4187 				       &ie_page_default,
4188 				       sizeof(ie_page_default));
4189 				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_SAVED],
4190 				       &ie_page_default,
4191 				       sizeof(ie_page_default));
4192 				page_index->page_data =
4193 					(uint8_t *)lun->mode_pages.ie_page;
4194 				break;
4195 			case 0x02: {
4196 				struct ctl_logical_block_provisioning_page *page;
4197 
4198 				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_DEFAULT],
4199 				       &lbp_page_default,
4200 				       sizeof(lbp_page_default));
4201 				memcpy(&lun->mode_pages.lbp_page[
4202 				       CTL_PAGE_CHANGEABLE], &lbp_page_changeable,
4203 				       sizeof(lbp_page_changeable));
4204 				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4205 				       &lbp_page_default,
4206 				       sizeof(lbp_page_default));
4207 				page = &lun->mode_pages.lbp_page[CTL_PAGE_SAVED];
4208 				value = dnvlist_get_string(lun->be_lun->options,
4209 				    "avail-threshold", NULL);
4210 				if (value != NULL &&
4211 				    ctl_expand_number(value, &ival) == 0) {
4212 					page->descr[0].flags |= SLBPPD_ENABLED |
4213 					    SLBPPD_ARMING_DEC;
4214 					if (lun->be_lun->blocksize)
4215 						ival /= lun->be_lun->blocksize;
4216 					else
4217 						ival /= 512;
4218 					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4219 					    page->descr[0].count);
4220 				}
4221 				value = dnvlist_get_string(lun->be_lun->options,
4222 				    "used-threshold", NULL);
4223 				if (value != NULL &&
4224 				    ctl_expand_number(value, &ival) == 0) {
4225 					page->descr[1].flags |= SLBPPD_ENABLED |
4226 					    SLBPPD_ARMING_INC;
4227 					if (lun->be_lun->blocksize)
4228 						ival /= lun->be_lun->blocksize;
4229 					else
4230 						ival /= 512;
4231 					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4232 					    page->descr[1].count);
4233 				}
4234 				value = dnvlist_get_string(lun->be_lun->options,
4235 				    "pool-avail-threshold", NULL);
4236 				if (value != NULL &&
4237 				    ctl_expand_number(value, &ival) == 0) {
4238 					page->descr[2].flags |= SLBPPD_ENABLED |
4239 					    SLBPPD_ARMING_DEC;
4240 					if (lun->be_lun->blocksize)
4241 						ival /= lun->be_lun->blocksize;
4242 					else
4243 						ival /= 512;
4244 					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4245 					    page->descr[2].count);
4246 				}
4247 				value = dnvlist_get_string(lun->be_lun->options,
4248 				    "pool-used-threshold", NULL);
4249 				if (value != NULL &&
4250 				    ctl_expand_number(value, &ival) == 0) {
4251 					page->descr[3].flags |= SLBPPD_ENABLED |
4252 					    SLBPPD_ARMING_INC;
4253 					if (lun->be_lun->blocksize)
4254 						ival /= lun->be_lun->blocksize;
4255 					else
4256 						ival /= 512;
4257 					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4258 					    page->descr[3].count);
4259 				}
4260 				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_CURRENT],
4261 				       &lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4262 				       sizeof(lbp_page_default));
4263 				page_index->page_data =
4264 					(uint8_t *)lun->mode_pages.lbp_page;
4265 				break;
4266 			}
4267 			default:
4268 				panic("subpage %#x for page %#x is incorrect!",
4269 				      page_index->subpage, page_code);
4270 			}
4271 			break;
4272 		}
4273 		case SMS_CDDVD_CAPS_PAGE:{
4274 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4275 			    ("subpage %#x for page %#x is incorrect!",
4276 			    page_index->subpage, page_code));
4277 			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_DEFAULT],
4278 			       &cddvd_page_default,
4279 			       sizeof(cddvd_page_default));
4280 			memcpy(&lun->mode_pages.cddvd_page[
4281 			       CTL_PAGE_CHANGEABLE], &cddvd_page_changeable,
4282 			       sizeof(cddvd_page_changeable));
4283 			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_SAVED],
4284 			       &cddvd_page_default,
4285 			       sizeof(cddvd_page_default));
4286 			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_CURRENT],
4287 			       &lun->mode_pages.cddvd_page[CTL_PAGE_SAVED],
4288 			       sizeof(cddvd_page_default));
4289 			page_index->page_data =
4290 				(uint8_t *)lun->mode_pages.cddvd_page;
4291 			break;
4292 		}
4293 		default:
4294 			panic("invalid page code value %#x", page_code);
4295 		}
4296 	}
4297 
4298 	return (CTL_RETVAL_COMPLETE);
4299 }
4300 
4301 static int
4302 ctl_init_log_page_index(struct ctl_lun *lun)
4303 {
4304 	struct ctl_page_index *page_index;
4305 	int i, j, k, prev;
4306 
4307 	memcpy(&lun->log_pages.index, log_page_index_template,
4308 	       sizeof(log_page_index_template));
4309 
4310 	prev = -1;
4311 	for (i = 0, j = 0, k = 0; i < CTL_NUM_LOG_PAGES; i++) {
4312 		page_index = &lun->log_pages.index[i];
4313 		if (lun->be_lun->lun_type == T_DIRECT &&
4314 		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
4315 			continue;
4316 		if (lun->be_lun->lun_type == T_PROCESSOR &&
4317 		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
4318 			continue;
4319 		if (lun->be_lun->lun_type == T_CDROM &&
4320 		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
4321 			continue;
4322 
4323 		if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING &&
4324 		    lun->backend->lun_attr == NULL)
4325 			continue;
4326 
4327 		if (page_index->page_code != prev) {
4328 			lun->log_pages.pages_page[j] = page_index->page_code;
4329 			prev = page_index->page_code;
4330 			j++;
4331 		}
4332 		lun->log_pages.subpages_page[k*2] = page_index->page_code;
4333 		lun->log_pages.subpages_page[k*2+1] = page_index->subpage;
4334 		k++;
4335 	}
4336 	lun->log_pages.index[0].page_data = &lun->log_pages.pages_page[0];
4337 	lun->log_pages.index[0].page_len = j;
4338 	lun->log_pages.index[1].page_data = &lun->log_pages.subpages_page[0];
4339 	lun->log_pages.index[1].page_len = k * 2;
4340 	lun->log_pages.index[2].page_data = (uint8_t *)&lun->log_pages.temp_page;
4341 	lun->log_pages.index[2].page_len = sizeof(lun->log_pages.temp_page);
4342 	lun->log_pages.index[3].page_data = &lun->log_pages.lbp_page[0];
4343 	lun->log_pages.index[3].page_len = 12*CTL_NUM_LBP_PARAMS;
4344 	lun->log_pages.index[4].page_data = (uint8_t *)&lun->log_pages.stat_page;
4345 	lun->log_pages.index[4].page_len = sizeof(lun->log_pages.stat_page);
4346 	lun->log_pages.index[5].page_data = (uint8_t *)&lun->log_pages.ie_page;
4347 	lun->log_pages.index[5].page_len = sizeof(lun->log_pages.ie_page);
4348 
4349 	return (CTL_RETVAL_COMPLETE);
4350 }
4351 
4352 static int
4353 hex2bin(const char *str, uint8_t *buf, int buf_size)
4354 {
4355 	int i;
4356 	u_char c;
4357 
4358 	memset(buf, 0, buf_size);
4359 	while (isspace(str[0]))
4360 		str++;
4361 	if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
4362 		str += 2;
4363 	buf_size *= 2;
4364 	for (i = 0; str[i] != 0 && i < buf_size; i++) {
4365 		while (str[i] == '-')	/* Skip dashes in UUIDs. */
4366 			str++;
4367 		c = str[i];
4368 		if (isdigit(c))
4369 			c -= '0';
4370 		else if (isalpha(c))
4371 			c -= isupper(c) ? 'A' - 10 : 'a' - 10;
4372 		else
4373 			break;
4374 		if (c >= 16)
4375 			break;
4376 		if ((i & 1) == 0)
4377 			buf[i / 2] |= (c << 4);
4378 		else
4379 			buf[i / 2] |= c;
4380 	}
4381 	return ((i + 1) / 2);
4382 }
4383 
4384 /*
4385  * Add LUN.
4386  *
4387  * Returns 0 for success, non-zero (errno) for failure.
4388  */
4389 int
4390 ctl_add_lun(struct ctl_be_lun *be_lun)
4391 {
4392 	struct ctl_softc *ctl_softc = control_softc;
4393 	struct ctl_lun *nlun, *lun;
4394 	struct scsi_vpd_id_descriptor *desc;
4395 	struct scsi_vpd_id_t10 *t10id;
4396 	const char *eui, *naa, *scsiname, *uuid, *vendor, *value;
4397 	int lun_number;
4398 	int devidlen, idlen1, idlen2 = 0, len;
4399 
4400 	/*
4401 	 * We support only Direct Access, CD-ROM or Processor LUN types.
4402 	 */
4403 	switch (be_lun->lun_type) {
4404 	case T_DIRECT:
4405 	case T_PROCESSOR:
4406 	case T_CDROM:
4407 		break;
4408 	case T_SEQUENTIAL:
4409 	case T_CHANGER:
4410 	default:
4411 		return (EINVAL);
4412 	}
4413 	lun = malloc(sizeof(*lun), M_CTL, M_WAITOK | M_ZERO);
4414 
4415 	lun->pending_sense = malloc(sizeof(struct scsi_sense_data *) *
4416 	    ctl_max_ports, M_DEVBUF, M_WAITOK | M_ZERO);
4417 	lun->pending_ua = malloc(sizeof(ctl_ua_type *) * ctl_max_ports,
4418 	    M_DEVBUF, M_WAITOK | M_ZERO);
4419 	lun->pr_keys = malloc(sizeof(uint64_t *) * ctl_max_ports,
4420 	    M_DEVBUF, M_WAITOK | M_ZERO);
4421 
4422 	/* Generate LUN ID. */
4423 	devidlen = max(CTL_DEVID_MIN_LEN,
4424 	    strnlen(be_lun->device_id, CTL_DEVID_LEN));
4425 	idlen1 = sizeof(*t10id) + devidlen;
4426 	len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4427 	scsiname = dnvlist_get_string(be_lun->options, "scsiname", NULL);
4428 	if (scsiname != NULL) {
4429 		idlen2 = roundup2(strlen(scsiname) + 1, 4);
4430 		len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4431 	}
4432 	eui = dnvlist_get_string(be_lun->options, "eui", NULL);
4433 	if (eui != NULL) {
4434 		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4435 	}
4436 	naa = dnvlist_get_string(be_lun->options, "naa", NULL);
4437 	if (naa != NULL) {
4438 		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4439 	}
4440 	uuid = dnvlist_get_string(be_lun->options, "uuid", NULL);
4441 	if (uuid != NULL) {
4442 		len += sizeof(struct scsi_vpd_id_descriptor) + 18;
4443 	}
4444 	lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4445 	    M_CTL, M_WAITOK | M_ZERO);
4446 	desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4447 	desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4448 	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4449 	desc->length = idlen1;
4450 	t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4451 	memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4452 	if ((vendor = dnvlist_get_string(be_lun->options, "vendor", NULL)) == NULL) {
4453 		strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4454 	} else {
4455 		strncpy(t10id->vendor, vendor,
4456 		    min(sizeof(t10id->vendor), strlen(vendor)));
4457 	}
4458 	strncpy((char *)t10id->vendor_spec_id,
4459 	    (char *)be_lun->device_id, devidlen);
4460 	if (scsiname != NULL) {
4461 		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4462 		    desc->length);
4463 		desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4464 		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4465 		    SVPD_ID_TYPE_SCSI_NAME;
4466 		desc->length = idlen2;
4467 		strlcpy(desc->identifier, scsiname, idlen2);
4468 	}
4469 	if (eui != NULL) {
4470 		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4471 		    desc->length);
4472 		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4473 		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4474 		    SVPD_ID_TYPE_EUI64;
4475 		desc->length = hex2bin(eui, desc->identifier, 16);
4476 		desc->length = desc->length > 12 ? 16 :
4477 		    (desc->length > 8 ? 12 : 8);
4478 		len -= 16 - desc->length;
4479 	}
4480 	if (naa != NULL) {
4481 		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4482 		    desc->length);
4483 		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4484 		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4485 		    SVPD_ID_TYPE_NAA;
4486 		desc->length = hex2bin(naa, desc->identifier, 16);
4487 		desc->length = desc->length > 8 ? 16 : 8;
4488 		len -= 16 - desc->length;
4489 	}
4490 	if (uuid != NULL) {
4491 		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4492 		    desc->length);
4493 		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4494 		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4495 		    SVPD_ID_TYPE_UUID;
4496 		desc->identifier[0] = 0x10;
4497 		hex2bin(uuid, &desc->identifier[2], 16);
4498 		desc->length = 18;
4499 	}
4500 	lun->lun_devid->len = len;
4501 
4502 	mtx_lock(&ctl_softc->ctl_lock);
4503 	/*
4504 	 * See if the caller requested a particular LUN number.  If so, see
4505 	 * if it is available.  Otherwise, allocate the first available LUN.
4506 	 */
4507 	if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4508 		if ((be_lun->req_lun_id > (ctl_max_luns - 1))
4509 		 || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4510 			mtx_unlock(&ctl_softc->ctl_lock);
4511 			if (be_lun->req_lun_id > (ctl_max_luns - 1)) {
4512 				printf("ctl: requested LUN ID %d is higher "
4513 				       "than ctl_max_luns - 1 (%d)\n",
4514 				       be_lun->req_lun_id, ctl_max_luns - 1);
4515 			} else {
4516 				/*
4517 				 * XXX KDM return an error, or just assign
4518 				 * another LUN ID in this case??
4519 				 */
4520 				printf("ctl: requested LUN ID %d is already "
4521 				       "in use\n", be_lun->req_lun_id);
4522 			}
4523 fail:
4524 			free(lun->lun_devid, M_CTL);
4525 			free(lun, M_CTL);
4526 			return (ENOSPC);
4527 		}
4528 		lun_number = be_lun->req_lun_id;
4529 	} else {
4530 		lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, 0, ctl_max_luns);
4531 		if (lun_number == -1) {
4532 			mtx_unlock(&ctl_softc->ctl_lock);
4533 			printf("ctl: can't allocate LUN, out of LUNs\n");
4534 			goto fail;
4535 		}
4536 	}
4537 	ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4538 	mtx_unlock(&ctl_softc->ctl_lock);
4539 
4540 	mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4541 	lun->lun = lun_number;
4542 	lun->be_lun = be_lun;
4543 	/*
4544 	 * The processor LUN is always enabled.  Disk LUNs come on line
4545 	 * disabled, and must be enabled by the backend.
4546 	 */
4547 	lun->flags |= CTL_LUN_DISABLED;
4548 	lun->backend = be_lun->be;
4549 	be_lun->ctl_lun = lun;
4550 	be_lun->lun_id = lun_number;
4551 	if (be_lun->flags & CTL_LUN_FLAG_EJECTED)
4552 		lun->flags |= CTL_LUN_EJECTED;
4553 	if (be_lun->flags & CTL_LUN_FLAG_NO_MEDIA)
4554 		lun->flags |= CTL_LUN_NO_MEDIA;
4555 	if (be_lun->flags & CTL_LUN_FLAG_STOPPED)
4556 		lun->flags |= CTL_LUN_STOPPED;
4557 
4558 	if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4559 		lun->flags |= CTL_LUN_PRIMARY_SC;
4560 
4561 	value = dnvlist_get_string(be_lun->options, "removable", NULL);
4562 	if (value != NULL) {
4563 		if (strcmp(value, "on") == 0)
4564 			lun->flags |= CTL_LUN_REMOVABLE;
4565 	} else if (be_lun->lun_type == T_CDROM)
4566 		lun->flags |= CTL_LUN_REMOVABLE;
4567 
4568 	lun->ctl_softc = ctl_softc;
4569 #ifdef CTL_TIME_IO
4570 	lun->last_busy = getsbinuptime();
4571 #endif
4572 	LIST_INIT(&lun->ooa_queue);
4573 	STAILQ_INIT(&lun->error_list);
4574 	lun->ie_reported = 1;
4575 	callout_init_mtx(&lun->ie_callout, &lun->lun_lock, 0);
4576 	ctl_tpc_lun_init(lun);
4577 	if (lun->flags & CTL_LUN_REMOVABLE) {
4578 		lun->prevent = malloc((CTL_MAX_INITIATORS + 31) / 32 * 4,
4579 		    M_CTL, M_WAITOK);
4580 	}
4581 
4582 	/*
4583 	 * Initialize the mode and log page index.
4584 	 */
4585 	ctl_init_page_index(lun);
4586 	ctl_init_log_page_index(lun);
4587 
4588 	/* Setup statistics gathering */
4589 	lun->stats.item = lun_number;
4590 
4591 	/*
4592 	 * Now, before we insert this lun on the lun list, set the lun
4593 	 * inventory changed UA for all other luns.
4594 	 */
4595 	mtx_lock(&ctl_softc->ctl_lock);
4596 	STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4597 		mtx_lock(&nlun->lun_lock);
4598 		ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4599 		mtx_unlock(&nlun->lun_lock);
4600 	}
4601 	STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4602 	ctl_softc->ctl_luns[lun_number] = lun;
4603 	ctl_softc->num_luns++;
4604 	mtx_unlock(&ctl_softc->ctl_lock);
4605 
4606 	/*
4607 	 * We successfully added the LUN, attempt to enable it.
4608 	 */
4609 	if (ctl_enable_lun(lun) != 0) {
4610 		printf("%s: ctl_enable_lun() failed!\n", __func__);
4611 		mtx_lock(&ctl_softc->ctl_lock);
4612 		STAILQ_REMOVE(&ctl_softc->lun_list, lun, ctl_lun, links);
4613 		ctl_clear_mask(ctl_softc->ctl_lun_mask, lun_number);
4614 		ctl_softc->ctl_luns[lun_number] = NULL;
4615 		ctl_softc->num_luns--;
4616 		mtx_unlock(&ctl_softc->ctl_lock);
4617 		free(lun->lun_devid, M_CTL);
4618 		free(lun, M_CTL);
4619 		return (EIO);
4620 	}
4621 
4622 	return (0);
4623 }
4624 
4625 /*
4626  * Free LUN that has no active requests.
4627  */
4628 static int
4629 ctl_free_lun(struct ctl_lun *lun)
4630 {
4631 	struct ctl_softc *softc = lun->ctl_softc;
4632 	struct ctl_lun *nlun;
4633 	int i;
4634 
4635 	KASSERT(LIST_EMPTY(&lun->ooa_queue),
4636 	    ("Freeing a LUN %p with outstanding I/O!\n", lun));
4637 
4638 	mtx_lock(&softc->ctl_lock);
4639 	STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4640 	ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4641 	softc->ctl_luns[lun->lun] = NULL;
4642 	softc->num_luns--;
4643 	STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4644 		mtx_lock(&nlun->lun_lock);
4645 		ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4646 		mtx_unlock(&nlun->lun_lock);
4647 	}
4648 	mtx_unlock(&softc->ctl_lock);
4649 
4650 	/*
4651 	 * Tell the backend to free resources, if this LUN has a backend.
4652 	 */
4653 	lun->be_lun->lun_shutdown(lun->be_lun);
4654 
4655 	lun->ie_reportcnt = UINT32_MAX;
4656 	callout_drain(&lun->ie_callout);
4657 	ctl_tpc_lun_shutdown(lun);
4658 	mtx_destroy(&lun->lun_lock);
4659 	free(lun->lun_devid, M_CTL);
4660 	for (i = 0; i < ctl_max_ports; i++)
4661 		free(lun->pending_ua[i], M_CTL);
4662 	free(lun->pending_ua, M_DEVBUF);
4663 	for (i = 0; i < ctl_max_ports; i++)
4664 		free(lun->pr_keys[i], M_CTL);
4665 	free(lun->pr_keys, M_DEVBUF);
4666 	free(lun->write_buffer, M_CTL);
4667 	free(lun->prevent, M_CTL);
4668 	free(lun, M_CTL);
4669 
4670 	return (0);
4671 }
4672 
4673 static int
4674 ctl_enable_lun(struct ctl_lun *lun)
4675 {
4676 	struct ctl_softc *softc;
4677 	struct ctl_port *port, *nport;
4678 	int retval;
4679 
4680 	softc = lun->ctl_softc;
4681 
4682 	mtx_lock(&softc->ctl_lock);
4683 	mtx_lock(&lun->lun_lock);
4684 	KASSERT((lun->flags & CTL_LUN_DISABLED) != 0,
4685 	    ("%s: LUN not disabled", __func__));
4686 	lun->flags &= ~CTL_LUN_DISABLED;
4687 	mtx_unlock(&lun->lun_lock);
4688 
4689 	STAILQ_FOREACH_SAFE(port, &softc->port_list, links, nport) {
4690 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4691 		    port->lun_map != NULL || port->lun_enable == NULL)
4692 			continue;
4693 
4694 		/*
4695 		 * Drop the lock while we call the FETD's enable routine.
4696 		 * This can lead to a callback into CTL (at least in the
4697 		 * case of the internal initiator frontend.
4698 		 */
4699 		mtx_unlock(&softc->ctl_lock);
4700 		retval = port->lun_enable(port->targ_lun_arg, lun->lun);
4701 		mtx_lock(&softc->ctl_lock);
4702 		if (retval != 0) {
4703 			printf("%s: FETD %s port %d returned error "
4704 			       "%d for lun_enable on lun %jd\n",
4705 			       __func__, port->port_name, port->targ_port,
4706 			       retval, (intmax_t)lun->lun);
4707 		}
4708 	}
4709 
4710 	mtx_unlock(&softc->ctl_lock);
4711 	ctl_isc_announce_lun(lun);
4712 
4713 	return (0);
4714 }
4715 
4716 static int
4717 ctl_disable_lun(struct ctl_lun *lun)
4718 {
4719 	struct ctl_softc *softc;
4720 	struct ctl_port *port;
4721 	int retval;
4722 
4723 	softc = lun->ctl_softc;
4724 
4725 	mtx_lock(&softc->ctl_lock);
4726 	mtx_lock(&lun->lun_lock);
4727 	KASSERT((lun->flags & CTL_LUN_DISABLED) == 0,
4728 	    ("%s: LUN not enabled", __func__));
4729 	lun->flags |= CTL_LUN_DISABLED;
4730 	mtx_unlock(&lun->lun_lock);
4731 
4732 	STAILQ_FOREACH(port, &softc->port_list, links) {
4733 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4734 		    port->lun_map != NULL || port->lun_disable == NULL)
4735 			continue;
4736 
4737 		/*
4738 		 * Drop the lock before we call the frontend's disable
4739 		 * routine, to avoid lock order reversals.
4740 		 *
4741 		 * XXX KDM what happens if the frontend list changes while
4742 		 * we're traversing it?  It's unlikely, but should be handled.
4743 		 */
4744 		mtx_unlock(&softc->ctl_lock);
4745 		retval = port->lun_disable(port->targ_lun_arg, lun->lun);
4746 		mtx_lock(&softc->ctl_lock);
4747 		if (retval != 0) {
4748 			printf("%s: FETD %s port %d returned error "
4749 			       "%d for lun_disable on lun %jd\n",
4750 			       __func__, port->port_name, port->targ_port,
4751 			       retval, (intmax_t)lun->lun);
4752 		}
4753 	}
4754 
4755 	mtx_unlock(&softc->ctl_lock);
4756 	ctl_isc_announce_lun(lun);
4757 
4758 	return (0);
4759 }
4760 
4761 int
4762 ctl_start_lun(struct ctl_be_lun *be_lun)
4763 {
4764 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4765 
4766 	mtx_lock(&lun->lun_lock);
4767 	lun->flags &= ~CTL_LUN_STOPPED;
4768 	mtx_unlock(&lun->lun_lock);
4769 	return (0);
4770 }
4771 
4772 int
4773 ctl_stop_lun(struct ctl_be_lun *be_lun)
4774 {
4775 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4776 
4777 	mtx_lock(&lun->lun_lock);
4778 	lun->flags |= CTL_LUN_STOPPED;
4779 	mtx_unlock(&lun->lun_lock);
4780 	return (0);
4781 }
4782 
4783 int
4784 ctl_lun_no_media(struct ctl_be_lun *be_lun)
4785 {
4786 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4787 
4788 	mtx_lock(&lun->lun_lock);
4789 	lun->flags |= CTL_LUN_NO_MEDIA;
4790 	mtx_unlock(&lun->lun_lock);
4791 	return (0);
4792 }
4793 
4794 int
4795 ctl_lun_has_media(struct ctl_be_lun *be_lun)
4796 {
4797 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4798 	union ctl_ha_msg msg;
4799 
4800 	mtx_lock(&lun->lun_lock);
4801 	lun->flags &= ~(CTL_LUN_NO_MEDIA | CTL_LUN_EJECTED);
4802 	if (lun->flags & CTL_LUN_REMOVABLE)
4803 		ctl_est_ua_all(lun, -1, CTL_UA_MEDIUM_CHANGE);
4804 	mtx_unlock(&lun->lun_lock);
4805 	if ((lun->flags & CTL_LUN_REMOVABLE) &&
4806 	    lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
4807 		bzero(&msg.ua, sizeof(msg.ua));
4808 		msg.hdr.msg_type = CTL_MSG_UA;
4809 		msg.hdr.nexus.initid = -1;
4810 		msg.hdr.nexus.targ_port = -1;
4811 		msg.hdr.nexus.targ_lun = lun->lun;
4812 		msg.hdr.nexus.targ_mapped_lun = lun->lun;
4813 		msg.ua.ua_all = 1;
4814 		msg.ua.ua_set = 1;
4815 		msg.ua.ua_type = CTL_UA_MEDIUM_CHANGE;
4816 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
4817 		    M_WAITOK);
4818 	}
4819 	return (0);
4820 }
4821 
4822 int
4823 ctl_lun_ejected(struct ctl_be_lun *be_lun)
4824 {
4825 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4826 
4827 	mtx_lock(&lun->lun_lock);
4828 	lun->flags |= CTL_LUN_EJECTED;
4829 	mtx_unlock(&lun->lun_lock);
4830 	return (0);
4831 }
4832 
4833 int
4834 ctl_lun_primary(struct ctl_be_lun *be_lun)
4835 {
4836 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4837 
4838 	mtx_lock(&lun->lun_lock);
4839 	lun->flags |= CTL_LUN_PRIMARY_SC;
4840 	ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
4841 	mtx_unlock(&lun->lun_lock);
4842 	ctl_isc_announce_lun(lun);
4843 	return (0);
4844 }
4845 
4846 int
4847 ctl_lun_secondary(struct ctl_be_lun *be_lun)
4848 {
4849 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4850 
4851 	mtx_lock(&lun->lun_lock);
4852 	lun->flags &= ~CTL_LUN_PRIMARY_SC;
4853 	ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
4854 	mtx_unlock(&lun->lun_lock);
4855 	ctl_isc_announce_lun(lun);
4856 	return (0);
4857 }
4858 
4859 /*
4860  * Remove LUN.  If there are active requests, wait for completion.
4861  *
4862  * Returns 0 for success, non-zero (errno) for failure.
4863  * Completion is reported to backed via the lun_shutdown() method.
4864  */
4865 int
4866 ctl_remove_lun(struct ctl_be_lun *be_lun)
4867 {
4868 	struct ctl_lun *lun;
4869 
4870 	lun = (struct ctl_lun *)be_lun->ctl_lun;
4871 
4872 	ctl_disable_lun(lun);
4873 
4874 	mtx_lock(&lun->lun_lock);
4875 	lun->flags |= CTL_LUN_INVALID;
4876 
4877 	/*
4878 	 * If there is nothing in the OOA queue, go ahead and free the LUN.
4879 	 * If we have something in the OOA queue, we'll free it when the
4880 	 * last I/O completes.
4881 	 */
4882 	if (LIST_EMPTY(&lun->ooa_queue)) {
4883 		mtx_unlock(&lun->lun_lock);
4884 		ctl_free_lun(lun);
4885 	} else
4886 		mtx_unlock(&lun->lun_lock);
4887 
4888 	return (0);
4889 }
4890 
4891 void
4892 ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
4893 {
4894 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4895 	union ctl_ha_msg msg;
4896 
4897 	mtx_lock(&lun->lun_lock);
4898 	ctl_est_ua_all(lun, -1, CTL_UA_CAPACITY_CHANGE);
4899 	mtx_unlock(&lun->lun_lock);
4900 	if (lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
4901 		/* Send msg to other side. */
4902 		bzero(&msg.ua, sizeof(msg.ua));
4903 		msg.hdr.msg_type = CTL_MSG_UA;
4904 		msg.hdr.nexus.initid = -1;
4905 		msg.hdr.nexus.targ_port = -1;
4906 		msg.hdr.nexus.targ_lun = lun->lun;
4907 		msg.hdr.nexus.targ_mapped_lun = lun->lun;
4908 		msg.ua.ua_all = 1;
4909 		msg.ua.ua_set = 1;
4910 		msg.ua.ua_type = CTL_UA_CAPACITY_CHANGE;
4911 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
4912 		    M_WAITOK);
4913 	}
4914 }
4915 
4916 /*
4917  * Backend "memory move is complete" callback for requests that never
4918  * make it down to say RAIDCore's configuration code.
4919  */
4920 int
4921 ctl_config_move_done(union ctl_io *io, bool samethr)
4922 {
4923 	int retval;
4924 
4925 	CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
4926 	KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
4927 	    ("%s: unexpected I/O type %x", __func__, io->io_hdr.io_type));
4928 
4929 	if (ctl_debug & CTL_DEBUG_CDB_DATA)
4930 		ctl_data_print(io);
4931 	if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN) ||
4932 	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
4933 	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) ||
4934 	    ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
4935 		/*
4936 		 * XXX KDM just assuming a single pointer here, and not a
4937 		 * S/G list.  If we start using S/G lists for config data,
4938 		 * we'll need to know how to clean them up here as well.
4939 		 */
4940 		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
4941 			free(io->scsiio.kern_data_ptr, M_CTL);
4942 		ctl_done(io);
4943 		retval = CTL_RETVAL_COMPLETE;
4944 	} else {
4945 		/*
4946 		 * XXX KDM now we need to continue data movement.  Some
4947 		 * options:
4948 		 * - call ctl_scsiio() again?  We don't do this for data
4949 		 *   writes, because for those at least we know ahead of
4950 		 *   time where the write will go and how long it is.  For
4951 		 *   config writes, though, that information is largely
4952 		 *   contained within the write itself, thus we need to
4953 		 *   parse out the data again.
4954 		 *
4955 		 * - Call some other function once the data is in?
4956 		 */
4957 
4958 		/*
4959 		 * XXX KDM call ctl_scsiio() again for now, and check flag
4960 		 * bits to see whether we're allocated or not.
4961 		 */
4962 		retval = ctl_scsiio(&io->scsiio);
4963 	}
4964 	return (retval);
4965 }
4966 
4967 /*
4968  * This gets called by a backend driver when it is done with a
4969  * data_submit method.
4970  */
4971 void
4972 ctl_data_submit_done(union ctl_io *io)
4973 {
4974 	/*
4975 	 * If the IO_CONT flag is set, we need to call the supplied
4976 	 * function to continue processing the I/O, instead of completing
4977 	 * the I/O just yet.
4978 	 *
4979 	 * If there is an error, though, we don't want to keep processing.
4980 	 * Instead, just send status back to the initiator.
4981 	 */
4982 	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
4983 	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
4984 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
4985 	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
4986 		io->scsiio.io_cont(io);
4987 		return;
4988 	}
4989 	ctl_done(io);
4990 }
4991 
4992 /*
4993  * This gets called by a backend driver when it is done with a
4994  * configuration write.
4995  */
4996 void
4997 ctl_config_write_done(union ctl_io *io)
4998 {
4999 	uint8_t *buf;
5000 
5001 	/*
5002 	 * If the IO_CONT flag is set, we need to call the supplied
5003 	 * function to continue processing the I/O, instead of completing
5004 	 * the I/O just yet.
5005 	 *
5006 	 * If there is an error, though, we don't want to keep processing.
5007 	 * Instead, just send status back to the initiator.
5008 	 */
5009 	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5010 	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5011 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5012 	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5013 		io->scsiio.io_cont(io);
5014 		return;
5015 	}
5016 	/*
5017 	 * Since a configuration write can be done for commands that actually
5018 	 * have data allocated, like write buffer, and commands that have
5019 	 * no data, like start/stop unit, we need to check here.
5020 	 */
5021 	if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5022 		buf = io->scsiio.kern_data_ptr;
5023 	else
5024 		buf = NULL;
5025 	ctl_done(io);
5026 	if (buf)
5027 		free(buf, M_CTL);
5028 }
5029 
5030 void
5031 ctl_config_read_done(union ctl_io *io)
5032 {
5033 	uint8_t *buf;
5034 
5035 	/*
5036 	 * If there is some error -- we are done, skip data transfer.
5037 	 */
5038 	if ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0 ||
5039 	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5040 	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)) {
5041 		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5042 			buf = io->scsiio.kern_data_ptr;
5043 		else
5044 			buf = NULL;
5045 		ctl_done(io);
5046 		if (buf)
5047 			free(buf, M_CTL);
5048 		return;
5049 	}
5050 
5051 	/*
5052 	 * If the IO_CONT flag is set, we need to call the supplied
5053 	 * function to continue processing the I/O, instead of completing
5054 	 * the I/O just yet.
5055 	 */
5056 	if (io->io_hdr.flags & CTL_FLAG_IO_CONT) {
5057 		io->scsiio.io_cont(io);
5058 		return;
5059 	}
5060 
5061 	ctl_datamove(io);
5062 }
5063 
5064 /*
5065  * SCSI release command.
5066  */
5067 int
5068 ctl_scsi_release(struct ctl_scsiio *ctsio)
5069 {
5070 	struct ctl_lun *lun = CTL_LUN(ctsio);
5071 	uint32_t residx;
5072 
5073 	CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5074 
5075 	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5076 
5077 	/*
5078 	 * XXX KDM right now, we only support LUN reservation.  We don't
5079 	 * support 3rd party reservations, or extent reservations, which
5080 	 * might actually need the parameter list.  If we've gotten this
5081 	 * far, we've got a LUN reservation.  Anything else got kicked out
5082 	 * above.  So, according to SPC, ignore the length.
5083 	 */
5084 
5085 	mtx_lock(&lun->lun_lock);
5086 
5087 	/*
5088 	 * According to SPC, it is not an error for an intiator to attempt
5089 	 * to release a reservation on a LUN that isn't reserved, or that
5090 	 * is reserved by another initiator.  The reservation can only be
5091 	 * released, though, by the initiator who made it or by one of
5092 	 * several reset type events.
5093 	 */
5094 	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
5095 			lun->flags &= ~CTL_LUN_RESERVED;
5096 
5097 	mtx_unlock(&lun->lun_lock);
5098 
5099 	ctl_set_success(ctsio);
5100 	ctl_done((union ctl_io *)ctsio);
5101 	return (CTL_RETVAL_COMPLETE);
5102 }
5103 
5104 int
5105 ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5106 {
5107 	struct ctl_lun *lun = CTL_LUN(ctsio);
5108 	uint32_t residx;
5109 
5110 	CTL_DEBUG_PRINT(("ctl_reserve\n"));
5111 
5112 	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5113 
5114 	/*
5115 	 * XXX KDM right now, we only support LUN reservation.  We don't
5116 	 * support 3rd party reservations, or extent reservations, which
5117 	 * might actually need the parameter list.  If we've gotten this
5118 	 * far, we've got a LUN reservation.  Anything else got kicked out
5119 	 * above.  So, according to SPC, ignore the length.
5120 	 */
5121 
5122 	mtx_lock(&lun->lun_lock);
5123 	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
5124 		ctl_set_reservation_conflict(ctsio);
5125 		goto bailout;
5126 	}
5127 
5128 	/* SPC-3 exceptions to SPC-2 RESERVE and RELEASE behavior. */
5129 	if (lun->flags & CTL_LUN_PR_RESERVED) {
5130 		ctl_set_success(ctsio);
5131 		goto bailout;
5132 	}
5133 
5134 	lun->flags |= CTL_LUN_RESERVED;
5135 	lun->res_idx = residx;
5136 	ctl_set_success(ctsio);
5137 
5138 bailout:
5139 	mtx_unlock(&lun->lun_lock);
5140 	ctl_done((union ctl_io *)ctsio);
5141 	return (CTL_RETVAL_COMPLETE);
5142 }
5143 
5144 int
5145 ctl_start_stop(struct ctl_scsiio *ctsio)
5146 {
5147 	struct ctl_lun *lun = CTL_LUN(ctsio);
5148 	struct scsi_start_stop_unit *cdb;
5149 	int retval;
5150 
5151 	CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5152 
5153 	cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5154 
5155 	if ((cdb->how & SSS_PC_MASK) == 0) {
5156 		if ((lun->flags & CTL_LUN_PR_RESERVED) &&
5157 		    (cdb->how & SSS_START) == 0) {
5158 			uint32_t residx;
5159 
5160 			residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5161 			if (ctl_get_prkey(lun, residx) == 0 ||
5162 			    (lun->pr_res_idx != residx && lun->pr_res_type < 4)) {
5163 				ctl_set_reservation_conflict(ctsio);
5164 				ctl_done((union ctl_io *)ctsio);
5165 				return (CTL_RETVAL_COMPLETE);
5166 			}
5167 		}
5168 
5169 		if ((cdb->how & SSS_LOEJ) &&
5170 		    (lun->flags & CTL_LUN_REMOVABLE) == 0) {
5171 			ctl_set_invalid_field(ctsio,
5172 					      /*sks_valid*/ 1,
5173 					      /*command*/ 1,
5174 					      /*field*/ 4,
5175 					      /*bit_valid*/ 1,
5176 					      /*bit*/ 1);
5177 			ctl_done((union ctl_io *)ctsio);
5178 			return (CTL_RETVAL_COMPLETE);
5179 		}
5180 
5181 		if ((cdb->how & SSS_START) == 0 && (cdb->how & SSS_LOEJ) &&
5182 		    lun->prevent_count > 0) {
5183 			/* "Medium removal prevented" */
5184 			ctl_set_sense(ctsio, /*current_error*/ 1,
5185 			    /*sense_key*/(lun->flags & CTL_LUN_NO_MEDIA) ?
5186 			     SSD_KEY_NOT_READY : SSD_KEY_ILLEGAL_REQUEST,
5187 			    /*asc*/ 0x53, /*ascq*/ 0x02, SSD_ELEM_NONE);
5188 			ctl_done((union ctl_io *)ctsio);
5189 			return (CTL_RETVAL_COMPLETE);
5190 		}
5191 	}
5192 
5193 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5194 	return (retval);
5195 }
5196 
5197 int
5198 ctl_prevent_allow(struct ctl_scsiio *ctsio)
5199 {
5200 	struct ctl_lun *lun = CTL_LUN(ctsio);
5201 	struct scsi_prevent *cdb;
5202 	int retval;
5203 	uint32_t initidx;
5204 
5205 	CTL_DEBUG_PRINT(("ctl_prevent_allow\n"));
5206 
5207 	cdb = (struct scsi_prevent *)ctsio->cdb;
5208 
5209 	if ((lun->flags & CTL_LUN_REMOVABLE) == 0 || lun->prevent == NULL) {
5210 		ctl_set_invalid_opcode(ctsio);
5211 		ctl_done((union ctl_io *)ctsio);
5212 		return (CTL_RETVAL_COMPLETE);
5213 	}
5214 
5215 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5216 	mtx_lock(&lun->lun_lock);
5217 	if ((cdb->how & PR_PREVENT) &&
5218 	    ctl_is_set(lun->prevent, initidx) == 0) {
5219 		ctl_set_mask(lun->prevent, initidx);
5220 		lun->prevent_count++;
5221 	} else if ((cdb->how & PR_PREVENT) == 0 &&
5222 	    ctl_is_set(lun->prevent, initidx)) {
5223 		ctl_clear_mask(lun->prevent, initidx);
5224 		lun->prevent_count--;
5225 	}
5226 	mtx_unlock(&lun->lun_lock);
5227 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5228 	return (retval);
5229 }
5230 
5231 /*
5232  * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5233  * we don't really do anything with the LBA and length fields if the user
5234  * passes them in.  Instead we'll just flush out the cache for the entire
5235  * LUN.
5236  */
5237 int
5238 ctl_sync_cache(struct ctl_scsiio *ctsio)
5239 {
5240 	struct ctl_lun *lun = CTL_LUN(ctsio);
5241 	struct ctl_lba_len_flags *lbalen;
5242 	uint64_t starting_lba;
5243 	uint32_t block_count;
5244 	int retval;
5245 	uint8_t byte2;
5246 
5247 	CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5248 
5249 	retval = 0;
5250 
5251 	switch (ctsio->cdb[0]) {
5252 	case SYNCHRONIZE_CACHE: {
5253 		struct scsi_sync_cache *cdb;
5254 		cdb = (struct scsi_sync_cache *)ctsio->cdb;
5255 
5256 		starting_lba = scsi_4btoul(cdb->begin_lba);
5257 		block_count = scsi_2btoul(cdb->lb_count);
5258 		byte2 = cdb->byte2;
5259 		break;
5260 	}
5261 	case SYNCHRONIZE_CACHE_16: {
5262 		struct scsi_sync_cache_16 *cdb;
5263 		cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5264 
5265 		starting_lba = scsi_8btou64(cdb->begin_lba);
5266 		block_count = scsi_4btoul(cdb->lb_count);
5267 		byte2 = cdb->byte2;
5268 		break;
5269 	}
5270 	default:
5271 		ctl_set_invalid_opcode(ctsio);
5272 		ctl_done((union ctl_io *)ctsio);
5273 		goto bailout;
5274 		break; /* NOTREACHED */
5275 	}
5276 
5277 	/*
5278 	 * We check the LBA and length, but don't do anything with them.
5279 	 * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5280 	 * get flushed.  This check will just help satisfy anyone who wants
5281 	 * to see an error for an out of range LBA.
5282 	 */
5283 	if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5284 		ctl_set_lba_out_of_range(ctsio,
5285 		    MAX(starting_lba, lun->be_lun->maxlba + 1));
5286 		ctl_done((union ctl_io *)ctsio);
5287 		goto bailout;
5288 	}
5289 
5290 	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5291 	lbalen->lba = starting_lba;
5292 	lbalen->len = block_count;
5293 	lbalen->flags = byte2;
5294 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5295 
5296 bailout:
5297 	return (retval);
5298 }
5299 
5300 int
5301 ctl_format(struct ctl_scsiio *ctsio)
5302 {
5303 	struct scsi_format *cdb;
5304 	int length, defect_list_len;
5305 
5306 	CTL_DEBUG_PRINT(("ctl_format\n"));
5307 
5308 	cdb = (struct scsi_format *)ctsio->cdb;
5309 
5310 	length = 0;
5311 	if (cdb->byte2 & SF_FMTDATA) {
5312 		if (cdb->byte2 & SF_LONGLIST)
5313 			length = sizeof(struct scsi_format_header_long);
5314 		else
5315 			length = sizeof(struct scsi_format_header_short);
5316 	}
5317 
5318 	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5319 	 && (length > 0)) {
5320 		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5321 		ctsio->kern_data_len = length;
5322 		ctsio->kern_total_len = length;
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 	defect_list_len = 0;
5333 
5334 	if (cdb->byte2 & SF_FMTDATA) {
5335 		if (cdb->byte2 & SF_LONGLIST) {
5336 			struct scsi_format_header_long *header;
5337 
5338 			header = (struct scsi_format_header_long *)
5339 				ctsio->kern_data_ptr;
5340 
5341 			defect_list_len = scsi_4btoul(header->defect_list_len);
5342 			if (defect_list_len != 0) {
5343 				ctl_set_invalid_field(ctsio,
5344 						      /*sks_valid*/ 1,
5345 						      /*command*/ 0,
5346 						      /*field*/ 2,
5347 						      /*bit_valid*/ 0,
5348 						      /*bit*/ 0);
5349 				goto bailout;
5350 			}
5351 		} else {
5352 			struct scsi_format_header_short *header;
5353 
5354 			header = (struct scsi_format_header_short *)
5355 				ctsio->kern_data_ptr;
5356 
5357 			defect_list_len = scsi_2btoul(header->defect_list_len);
5358 			if (defect_list_len != 0) {
5359 				ctl_set_invalid_field(ctsio,
5360 						      /*sks_valid*/ 1,
5361 						      /*command*/ 0,
5362 						      /*field*/ 2,
5363 						      /*bit_valid*/ 0,
5364 						      /*bit*/ 0);
5365 				goto bailout;
5366 			}
5367 		}
5368 	}
5369 
5370 	ctl_set_success(ctsio);
5371 bailout:
5372 
5373 	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5374 		free(ctsio->kern_data_ptr, M_CTL);
5375 		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5376 	}
5377 
5378 	ctl_done((union ctl_io *)ctsio);
5379 	return (CTL_RETVAL_COMPLETE);
5380 }
5381 
5382 int
5383 ctl_read_buffer(struct ctl_scsiio *ctsio)
5384 {
5385 	struct ctl_lun *lun = CTL_LUN(ctsio);
5386 	uint64_t buffer_offset;
5387 	uint32_t len;
5388 	uint8_t byte2;
5389 	static uint8_t descr[4];
5390 	static uint8_t echo_descr[4] = { 0 };
5391 
5392 	CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5393 
5394 	switch (ctsio->cdb[0]) {
5395 	case READ_BUFFER: {
5396 		struct scsi_read_buffer *cdb;
5397 
5398 		cdb = (struct scsi_read_buffer *)ctsio->cdb;
5399 		buffer_offset = scsi_3btoul(cdb->offset);
5400 		len = scsi_3btoul(cdb->length);
5401 		byte2 = cdb->byte2;
5402 		break;
5403 	}
5404 	case READ_BUFFER_16: {
5405 		struct scsi_read_buffer_16 *cdb;
5406 
5407 		cdb = (struct scsi_read_buffer_16 *)ctsio->cdb;
5408 		buffer_offset = scsi_8btou64(cdb->offset);
5409 		len = scsi_4btoul(cdb->length);
5410 		byte2 = cdb->byte2;
5411 		break;
5412 	}
5413 	default: /* This shouldn't happen. */
5414 		ctl_set_invalid_opcode(ctsio);
5415 		ctl_done((union ctl_io *)ctsio);
5416 		return (CTL_RETVAL_COMPLETE);
5417 	}
5418 
5419 	if (buffer_offset > CTL_WRITE_BUFFER_SIZE ||
5420 	    buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5421 		ctl_set_invalid_field(ctsio,
5422 				      /*sks_valid*/ 1,
5423 				      /*command*/ 1,
5424 				      /*field*/ 6,
5425 				      /*bit_valid*/ 0,
5426 				      /*bit*/ 0);
5427 		ctl_done((union ctl_io *)ctsio);
5428 		return (CTL_RETVAL_COMPLETE);
5429 	}
5430 
5431 	if ((byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5432 		descr[0] = 0;
5433 		scsi_ulto3b(CTL_WRITE_BUFFER_SIZE, &descr[1]);
5434 		ctsio->kern_data_ptr = descr;
5435 		len = min(len, sizeof(descr));
5436 	} else if ((byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5437 		ctsio->kern_data_ptr = echo_descr;
5438 		len = min(len, sizeof(echo_descr));
5439 	} else {
5440 		if (lun->write_buffer == NULL) {
5441 			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5442 			    M_CTL, M_WAITOK);
5443 		}
5444 		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5445 	}
5446 	ctsio->kern_data_len = len;
5447 	ctsio->kern_total_len = len;
5448 	ctsio->kern_rel_offset = 0;
5449 	ctsio->kern_sg_entries = 0;
5450 	ctl_set_success(ctsio);
5451 	ctsio->be_move_done = ctl_config_move_done;
5452 	ctl_datamove((union ctl_io *)ctsio);
5453 	return (CTL_RETVAL_COMPLETE);
5454 }
5455 
5456 int
5457 ctl_write_buffer(struct ctl_scsiio *ctsio)
5458 {
5459 	struct ctl_lun *lun = CTL_LUN(ctsio);
5460 	struct scsi_write_buffer *cdb;
5461 	int buffer_offset, len;
5462 
5463 	CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5464 
5465 	cdb = (struct scsi_write_buffer *)ctsio->cdb;
5466 
5467 	len = scsi_3btoul(cdb->length);
5468 	buffer_offset = scsi_3btoul(cdb->offset);
5469 
5470 	if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5471 		ctl_set_invalid_field(ctsio,
5472 				      /*sks_valid*/ 1,
5473 				      /*command*/ 1,
5474 				      /*field*/ 6,
5475 				      /*bit_valid*/ 0,
5476 				      /*bit*/ 0);
5477 		ctl_done((union ctl_io *)ctsio);
5478 		return (CTL_RETVAL_COMPLETE);
5479 	}
5480 
5481 	/*
5482 	 * If we've got a kernel request that hasn't been malloced yet,
5483 	 * malloc it and tell the caller the data buffer is here.
5484 	 */
5485 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5486 		if (lun->write_buffer == NULL) {
5487 			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5488 			    M_CTL, M_WAITOK);
5489 		}
5490 		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5491 		ctsio->kern_data_len = len;
5492 		ctsio->kern_total_len = len;
5493 		ctsio->kern_rel_offset = 0;
5494 		ctsio->kern_sg_entries = 0;
5495 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5496 		ctsio->be_move_done = ctl_config_move_done;
5497 		ctl_datamove((union ctl_io *)ctsio);
5498 
5499 		return (CTL_RETVAL_COMPLETE);
5500 	}
5501 
5502 	ctl_set_success(ctsio);
5503 	ctl_done((union ctl_io *)ctsio);
5504 	return (CTL_RETVAL_COMPLETE);
5505 }
5506 
5507 static int
5508 ctl_write_same_cont(union ctl_io *io)
5509 {
5510 	struct ctl_lun *lun = CTL_LUN(io);
5511 	struct ctl_scsiio *ctsio;
5512 	struct ctl_lba_len_flags *lbalen;
5513 	int retval;
5514 
5515 	ctsio = &io->scsiio;
5516 	ctsio->io_hdr.status = CTL_STATUS_NONE;
5517 	lbalen = (struct ctl_lba_len_flags *)
5518 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5519 	lbalen->lba += lbalen->len;
5520 	if ((lun->be_lun->maxlba + 1) - lbalen->lba <= UINT32_MAX) {
5521 		ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
5522 		lbalen->len = (lun->be_lun->maxlba + 1) - lbalen->lba;
5523 	}
5524 
5525 	CTL_DEBUG_PRINT(("ctl_write_same_cont: calling config_write()\n"));
5526 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5527 	return (retval);
5528 }
5529 
5530 int
5531 ctl_write_same(struct ctl_scsiio *ctsio)
5532 {
5533 	struct ctl_lun *lun = CTL_LUN(ctsio);
5534 	struct ctl_lba_len_flags *lbalen;
5535 	const char *val;
5536 	uint64_t lba, ival;
5537 	uint32_t num_blocks;
5538 	int len, retval;
5539 	uint8_t byte2;
5540 
5541 	CTL_DEBUG_PRINT(("ctl_write_same\n"));
5542 
5543 	switch (ctsio->cdb[0]) {
5544 	case WRITE_SAME_10: {
5545 		struct scsi_write_same_10 *cdb;
5546 
5547 		cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5548 
5549 		lba = scsi_4btoul(cdb->addr);
5550 		num_blocks = scsi_2btoul(cdb->length);
5551 		byte2 = cdb->byte2;
5552 		break;
5553 	}
5554 	case WRITE_SAME_16: {
5555 		struct scsi_write_same_16 *cdb;
5556 
5557 		cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5558 
5559 		lba = scsi_8btou64(cdb->addr);
5560 		num_blocks = scsi_4btoul(cdb->length);
5561 		byte2 = cdb->byte2;
5562 		break;
5563 	}
5564 	default:
5565 		/*
5566 		 * We got a command we don't support.  This shouldn't
5567 		 * happen, commands should be filtered out above us.
5568 		 */
5569 		ctl_set_invalid_opcode(ctsio);
5570 		ctl_done((union ctl_io *)ctsio);
5571 
5572 		return (CTL_RETVAL_COMPLETE);
5573 		break; /* NOTREACHED */
5574 	}
5575 
5576 	/* ANCHOR flag can be used only together with UNMAP */
5577 	if ((byte2 & SWS_UNMAP) == 0 && (byte2 & SWS_ANCHOR) != 0) {
5578 		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
5579 		    /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
5580 		ctl_done((union ctl_io *)ctsio);
5581 		return (CTL_RETVAL_COMPLETE);
5582 	}
5583 
5584 	/*
5585 	 * The first check is to make sure we're in bounds, the second
5586 	 * check is to catch wrap-around problems.  If the lba + num blocks
5587 	 * is less than the lba, then we've wrapped around and the block
5588 	 * range is invalid anyway.
5589 	 */
5590 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5591 	 || ((lba + num_blocks) < lba)) {
5592 		ctl_set_lba_out_of_range(ctsio,
5593 		    MAX(lba, lun->be_lun->maxlba + 1));
5594 		ctl_done((union ctl_io *)ctsio);
5595 		return (CTL_RETVAL_COMPLETE);
5596 	}
5597 
5598 	/* Zero number of blocks means "to the last logical block" */
5599 	if (num_blocks == 0) {
5600 		ival = UINT64_MAX;
5601 		val = dnvlist_get_string(lun->be_lun->options,
5602 		    "write_same_max_lba", NULL);
5603 		if (val != NULL)
5604 			ctl_expand_number(val, &ival);
5605 		if ((lun->be_lun->maxlba + 1) - lba > ival) {
5606 			ctl_set_invalid_field(ctsio,
5607 			    /*sks_valid*/ 1, /*command*/ 1,
5608 			    /*field*/ ctsio->cdb[0] == WRITE_SAME_10 ? 7 : 10,
5609 			    /*bit_valid*/ 0, /*bit*/ 0);
5610 			ctl_done((union ctl_io *)ctsio);
5611 			return (CTL_RETVAL_COMPLETE);
5612 		}
5613 		if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5614 			ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
5615 			ctsio->io_cont = ctl_write_same_cont;
5616 			num_blocks = 1 << 31;
5617 		} else
5618 			num_blocks = (lun->be_lun->maxlba + 1) - lba;
5619 	}
5620 
5621 	len = lun->be_lun->blocksize;
5622 
5623 	/*
5624 	 * If we've got a kernel request that hasn't been malloced yet,
5625 	 * malloc it and tell the caller the data buffer is here.
5626 	 */
5627 	if ((byte2 & SWS_NDOB) == 0 &&
5628 	    (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5629 		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);
5630 		ctsio->kern_data_len = len;
5631 		ctsio->kern_total_len = len;
5632 		ctsio->kern_rel_offset = 0;
5633 		ctsio->kern_sg_entries = 0;
5634 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5635 		ctsio->be_move_done = ctl_config_move_done;
5636 		ctl_datamove((union ctl_io *)ctsio);
5637 
5638 		return (CTL_RETVAL_COMPLETE);
5639 	}
5640 
5641 	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5642 	lbalen->lba = lba;
5643 	lbalen->len = num_blocks;
5644 	lbalen->flags = byte2;
5645 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5646 
5647 	return (retval);
5648 }
5649 
5650 int
5651 ctl_unmap(struct ctl_scsiio *ctsio)
5652 {
5653 	struct ctl_lun *lun = CTL_LUN(ctsio);
5654 	struct scsi_unmap *cdb;
5655 	struct ctl_ptr_len_flags *ptrlen;
5656 	struct scsi_unmap_header *hdr;
5657 	struct scsi_unmap_desc *buf, *end, *endnz, *range;
5658 	uint64_t lba;
5659 	uint32_t num_blocks;
5660 	int len, retval;
5661 	uint8_t byte2;
5662 
5663 	CTL_DEBUG_PRINT(("ctl_unmap\n"));
5664 
5665 	cdb = (struct scsi_unmap *)ctsio->cdb;
5666 	len = scsi_2btoul(cdb->length);
5667 	byte2 = cdb->byte2;
5668 
5669 	/*
5670 	 * If we've got a kernel request that hasn't been malloced yet,
5671 	 * malloc it and tell the caller the data buffer is here.
5672 	 */
5673 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5674 		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);
5675 		ctsio->kern_data_len = len;
5676 		ctsio->kern_total_len = len;
5677 		ctsio->kern_rel_offset = 0;
5678 		ctsio->kern_sg_entries = 0;
5679 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5680 		ctsio->be_move_done = ctl_config_move_done;
5681 		ctl_datamove((union ctl_io *)ctsio);
5682 
5683 		return (CTL_RETVAL_COMPLETE);
5684 	}
5685 
5686 	len = ctsio->kern_total_len - ctsio->kern_data_resid;
5687 	hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
5688 	if (len < sizeof (*hdr) ||
5689 	    len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
5690 	    len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
5691 	    scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
5692 		ctl_set_invalid_field(ctsio,
5693 				      /*sks_valid*/ 0,
5694 				      /*command*/ 0,
5695 				      /*field*/ 0,
5696 				      /*bit_valid*/ 0,
5697 				      /*bit*/ 0);
5698 		goto done;
5699 	}
5700 	len = scsi_2btoul(hdr->desc_length);
5701 	buf = (struct scsi_unmap_desc *)(hdr + 1);
5702 	end = buf + len / sizeof(*buf);
5703 
5704 	endnz = buf;
5705 	for (range = buf; range < end; range++) {
5706 		lba = scsi_8btou64(range->lba);
5707 		num_blocks = scsi_4btoul(range->length);
5708 		if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5709 		 || ((lba + num_blocks) < lba)) {
5710 			ctl_set_lba_out_of_range(ctsio,
5711 			    MAX(lba, lun->be_lun->maxlba + 1));
5712 			ctl_done((union ctl_io *)ctsio);
5713 			return (CTL_RETVAL_COMPLETE);
5714 		}
5715 		if (num_blocks != 0)
5716 			endnz = range + 1;
5717 	}
5718 
5719 	/*
5720 	 * Block backend can not handle zero last range.
5721 	 * Filter it out and return if there is nothing left.
5722 	 */
5723 	len = (uint8_t *)endnz - (uint8_t *)buf;
5724 	if (len == 0) {
5725 		ctl_set_success(ctsio);
5726 		goto done;
5727 	}
5728 
5729 	mtx_lock(&lun->lun_lock);
5730 	ptrlen = (struct ctl_ptr_len_flags *)
5731 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5732 	ptrlen->ptr = (void *)buf;
5733 	ptrlen->len = len;
5734 	ptrlen->flags = byte2;
5735 	ctl_try_unblock_others(lun, (union ctl_io *)ctsio, FALSE);
5736 	mtx_unlock(&lun->lun_lock);
5737 
5738 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5739 	return (retval);
5740 
5741 done:
5742 	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5743 		free(ctsio->kern_data_ptr, M_CTL);
5744 		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5745 	}
5746 	ctl_done((union ctl_io *)ctsio);
5747 	return (CTL_RETVAL_COMPLETE);
5748 }
5749 
5750 int
5751 ctl_default_page_handler(struct ctl_scsiio *ctsio,
5752 			 struct ctl_page_index *page_index, uint8_t *page_ptr)
5753 {
5754 	struct ctl_lun *lun = CTL_LUN(ctsio);
5755 	uint8_t *current_cp;
5756 	int set_ua;
5757 	uint32_t initidx;
5758 
5759 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5760 	set_ua = 0;
5761 
5762 	current_cp = (page_index->page_data + (page_index->page_len *
5763 	    CTL_PAGE_CURRENT));
5764 
5765 	mtx_lock(&lun->lun_lock);
5766 	if (memcmp(current_cp, page_ptr, page_index->page_len)) {
5767 		memcpy(current_cp, page_ptr, page_index->page_len);
5768 		set_ua = 1;
5769 	}
5770 	if (set_ua != 0)
5771 		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
5772 	mtx_unlock(&lun->lun_lock);
5773 	if (set_ua) {
5774 		ctl_isc_announce_mode(lun,
5775 		    ctl_get_initindex(&ctsio->io_hdr.nexus),
5776 		    page_index->page_code, page_index->subpage);
5777 	}
5778 	return (CTL_RETVAL_COMPLETE);
5779 }
5780 
5781 static void
5782 ctl_ie_timer(void *arg)
5783 {
5784 	struct ctl_lun *lun = arg;
5785 	uint64_t t;
5786 
5787 	if (lun->ie_asc == 0)
5788 		return;
5789 
5790 	if (lun->MODE_IE.mrie == SIEP_MRIE_UA)
5791 		ctl_est_ua_all(lun, -1, CTL_UA_IE);
5792 	else
5793 		lun->ie_reported = 0;
5794 
5795 	if (lun->ie_reportcnt < scsi_4btoul(lun->MODE_IE.report_count)) {
5796 		lun->ie_reportcnt++;
5797 		t = scsi_4btoul(lun->MODE_IE.interval_timer);
5798 		if (t == 0 || t == UINT32_MAX)
5799 			t = 3000;  /* 5 min */
5800 		callout_schedule_sbt(&lun->ie_callout, SBT_1S / 10 * t,
5801 		    SBT_1S / 10, 0);
5802 	}
5803 }
5804 
5805 int
5806 ctl_ie_page_handler(struct ctl_scsiio *ctsio,
5807 			 struct ctl_page_index *page_index, uint8_t *page_ptr)
5808 {
5809 	struct ctl_lun *lun = CTL_LUN(ctsio);
5810 	struct scsi_info_exceptions_page *pg;
5811 	uint64_t t;
5812 
5813 	(void)ctl_default_page_handler(ctsio, page_index, page_ptr);
5814 
5815 	pg = (struct scsi_info_exceptions_page *)page_ptr;
5816 	mtx_lock(&lun->lun_lock);
5817 	if (pg->info_flags & SIEP_FLAGS_TEST) {
5818 		lun->ie_asc = 0x5d;
5819 		lun->ie_ascq = 0xff;
5820 		if (pg->mrie == SIEP_MRIE_UA) {
5821 			ctl_est_ua_all(lun, -1, CTL_UA_IE);
5822 			lun->ie_reported = 1;
5823 		} else {
5824 			ctl_clr_ua_all(lun, -1, CTL_UA_IE);
5825 			lun->ie_reported = -1;
5826 		}
5827 		lun->ie_reportcnt = 1;
5828 		if (lun->ie_reportcnt < scsi_4btoul(pg->report_count)) {
5829 			lun->ie_reportcnt++;
5830 			t = scsi_4btoul(pg->interval_timer);
5831 			if (t == 0 || t == UINT32_MAX)
5832 				t = 3000;  /* 5 min */
5833 			callout_reset_sbt(&lun->ie_callout, SBT_1S / 10 * t,
5834 			    SBT_1S / 10, ctl_ie_timer, lun, 0);
5835 		}
5836 	} else {
5837 		lun->ie_asc = 0;
5838 		lun->ie_ascq = 0;
5839 		lun->ie_reported = 1;
5840 		ctl_clr_ua_all(lun, -1, CTL_UA_IE);
5841 		lun->ie_reportcnt = UINT32_MAX;
5842 		callout_stop(&lun->ie_callout);
5843 	}
5844 	mtx_unlock(&lun->lun_lock);
5845 	return (CTL_RETVAL_COMPLETE);
5846 }
5847 
5848 static int
5849 ctl_do_mode_select(union ctl_io *io)
5850 {
5851 	struct ctl_lun *lun = CTL_LUN(io);
5852 	struct scsi_mode_page_header *page_header;
5853 	struct ctl_page_index *page_index;
5854 	struct ctl_scsiio *ctsio;
5855 	int page_len, page_len_offset, page_len_size;
5856 	union ctl_modepage_info *modepage_info;
5857 	uint16_t *len_left, *len_used;
5858 	int retval, i;
5859 
5860 	ctsio = &io->scsiio;
5861 	page_index = NULL;
5862 	page_len = 0;
5863 
5864 	modepage_info = (union ctl_modepage_info *)
5865 		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
5866 	len_left = &modepage_info->header.len_left;
5867 	len_used = &modepage_info->header.len_used;
5868 
5869 do_next_page:
5870 
5871 	page_header = (struct scsi_mode_page_header *)
5872 		(ctsio->kern_data_ptr + *len_used);
5873 
5874 	if (*len_left == 0) {
5875 		free(ctsio->kern_data_ptr, M_CTL);
5876 		ctl_set_success(ctsio);
5877 		ctl_done((union ctl_io *)ctsio);
5878 		return (CTL_RETVAL_COMPLETE);
5879 	} else if (*len_left < sizeof(struct scsi_mode_page_header)) {
5880 		free(ctsio->kern_data_ptr, M_CTL);
5881 		ctl_set_param_len_error(ctsio);
5882 		ctl_done((union ctl_io *)ctsio);
5883 		return (CTL_RETVAL_COMPLETE);
5884 
5885 	} else if ((page_header->page_code & SMPH_SPF)
5886 		&& (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
5887 		free(ctsio->kern_data_ptr, M_CTL);
5888 		ctl_set_param_len_error(ctsio);
5889 		ctl_done((union ctl_io *)ctsio);
5890 		return (CTL_RETVAL_COMPLETE);
5891 	}
5892 
5893 	/*
5894 	 * XXX KDM should we do something with the block descriptor?
5895 	 */
5896 	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
5897 		page_index = &lun->mode_pages.index[i];
5898 		if (lun->be_lun->lun_type == T_DIRECT &&
5899 		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
5900 			continue;
5901 		if (lun->be_lun->lun_type == T_PROCESSOR &&
5902 		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
5903 			continue;
5904 		if (lun->be_lun->lun_type == T_CDROM &&
5905 		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
5906 			continue;
5907 
5908 		if ((page_index->page_code & SMPH_PC_MASK) !=
5909 		    (page_header->page_code & SMPH_PC_MASK))
5910 			continue;
5911 
5912 		/*
5913 		 * If neither page has a subpage code, then we've got a
5914 		 * match.
5915 		 */
5916 		if (((page_index->page_code & SMPH_SPF) == 0)
5917 		 && ((page_header->page_code & SMPH_SPF) == 0)) {
5918 			page_len = page_header->page_length;
5919 			break;
5920 		}
5921 
5922 		/*
5923 		 * If both pages have subpages, then the subpage numbers
5924 		 * have to match.
5925 		 */
5926 		if ((page_index->page_code & SMPH_SPF)
5927 		  && (page_header->page_code & SMPH_SPF)) {
5928 			struct scsi_mode_page_header_sp *sph;
5929 
5930 			sph = (struct scsi_mode_page_header_sp *)page_header;
5931 			if (page_index->subpage == sph->subpage) {
5932 				page_len = scsi_2btoul(sph->page_length);
5933 				break;
5934 			}
5935 		}
5936 	}
5937 
5938 	/*
5939 	 * If we couldn't find the page, or if we don't have a mode select
5940 	 * handler for it, send back an error to the user.
5941 	 */
5942 	if ((i >= CTL_NUM_MODE_PAGES)
5943 	 || (page_index->select_handler == NULL)) {
5944 		ctl_set_invalid_field(ctsio,
5945 				      /*sks_valid*/ 1,
5946 				      /*command*/ 0,
5947 				      /*field*/ *len_used,
5948 				      /*bit_valid*/ 0,
5949 				      /*bit*/ 0);
5950 		free(ctsio->kern_data_ptr, M_CTL);
5951 		ctl_done((union ctl_io *)ctsio);
5952 		return (CTL_RETVAL_COMPLETE);
5953 	}
5954 
5955 	if (page_index->page_code & SMPH_SPF) {
5956 		page_len_offset = 2;
5957 		page_len_size = 2;
5958 	} else {
5959 		page_len_size = 1;
5960 		page_len_offset = 1;
5961 	}
5962 
5963 	/*
5964 	 * If the length the initiator gives us isn't the one we specify in
5965 	 * the mode page header, or if they didn't specify enough data in
5966 	 * the CDB to avoid truncating this page, kick out the request.
5967 	 */
5968 	if (page_len != page_index->page_len - page_len_offset - page_len_size) {
5969 		ctl_set_invalid_field(ctsio,
5970 				      /*sks_valid*/ 1,
5971 				      /*command*/ 0,
5972 				      /*field*/ *len_used + page_len_offset,
5973 				      /*bit_valid*/ 0,
5974 				      /*bit*/ 0);
5975 		free(ctsio->kern_data_ptr, M_CTL);
5976 		ctl_done((union ctl_io *)ctsio);
5977 		return (CTL_RETVAL_COMPLETE);
5978 	}
5979 	if (*len_left < page_index->page_len) {
5980 		free(ctsio->kern_data_ptr, M_CTL);
5981 		ctl_set_param_len_error(ctsio);
5982 		ctl_done((union ctl_io *)ctsio);
5983 		return (CTL_RETVAL_COMPLETE);
5984 	}
5985 
5986 	/*
5987 	 * Run through the mode page, checking to make sure that the bits
5988 	 * the user changed are actually legal for him to change.
5989 	 */
5990 	for (i = 0; i < page_index->page_len; i++) {
5991 		uint8_t *user_byte, *change_mask, *current_byte;
5992 		int bad_bit;
5993 		int j;
5994 
5995 		user_byte = (uint8_t *)page_header + i;
5996 		change_mask = page_index->page_data +
5997 			      (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
5998 		current_byte = page_index->page_data +
5999 			       (page_index->page_len * CTL_PAGE_CURRENT) + i;
6000 
6001 		/*
6002 		 * Check to see whether the user set any bits in this byte
6003 		 * that he is not allowed to set.
6004 		 */
6005 		if ((*user_byte & ~(*change_mask)) ==
6006 		    (*current_byte & ~(*change_mask)))
6007 			continue;
6008 
6009 		/*
6010 		 * Go through bit by bit to determine which one is illegal.
6011 		 */
6012 		bad_bit = 0;
6013 		for (j = 7; j >= 0; j--) {
6014 			if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6015 			    (((1 << i) & ~(*change_mask)) & *current_byte)) {
6016 				bad_bit = i;
6017 				break;
6018 			}
6019 		}
6020 		ctl_set_invalid_field(ctsio,
6021 				      /*sks_valid*/ 1,
6022 				      /*command*/ 0,
6023 				      /*field*/ *len_used + i,
6024 				      /*bit_valid*/ 1,
6025 				      /*bit*/ bad_bit);
6026 		free(ctsio->kern_data_ptr, M_CTL);
6027 		ctl_done((union ctl_io *)ctsio);
6028 		return (CTL_RETVAL_COMPLETE);
6029 	}
6030 
6031 	/*
6032 	 * Decrement these before we call the page handler, since we may
6033 	 * end up getting called back one way or another before the handler
6034 	 * returns to this context.
6035 	 */
6036 	*len_left -= page_index->page_len;
6037 	*len_used += page_index->page_len;
6038 
6039 	retval = page_index->select_handler(ctsio, page_index,
6040 					    (uint8_t *)page_header);
6041 
6042 	/*
6043 	 * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6044 	 * wait until this queued command completes to finish processing
6045 	 * the mode page.  If it returns anything other than
6046 	 * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6047 	 * already set the sense information, freed the data pointer, and
6048 	 * completed the io for us.
6049 	 */
6050 	if (retval != CTL_RETVAL_COMPLETE)
6051 		goto bailout_no_done;
6052 
6053 	/*
6054 	 * If the initiator sent us more than one page, parse the next one.
6055 	 */
6056 	if (*len_left > 0)
6057 		goto do_next_page;
6058 
6059 	ctl_set_success(ctsio);
6060 	free(ctsio->kern_data_ptr, M_CTL);
6061 	ctl_done((union ctl_io *)ctsio);
6062 
6063 bailout_no_done:
6064 
6065 	return (CTL_RETVAL_COMPLETE);
6066 
6067 }
6068 
6069 int
6070 ctl_mode_select(struct ctl_scsiio *ctsio)
6071 {
6072 	struct ctl_lun *lun = CTL_LUN(ctsio);
6073 	union ctl_modepage_info *modepage_info;
6074 	int bd_len, i, header_size, param_len, rtd;
6075 	uint32_t initidx;
6076 
6077 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6078 	switch (ctsio->cdb[0]) {
6079 	case MODE_SELECT_6: {
6080 		struct scsi_mode_select_6 *cdb;
6081 
6082 		cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6083 
6084 		rtd = (cdb->byte2 & SMS_RTD) ? 1 : 0;
6085 		param_len = cdb->length;
6086 		header_size = sizeof(struct scsi_mode_header_6);
6087 		break;
6088 	}
6089 	case MODE_SELECT_10: {
6090 		struct scsi_mode_select_10 *cdb;
6091 
6092 		cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6093 
6094 		rtd = (cdb->byte2 & SMS_RTD) ? 1 : 0;
6095 		param_len = scsi_2btoul(cdb->length);
6096 		header_size = sizeof(struct scsi_mode_header_10);
6097 		break;
6098 	}
6099 	default:
6100 		ctl_set_invalid_opcode(ctsio);
6101 		ctl_done((union ctl_io *)ctsio);
6102 		return (CTL_RETVAL_COMPLETE);
6103 	}
6104 
6105 	if (rtd) {
6106 		if (param_len != 0) {
6107 			ctl_set_invalid_field(ctsio, /*sks_valid*/ 0,
6108 			    /*command*/ 1, /*field*/ 0,
6109 			    /*bit_valid*/ 0, /*bit*/ 0);
6110 			ctl_done((union ctl_io *)ctsio);
6111 			return (CTL_RETVAL_COMPLETE);
6112 		}
6113 
6114 		/* Revert to defaults. */
6115 		ctl_init_page_index(lun);
6116 		mtx_lock(&lun->lun_lock);
6117 		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
6118 		mtx_unlock(&lun->lun_lock);
6119 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6120 			ctl_isc_announce_mode(lun, -1,
6121 			    lun->mode_pages.index[i].page_code & SMPH_PC_MASK,
6122 			    lun->mode_pages.index[i].subpage);
6123 		}
6124 		ctl_set_success(ctsio);
6125 		ctl_done((union ctl_io *)ctsio);
6126 		return (CTL_RETVAL_COMPLETE);
6127 	}
6128 
6129 	/*
6130 	 * From SPC-3:
6131 	 * "A parameter list length of zero indicates that the Data-Out Buffer
6132 	 * shall be empty. This condition shall not be considered as an error."
6133 	 */
6134 	if (param_len == 0) {
6135 		ctl_set_success(ctsio);
6136 		ctl_done((union ctl_io *)ctsio);
6137 		return (CTL_RETVAL_COMPLETE);
6138 	}
6139 
6140 	/*
6141 	 * Since we'll hit this the first time through, prior to
6142 	 * allocation, we don't need to free a data buffer here.
6143 	 */
6144 	if (param_len < header_size) {
6145 		ctl_set_param_len_error(ctsio);
6146 		ctl_done((union ctl_io *)ctsio);
6147 		return (CTL_RETVAL_COMPLETE);
6148 	}
6149 
6150 	/*
6151 	 * Allocate the data buffer and grab the user's data.  In theory,
6152 	 * we shouldn't have to sanity check the parameter list length here
6153 	 * because the maximum size is 64K.  We should be able to malloc
6154 	 * that much without too many problems.
6155 	 */
6156 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6157 		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6158 		ctsio->kern_data_len = param_len;
6159 		ctsio->kern_total_len = param_len;
6160 		ctsio->kern_rel_offset = 0;
6161 		ctsio->kern_sg_entries = 0;
6162 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6163 		ctsio->be_move_done = ctl_config_move_done;
6164 		ctl_datamove((union ctl_io *)ctsio);
6165 
6166 		return (CTL_RETVAL_COMPLETE);
6167 	}
6168 
6169 	switch (ctsio->cdb[0]) {
6170 	case MODE_SELECT_6: {
6171 		struct scsi_mode_header_6 *mh6;
6172 
6173 		mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6174 		bd_len = mh6->blk_desc_len;
6175 		break;
6176 	}
6177 	case MODE_SELECT_10: {
6178 		struct scsi_mode_header_10 *mh10;
6179 
6180 		mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6181 		bd_len = scsi_2btoul(mh10->blk_desc_len);
6182 		break;
6183 	}
6184 	default:
6185 		panic("%s: Invalid CDB type %#x", __func__, ctsio->cdb[0]);
6186 	}
6187 
6188 	if (param_len < (header_size + bd_len)) {
6189 		free(ctsio->kern_data_ptr, M_CTL);
6190 		ctl_set_param_len_error(ctsio);
6191 		ctl_done((union ctl_io *)ctsio);
6192 		return (CTL_RETVAL_COMPLETE);
6193 	}
6194 
6195 	/*
6196 	 * Set the IO_CONT flag, so that if this I/O gets passed to
6197 	 * ctl_config_write_done(), it'll get passed back to
6198 	 * ctl_do_mode_select() for further processing, or completion if
6199 	 * we're all done.
6200 	 */
6201 	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6202 	ctsio->io_cont = ctl_do_mode_select;
6203 
6204 	modepage_info = (union ctl_modepage_info *)
6205 		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6206 	memset(modepage_info, 0, sizeof(*modepage_info));
6207 	modepage_info->header.len_left = param_len - header_size - bd_len;
6208 	modepage_info->header.len_used = header_size + bd_len;
6209 
6210 	return (ctl_do_mode_select((union ctl_io *)ctsio));
6211 }
6212 
6213 int
6214 ctl_mode_sense(struct ctl_scsiio *ctsio)
6215 {
6216 	struct ctl_lun *lun = CTL_LUN(ctsio);
6217 	int pc, page_code, llba, subpage;
6218 	int alloc_len, page_len, header_len, bd_len, total_len;
6219 	void *block_desc;
6220 	struct ctl_page_index *page_index;
6221 
6222 	llba = 0;
6223 
6224 	CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6225 
6226 	switch (ctsio->cdb[0]) {
6227 	case MODE_SENSE_6: {
6228 		struct scsi_mode_sense_6 *cdb;
6229 
6230 		cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6231 
6232 		header_len = sizeof(struct scsi_mode_hdr_6);
6233 		if (cdb->byte2 & SMS_DBD)
6234 			bd_len = 0;
6235 		else
6236 			bd_len = sizeof(struct scsi_mode_block_descr);
6237 		header_len += bd_len;
6238 
6239 		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6240 		page_code = cdb->page & SMS_PAGE_CODE;
6241 		subpage = cdb->subpage;
6242 		alloc_len = cdb->length;
6243 		break;
6244 	}
6245 	case MODE_SENSE_10: {
6246 		struct scsi_mode_sense_10 *cdb;
6247 
6248 		cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6249 
6250 		header_len = sizeof(struct scsi_mode_hdr_10);
6251 		if (cdb->byte2 & SMS_DBD) {
6252 			bd_len = 0;
6253 		} else if (lun->be_lun->lun_type == T_DIRECT) {
6254 			if (cdb->byte2 & SMS10_LLBAA) {
6255 				llba = 1;
6256 				bd_len = sizeof(struct scsi_mode_block_descr_dlong);
6257 			} else
6258 				bd_len = sizeof(struct scsi_mode_block_descr_dshort);
6259 		} else
6260 			bd_len = sizeof(struct scsi_mode_block_descr);
6261 		header_len += bd_len;
6262 
6263 		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6264 		page_code = cdb->page & SMS_PAGE_CODE;
6265 		subpage = cdb->subpage;
6266 		alloc_len = scsi_2btoul(cdb->length);
6267 		break;
6268 	}
6269 	default:
6270 		ctl_set_invalid_opcode(ctsio);
6271 		ctl_done((union ctl_io *)ctsio);
6272 		return (CTL_RETVAL_COMPLETE);
6273 		break; /* NOTREACHED */
6274 	}
6275 
6276 	/*
6277 	 * We have to make a first pass through to calculate the size of
6278 	 * the pages that match the user's query.  Then we allocate enough
6279 	 * memory to hold it, and actually copy the data into the buffer.
6280 	 */
6281 	switch (page_code) {
6282 	case SMS_ALL_PAGES_PAGE: {
6283 		u_int i;
6284 
6285 		page_len = 0;
6286 
6287 		/*
6288 		 * At the moment, values other than 0 and 0xff here are
6289 		 * reserved according to SPC-3.
6290 		 */
6291 		if ((subpage != SMS_SUBPAGE_PAGE_0)
6292 		 && (subpage != SMS_SUBPAGE_ALL)) {
6293 			ctl_set_invalid_field(ctsio,
6294 					      /*sks_valid*/ 1,
6295 					      /*command*/ 1,
6296 					      /*field*/ 3,
6297 					      /*bit_valid*/ 0,
6298 					      /*bit*/ 0);
6299 			ctl_done((union ctl_io *)ctsio);
6300 			return (CTL_RETVAL_COMPLETE);
6301 		}
6302 
6303 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6304 			page_index = &lun->mode_pages.index[i];
6305 
6306 			/* Make sure the page is supported for this dev type */
6307 			if (lun->be_lun->lun_type == T_DIRECT &&
6308 			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6309 				continue;
6310 			if (lun->be_lun->lun_type == T_PROCESSOR &&
6311 			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6312 				continue;
6313 			if (lun->be_lun->lun_type == T_CDROM &&
6314 			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6315 				continue;
6316 
6317 			/*
6318 			 * We don't use this subpage if the user didn't
6319 			 * request all subpages.
6320 			 */
6321 			if ((page_index->subpage != 0)
6322 			 && (subpage == SMS_SUBPAGE_PAGE_0))
6323 				continue;
6324 
6325 			page_len += page_index->page_len;
6326 		}
6327 		break;
6328 	}
6329 	default: {
6330 		u_int i;
6331 
6332 		page_len = 0;
6333 
6334 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6335 			page_index = &lun->mode_pages.index[i];
6336 
6337 			/* Make sure the page is supported for this dev type */
6338 			if (lun->be_lun->lun_type == T_DIRECT &&
6339 			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6340 				continue;
6341 			if (lun->be_lun->lun_type == T_PROCESSOR &&
6342 			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6343 				continue;
6344 			if (lun->be_lun->lun_type == T_CDROM &&
6345 			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6346 				continue;
6347 
6348 			/* Look for the right page code */
6349 			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6350 				continue;
6351 
6352 			/* Look for the right subpage or the subpage wildcard*/
6353 			if ((page_index->subpage != subpage)
6354 			 && (subpage != SMS_SUBPAGE_ALL))
6355 				continue;
6356 
6357 			page_len += page_index->page_len;
6358 		}
6359 
6360 		if (page_len == 0) {
6361 			ctl_set_invalid_field(ctsio,
6362 					      /*sks_valid*/ 1,
6363 					      /*command*/ 1,
6364 					      /*field*/ 2,
6365 					      /*bit_valid*/ 1,
6366 					      /*bit*/ 5);
6367 			ctl_done((union ctl_io *)ctsio);
6368 			return (CTL_RETVAL_COMPLETE);
6369 		}
6370 		break;
6371 	}
6372 	}
6373 
6374 	total_len = header_len + page_len;
6375 
6376 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6377 	ctsio->kern_sg_entries = 0;
6378 	ctsio->kern_rel_offset = 0;
6379 	ctsio->kern_data_len = min(total_len, alloc_len);
6380 	ctsio->kern_total_len = ctsio->kern_data_len;
6381 
6382 	switch (ctsio->cdb[0]) {
6383 	case MODE_SENSE_6: {
6384 		struct scsi_mode_hdr_6 *header;
6385 
6386 		header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6387 
6388 		header->datalen = MIN(total_len - 1, 254);
6389 		if (lun->be_lun->lun_type == T_DIRECT) {
6390 			header->dev_specific = 0x10; /* DPOFUA */
6391 			if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6392 			    (lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0)
6393 				header->dev_specific |= 0x80; /* WP */
6394 		}
6395 		header->block_descr_len = bd_len;
6396 		block_desc = &header[1];
6397 		break;
6398 	}
6399 	case MODE_SENSE_10: {
6400 		struct scsi_mode_hdr_10 *header;
6401 		int datalen;
6402 
6403 		header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6404 
6405 		datalen = MIN(total_len - 2, 65533);
6406 		scsi_ulto2b(datalen, header->datalen);
6407 		if (lun->be_lun->lun_type == T_DIRECT) {
6408 			header->dev_specific = 0x10; /* DPOFUA */
6409 			if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6410 			    (lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0)
6411 				header->dev_specific |= 0x80; /* WP */
6412 		}
6413 		if (llba)
6414 			header->flags |= SMH_LONGLBA;
6415 		scsi_ulto2b(bd_len, header->block_descr_len);
6416 		block_desc = &header[1];
6417 		break;
6418 	}
6419 	default:
6420 		panic("%s: Invalid CDB type %#x", __func__, ctsio->cdb[0]);
6421 	}
6422 
6423 	/*
6424 	 * If we've got a disk, use its blocksize in the block
6425 	 * descriptor.  Otherwise, just set it to 0.
6426 	 */
6427 	if (bd_len > 0) {
6428 		if (lun->be_lun->lun_type == T_DIRECT) {
6429 			if (llba) {
6430 				struct scsi_mode_block_descr_dlong *bd = block_desc;
6431 				if (lun->be_lun->maxlba != 0)
6432 					scsi_u64to8b(lun->be_lun->maxlba + 1,
6433 					    bd->num_blocks);
6434 				scsi_ulto4b(lun->be_lun->blocksize,
6435 				    bd->block_len);
6436 			} else {
6437 				struct scsi_mode_block_descr_dshort *bd = block_desc;
6438 				if (lun->be_lun->maxlba != 0)
6439 					scsi_ulto4b(MIN(lun->be_lun->maxlba+1,
6440 					    UINT32_MAX), bd->num_blocks);
6441 				scsi_ulto3b(lun->be_lun->blocksize,
6442 				    bd->block_len);
6443 			}
6444 		} else {
6445 			struct scsi_mode_block_descr *bd = block_desc;
6446 			scsi_ulto3b(0, bd->block_len);
6447 		}
6448 	}
6449 
6450 	switch (page_code) {
6451 	case SMS_ALL_PAGES_PAGE: {
6452 		int i, data_used;
6453 
6454 		data_used = header_len;
6455 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6456 			struct ctl_page_index *page_index;
6457 
6458 			page_index = &lun->mode_pages.index[i];
6459 			if (lun->be_lun->lun_type == T_DIRECT &&
6460 			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6461 				continue;
6462 			if (lun->be_lun->lun_type == T_PROCESSOR &&
6463 			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6464 				continue;
6465 			if (lun->be_lun->lun_type == T_CDROM &&
6466 			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6467 				continue;
6468 
6469 			/*
6470 			 * We don't use this subpage if the user didn't
6471 			 * request all subpages.  We already checked (above)
6472 			 * to make sure the user only specified a subpage
6473 			 * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
6474 			 */
6475 			if ((page_index->subpage != 0)
6476 			 && (subpage == SMS_SUBPAGE_PAGE_0))
6477 				continue;
6478 
6479 			/*
6480 			 * Call the handler, if it exists, to update the
6481 			 * page to the latest values.
6482 			 */
6483 			if (page_index->sense_handler != NULL)
6484 				page_index->sense_handler(ctsio, page_index,pc);
6485 
6486 			memcpy(ctsio->kern_data_ptr + data_used,
6487 			       page_index->page_data +
6488 			       (page_index->page_len * pc),
6489 			       page_index->page_len);
6490 			data_used += page_index->page_len;
6491 		}
6492 		break;
6493 	}
6494 	default: {
6495 		int i, data_used;
6496 
6497 		data_used = header_len;
6498 
6499 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6500 			struct ctl_page_index *page_index;
6501 
6502 			page_index = &lun->mode_pages.index[i];
6503 
6504 			/* Look for the right page code */
6505 			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6506 				continue;
6507 
6508 			/* Look for the right subpage or the subpage wildcard*/
6509 			if ((page_index->subpage != subpage)
6510 			 && (subpage != SMS_SUBPAGE_ALL))
6511 				continue;
6512 
6513 			/* Make sure the page is supported for this dev type */
6514 			if (lun->be_lun->lun_type == T_DIRECT &&
6515 			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6516 				continue;
6517 			if (lun->be_lun->lun_type == T_PROCESSOR &&
6518 			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6519 				continue;
6520 			if (lun->be_lun->lun_type == T_CDROM &&
6521 			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6522 				continue;
6523 
6524 			/*
6525 			 * Call the handler, if it exists, to update the
6526 			 * page to the latest values.
6527 			 */
6528 			if (page_index->sense_handler != NULL)
6529 				page_index->sense_handler(ctsio, page_index,pc);
6530 
6531 			memcpy(ctsio->kern_data_ptr + data_used,
6532 			       page_index->page_data +
6533 			       (page_index->page_len * pc),
6534 			       page_index->page_len);
6535 			data_used += page_index->page_len;
6536 		}
6537 		break;
6538 	}
6539 	}
6540 
6541 	ctl_set_success(ctsio);
6542 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6543 	ctsio->be_move_done = ctl_config_move_done;
6544 	ctl_datamove((union ctl_io *)ctsio);
6545 	return (CTL_RETVAL_COMPLETE);
6546 }
6547 
6548 int
6549 ctl_temp_log_sense_handler(struct ctl_scsiio *ctsio,
6550 			       struct ctl_page_index *page_index,
6551 			       int pc)
6552 {
6553 	struct ctl_lun *lun = CTL_LUN(ctsio);
6554 	struct scsi_log_temperature *data;
6555 	const char *value;
6556 
6557 	data = (struct scsi_log_temperature *)page_index->page_data;
6558 
6559 	scsi_ulto2b(SLP_TEMPERATURE, data->hdr.param_code);
6560 	data->hdr.param_control = SLP_LBIN;
6561 	data->hdr.param_len = sizeof(struct scsi_log_temperature) -
6562 	    sizeof(struct scsi_log_param_header);
6563 	if ((value = dnvlist_get_string(lun->be_lun->options, "temperature",
6564 	    NULL)) != NULL)
6565 		data->temperature = strtol(value, NULL, 0);
6566 	else
6567 		data->temperature = 0xff;
6568 	data++;
6569 
6570 	scsi_ulto2b(SLP_REFTEMPERATURE, data->hdr.param_code);
6571 	data->hdr.param_control = SLP_LBIN;
6572 	data->hdr.param_len = sizeof(struct scsi_log_temperature) -
6573 	    sizeof(struct scsi_log_param_header);
6574 	if ((value = dnvlist_get_string(lun->be_lun->options, "reftemperature",
6575 	    NULL)) != NULL)
6576 		data->temperature = strtol(value, NULL, 0);
6577 	else
6578 		data->temperature = 0xff;
6579 	return (0);
6580 }
6581 
6582 int
6583 ctl_lbp_log_sense_handler(struct ctl_scsiio *ctsio,
6584 			       struct ctl_page_index *page_index,
6585 			       int pc)
6586 {
6587 	struct ctl_lun *lun = CTL_LUN(ctsio);
6588 	struct scsi_log_param_header *phdr;
6589 	uint8_t *data;
6590 	uint64_t val;
6591 
6592 	data = page_index->page_data;
6593 
6594 	if (lun->backend->lun_attr != NULL &&
6595 	    (val = lun->backend->lun_attr(lun->be_lun, "blocksavail"))
6596 	     != UINT64_MAX) {
6597 		phdr = (struct scsi_log_param_header *)data;
6598 		scsi_ulto2b(0x0001, phdr->param_code);
6599 		phdr->param_control = SLP_LBIN | SLP_LP;
6600 		phdr->param_len = 8;
6601 		data = (uint8_t *)(phdr + 1);
6602 		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6603 		data[4] = 0x02; /* per-pool */
6604 		data += phdr->param_len;
6605 	}
6606 
6607 	if (lun->backend->lun_attr != NULL &&
6608 	    (val = lun->backend->lun_attr(lun->be_lun, "blocksused"))
6609 	     != UINT64_MAX) {
6610 		phdr = (struct scsi_log_param_header *)data;
6611 		scsi_ulto2b(0x0002, phdr->param_code);
6612 		phdr->param_control = SLP_LBIN | SLP_LP;
6613 		phdr->param_len = 8;
6614 		data = (uint8_t *)(phdr + 1);
6615 		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6616 		data[4] = 0x01; /* per-LUN */
6617 		data += phdr->param_len;
6618 	}
6619 
6620 	if (lun->backend->lun_attr != NULL &&
6621 	    (val = lun->backend->lun_attr(lun->be_lun, "poolblocksavail"))
6622 	     != UINT64_MAX) {
6623 		phdr = (struct scsi_log_param_header *)data;
6624 		scsi_ulto2b(0x00f1, phdr->param_code);
6625 		phdr->param_control = SLP_LBIN | SLP_LP;
6626 		phdr->param_len = 8;
6627 		data = (uint8_t *)(phdr + 1);
6628 		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6629 		data[4] = 0x02; /* per-pool */
6630 		data += phdr->param_len;
6631 	}
6632 
6633 	if (lun->backend->lun_attr != NULL &&
6634 	    (val = lun->backend->lun_attr(lun->be_lun, "poolblocksused"))
6635 	     != UINT64_MAX) {
6636 		phdr = (struct scsi_log_param_header *)data;
6637 		scsi_ulto2b(0x00f2, phdr->param_code);
6638 		phdr->param_control = SLP_LBIN | SLP_LP;
6639 		phdr->param_len = 8;
6640 		data = (uint8_t *)(phdr + 1);
6641 		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6642 		data[4] = 0x02; /* per-pool */
6643 		data += phdr->param_len;
6644 	}
6645 
6646 	page_index->page_len = data - page_index->page_data;
6647 	return (0);
6648 }
6649 
6650 int
6651 ctl_sap_log_sense_handler(struct ctl_scsiio *ctsio,
6652 			       struct ctl_page_index *page_index,
6653 			       int pc)
6654 {
6655 	struct ctl_lun *lun = CTL_LUN(ctsio);
6656 	struct stat_page *data;
6657 	struct bintime *t;
6658 
6659 	data = (struct stat_page *)page_index->page_data;
6660 
6661 	scsi_ulto2b(SLP_SAP, data->sap.hdr.param_code);
6662 	data->sap.hdr.param_control = SLP_LBIN;
6663 	data->sap.hdr.param_len = sizeof(struct scsi_log_stat_and_perf) -
6664 	    sizeof(struct scsi_log_param_header);
6665 	scsi_u64to8b(lun->stats.operations[CTL_STATS_READ],
6666 	    data->sap.read_num);
6667 	scsi_u64to8b(lun->stats.operations[CTL_STATS_WRITE],
6668 	    data->sap.write_num);
6669 	if (lun->be_lun->blocksize > 0) {
6670 		scsi_u64to8b(lun->stats.bytes[CTL_STATS_WRITE] /
6671 		    lun->be_lun->blocksize, data->sap.recvieved_lba);
6672 		scsi_u64to8b(lun->stats.bytes[CTL_STATS_READ] /
6673 		    lun->be_lun->blocksize, data->sap.transmitted_lba);
6674 	}
6675 	t = &lun->stats.time[CTL_STATS_READ];
6676 	scsi_u64to8b((uint64_t)t->sec * 1000 + t->frac / (UINT64_MAX / 1000),
6677 	    data->sap.read_int);
6678 	t = &lun->stats.time[CTL_STATS_WRITE];
6679 	scsi_u64to8b((uint64_t)t->sec * 1000 + t->frac / (UINT64_MAX / 1000),
6680 	    data->sap.write_int);
6681 	scsi_u64to8b(0, data->sap.weighted_num);
6682 	scsi_u64to8b(0, data->sap.weighted_int);
6683 	scsi_ulto2b(SLP_IT, data->it.hdr.param_code);
6684 	data->it.hdr.param_control = SLP_LBIN;
6685 	data->it.hdr.param_len = sizeof(struct scsi_log_idle_time) -
6686 	    sizeof(struct scsi_log_param_header);
6687 #ifdef CTL_TIME_IO
6688 	scsi_u64to8b(lun->idle_time / SBT_1MS, data->it.idle_int);
6689 #endif
6690 	scsi_ulto2b(SLP_TI, data->ti.hdr.param_code);
6691 	data->it.hdr.param_control = SLP_LBIN;
6692 	data->ti.hdr.param_len = sizeof(struct scsi_log_time_interval) -
6693 	    sizeof(struct scsi_log_param_header);
6694 	scsi_ulto4b(3, data->ti.exponent);
6695 	scsi_ulto4b(1, data->ti.integer);
6696 	return (0);
6697 }
6698 
6699 int
6700 ctl_ie_log_sense_handler(struct ctl_scsiio *ctsio,
6701 			       struct ctl_page_index *page_index,
6702 			       int pc)
6703 {
6704 	struct ctl_lun *lun = CTL_LUN(ctsio);
6705 	struct scsi_log_informational_exceptions *data;
6706 	const char *value;
6707 
6708 	data = (struct scsi_log_informational_exceptions *)page_index->page_data;
6709 
6710 	scsi_ulto2b(SLP_IE_GEN, data->hdr.param_code);
6711 	data->hdr.param_control = SLP_LBIN;
6712 	data->hdr.param_len = sizeof(struct scsi_log_informational_exceptions) -
6713 	    sizeof(struct scsi_log_param_header);
6714 	data->ie_asc = lun->ie_asc;
6715 	data->ie_ascq = lun->ie_ascq;
6716 	if ((value = dnvlist_get_string(lun->be_lun->options, "temperature",
6717 	    NULL)) != NULL)
6718 		data->temperature = strtol(value, NULL, 0);
6719 	else
6720 		data->temperature = 0xff;
6721 	return (0);
6722 }
6723 
6724 int
6725 ctl_log_sense(struct ctl_scsiio *ctsio)
6726 {
6727 	struct ctl_lun *lun = CTL_LUN(ctsio);
6728 	int i, pc, page_code, subpage;
6729 	int alloc_len, total_len;
6730 	struct ctl_page_index *page_index;
6731 	struct scsi_log_sense *cdb;
6732 	struct scsi_log_header *header;
6733 
6734 	CTL_DEBUG_PRINT(("ctl_log_sense\n"));
6735 
6736 	cdb = (struct scsi_log_sense *)ctsio->cdb;
6737 	pc = (cdb->page & SLS_PAGE_CTRL_MASK) >> 6;
6738 	page_code = cdb->page & SLS_PAGE_CODE;
6739 	subpage = cdb->subpage;
6740 	alloc_len = scsi_2btoul(cdb->length);
6741 
6742 	page_index = NULL;
6743 	for (i = 0; i < CTL_NUM_LOG_PAGES; i++) {
6744 		page_index = &lun->log_pages.index[i];
6745 
6746 		/* Look for the right page code */
6747 		if ((page_index->page_code & SL_PAGE_CODE) != page_code)
6748 			continue;
6749 
6750 		/* Look for the right subpage or the subpage wildcard*/
6751 		if (page_index->subpage != subpage)
6752 			continue;
6753 
6754 		break;
6755 	}
6756 	if (i >= CTL_NUM_LOG_PAGES) {
6757 		ctl_set_invalid_field(ctsio,
6758 				      /*sks_valid*/ 1,
6759 				      /*command*/ 1,
6760 				      /*field*/ 2,
6761 				      /*bit_valid*/ 0,
6762 				      /*bit*/ 0);
6763 		ctl_done((union ctl_io *)ctsio);
6764 		return (CTL_RETVAL_COMPLETE);
6765 	}
6766 
6767 	total_len = sizeof(struct scsi_log_header) + page_index->page_len;
6768 
6769 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6770 	ctsio->kern_sg_entries = 0;
6771 	ctsio->kern_rel_offset = 0;
6772 	ctsio->kern_data_len = min(total_len, alloc_len);
6773 	ctsio->kern_total_len = ctsio->kern_data_len;
6774 
6775 	header = (struct scsi_log_header *)ctsio->kern_data_ptr;
6776 	header->page = page_index->page_code;
6777 	if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING)
6778 		header->page |= SL_DS;
6779 	if (page_index->subpage) {
6780 		header->page |= SL_SPF;
6781 		header->subpage = page_index->subpage;
6782 	}
6783 	scsi_ulto2b(page_index->page_len, header->datalen);
6784 
6785 	/*
6786 	 * Call the handler, if it exists, to update the
6787 	 * page to the latest values.
6788 	 */
6789 	if (page_index->sense_handler != NULL)
6790 		page_index->sense_handler(ctsio, page_index, pc);
6791 
6792 	memcpy(header + 1, page_index->page_data, page_index->page_len);
6793 
6794 	ctl_set_success(ctsio);
6795 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6796 	ctsio->be_move_done = ctl_config_move_done;
6797 	ctl_datamove((union ctl_io *)ctsio);
6798 	return (CTL_RETVAL_COMPLETE);
6799 }
6800 
6801 int
6802 ctl_read_capacity(struct ctl_scsiio *ctsio)
6803 {
6804 	struct ctl_lun *lun = CTL_LUN(ctsio);
6805 	struct scsi_read_capacity *cdb;
6806 	struct scsi_read_capacity_data *data;
6807 	uint32_t lba;
6808 
6809 	CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
6810 
6811 	cdb = (struct scsi_read_capacity *)ctsio->cdb;
6812 
6813 	lba = scsi_4btoul(cdb->addr);
6814 	if (((cdb->pmi & SRC_PMI) == 0)
6815 	 && (lba != 0)) {
6816 		ctl_set_invalid_field(/*ctsio*/ ctsio,
6817 				      /*sks_valid*/ 1,
6818 				      /*command*/ 1,
6819 				      /*field*/ 2,
6820 				      /*bit_valid*/ 0,
6821 				      /*bit*/ 0);
6822 		ctl_done((union ctl_io *)ctsio);
6823 		return (CTL_RETVAL_COMPLETE);
6824 	}
6825 
6826 	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
6827 	data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
6828 	ctsio->kern_data_len = sizeof(*data);
6829 	ctsio->kern_total_len = sizeof(*data);
6830 	ctsio->kern_rel_offset = 0;
6831 	ctsio->kern_sg_entries = 0;
6832 
6833 	/*
6834 	 * If the maximum LBA is greater than 0xfffffffe, the user must
6835 	 * issue a SERVICE ACTION IN (16) command, with the read capacity
6836 	 * serivce action set.
6837 	 */
6838 	if (lun->be_lun->maxlba > 0xfffffffe)
6839 		scsi_ulto4b(0xffffffff, data->addr);
6840 	else
6841 		scsi_ulto4b(lun->be_lun->maxlba, data->addr);
6842 
6843 	/*
6844 	 * XXX KDM this may not be 512 bytes...
6845 	 */
6846 	scsi_ulto4b(lun->be_lun->blocksize, data->length);
6847 
6848 	ctl_set_success(ctsio);
6849 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6850 	ctsio->be_move_done = ctl_config_move_done;
6851 	ctl_datamove((union ctl_io *)ctsio);
6852 	return (CTL_RETVAL_COMPLETE);
6853 }
6854 
6855 int
6856 ctl_read_capacity_16(struct ctl_scsiio *ctsio)
6857 {
6858 	struct ctl_lun *lun = CTL_LUN(ctsio);
6859 	struct scsi_read_capacity_16 *cdb;
6860 	struct scsi_read_capacity_data_long *data;
6861 	uint64_t lba;
6862 	uint32_t alloc_len;
6863 
6864 	CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
6865 
6866 	cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
6867 
6868 	alloc_len = scsi_4btoul(cdb->alloc_len);
6869 	lba = scsi_8btou64(cdb->addr);
6870 
6871 	if ((cdb->reladr & SRC16_PMI)
6872 	 && (lba != 0)) {
6873 		ctl_set_invalid_field(/*ctsio*/ ctsio,
6874 				      /*sks_valid*/ 1,
6875 				      /*command*/ 1,
6876 				      /*field*/ 2,
6877 				      /*bit_valid*/ 0,
6878 				      /*bit*/ 0);
6879 		ctl_done((union ctl_io *)ctsio);
6880 		return (CTL_RETVAL_COMPLETE);
6881 	}
6882 
6883 	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
6884 	data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
6885 	ctsio->kern_rel_offset = 0;
6886 	ctsio->kern_sg_entries = 0;
6887 	ctsio->kern_data_len = min(sizeof(*data), alloc_len);
6888 	ctsio->kern_total_len = ctsio->kern_data_len;
6889 
6890 	scsi_u64to8b(lun->be_lun->maxlba, data->addr);
6891 	/* XXX KDM this may not be 512 bytes... */
6892 	scsi_ulto4b(lun->be_lun->blocksize, data->length);
6893 	data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
6894 	scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
6895 	if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
6896 		data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
6897 
6898 	ctl_set_success(ctsio);
6899 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6900 	ctsio->be_move_done = ctl_config_move_done;
6901 	ctl_datamove((union ctl_io *)ctsio);
6902 	return (CTL_RETVAL_COMPLETE);
6903 }
6904 
6905 int
6906 ctl_get_lba_status(struct ctl_scsiio *ctsio)
6907 {
6908 	struct ctl_lun *lun = CTL_LUN(ctsio);
6909 	struct scsi_get_lba_status *cdb;
6910 	struct scsi_get_lba_status_data *data;
6911 	struct ctl_lba_len_flags *lbalen;
6912 	uint64_t lba;
6913 	uint32_t alloc_len, total_len;
6914 	int retval;
6915 
6916 	CTL_DEBUG_PRINT(("ctl_get_lba_status\n"));
6917 
6918 	cdb = (struct scsi_get_lba_status *)ctsio->cdb;
6919 	lba = scsi_8btou64(cdb->addr);
6920 	alloc_len = scsi_4btoul(cdb->alloc_len);
6921 
6922 	if (lba > lun->be_lun->maxlba) {
6923 		ctl_set_lba_out_of_range(ctsio, lba);
6924 		ctl_done((union ctl_io *)ctsio);
6925 		return (CTL_RETVAL_COMPLETE);
6926 	}
6927 
6928 	total_len = sizeof(*data) + sizeof(data->descr[0]);
6929 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6930 	data = (struct scsi_get_lba_status_data *)ctsio->kern_data_ptr;
6931 	ctsio->kern_rel_offset = 0;
6932 	ctsio->kern_sg_entries = 0;
6933 	ctsio->kern_data_len = min(total_len, alloc_len);
6934 	ctsio->kern_total_len = ctsio->kern_data_len;
6935 
6936 	/* Fill dummy data in case backend can't tell anything. */
6937 	scsi_ulto4b(4 + sizeof(data->descr[0]), data->length);
6938 	scsi_u64to8b(lba, data->descr[0].addr);
6939 	scsi_ulto4b(MIN(UINT32_MAX, lun->be_lun->maxlba + 1 - lba),
6940 	    data->descr[0].length);
6941 	data->descr[0].status = 0; /* Mapped or unknown. */
6942 
6943 	ctl_set_success(ctsio);
6944 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6945 	ctsio->be_move_done = ctl_config_move_done;
6946 
6947 	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
6948 	lbalen->lba = lba;
6949 	lbalen->len = total_len;
6950 	lbalen->flags = 0;
6951 	retval = lun->backend->config_read((union ctl_io *)ctsio);
6952 	return (retval);
6953 }
6954 
6955 int
6956 ctl_read_defect(struct ctl_scsiio *ctsio)
6957 {
6958 	struct scsi_read_defect_data_10 *ccb10;
6959 	struct scsi_read_defect_data_12 *ccb12;
6960 	struct scsi_read_defect_data_hdr_10 *data10;
6961 	struct scsi_read_defect_data_hdr_12 *data12;
6962 	uint32_t alloc_len, data_len;
6963 	uint8_t format;
6964 
6965 	CTL_DEBUG_PRINT(("ctl_read_defect\n"));
6966 
6967 	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
6968 		ccb10 = (struct scsi_read_defect_data_10 *)&ctsio->cdb;
6969 		format = ccb10->format;
6970 		alloc_len = scsi_2btoul(ccb10->alloc_length);
6971 		data_len = sizeof(*data10);
6972 	} else {
6973 		ccb12 = (struct scsi_read_defect_data_12 *)&ctsio->cdb;
6974 		format = ccb12->format;
6975 		alloc_len = scsi_4btoul(ccb12->alloc_length);
6976 		data_len = sizeof(*data12);
6977 	}
6978 	if (alloc_len == 0) {
6979 		ctl_set_success(ctsio);
6980 		ctl_done((union ctl_io *)ctsio);
6981 		return (CTL_RETVAL_COMPLETE);
6982 	}
6983 
6984 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
6985 	ctsio->kern_rel_offset = 0;
6986 	ctsio->kern_sg_entries = 0;
6987 	ctsio->kern_data_len = min(data_len, alloc_len);
6988 	ctsio->kern_total_len = ctsio->kern_data_len;
6989 
6990 	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
6991 		data10 = (struct scsi_read_defect_data_hdr_10 *)
6992 		    ctsio->kern_data_ptr;
6993 		data10->format = format;
6994 		scsi_ulto2b(0, data10->length);
6995 	} else {
6996 		data12 = (struct scsi_read_defect_data_hdr_12 *)
6997 		    ctsio->kern_data_ptr;
6998 		data12->format = format;
6999 		scsi_ulto2b(0, data12->generation);
7000 		scsi_ulto4b(0, data12->length);
7001 	}
7002 
7003 	ctl_set_success(ctsio);
7004 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7005 	ctsio->be_move_done = ctl_config_move_done;
7006 	ctl_datamove((union ctl_io *)ctsio);
7007 	return (CTL_RETVAL_COMPLETE);
7008 }
7009 
7010 int
7011 ctl_report_ident_info(struct ctl_scsiio *ctsio)
7012 {
7013 	struct ctl_lun *lun = CTL_LUN(ctsio);
7014 	struct scsi_report_ident_info *cdb;
7015 	struct scsi_report_ident_info_data *rii_ptr;
7016 	struct scsi_report_ident_info_descr *riid_ptr;
7017 	const char *oii, *otii;
7018 	int retval, alloc_len, total_len = 0, len = 0;
7019 
7020 	CTL_DEBUG_PRINT(("ctl_report_ident_info\n"));
7021 
7022 	cdb = (struct scsi_report_ident_info *)ctsio->cdb;
7023 	retval = CTL_RETVAL_COMPLETE;
7024 
7025 	total_len = sizeof(struct scsi_report_ident_info_data);
7026 	switch (cdb->type) {
7027 	case RII_LUII:
7028 		oii = dnvlist_get_string(lun->be_lun->options,
7029 		    "ident_info", NULL);
7030 		if (oii)
7031 			len = strlen(oii);	/* Approximately */
7032 		break;
7033 	case RII_LUTII:
7034 		otii = dnvlist_get_string(lun->be_lun->options,
7035 		    "text_ident_info", NULL);
7036 		if (otii)
7037 			len = strlen(otii) + 1;	/* NULL-terminated */
7038 		break;
7039 	case RII_IIS:
7040 		len = 2 * sizeof(struct scsi_report_ident_info_descr);
7041 		break;
7042 	default:
7043 		ctl_set_invalid_field(/*ctsio*/ ctsio,
7044 				      /*sks_valid*/ 1,
7045 				      /*command*/ 1,
7046 				      /*field*/ 11,
7047 				      /*bit_valid*/ 1,
7048 				      /*bit*/ 2);
7049 		ctl_done((union ctl_io *)ctsio);
7050 		return(retval);
7051 	}
7052 	total_len += len;
7053 	alloc_len = scsi_4btoul(cdb->length);
7054 
7055 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7056 	ctsio->kern_sg_entries = 0;
7057 	ctsio->kern_rel_offset = 0;
7058 	ctsio->kern_data_len = min(total_len, alloc_len);
7059 	ctsio->kern_total_len = ctsio->kern_data_len;
7060 
7061 	rii_ptr = (struct scsi_report_ident_info_data *)ctsio->kern_data_ptr;
7062 	switch (cdb->type) {
7063 	case RII_LUII:
7064 		if (oii) {
7065 			if (oii[0] == '0' && oii[1] == 'x')
7066 				len = hex2bin(oii, (uint8_t *)(rii_ptr + 1), len);
7067 			else
7068 				strncpy((uint8_t *)(rii_ptr + 1), oii, len);
7069 		}
7070 		break;
7071 	case RII_LUTII:
7072 		if (otii)
7073 			strlcpy((uint8_t *)(rii_ptr + 1), otii, len);
7074 		break;
7075 	case RII_IIS:
7076 		riid_ptr = (struct scsi_report_ident_info_descr *)(rii_ptr + 1);
7077 		riid_ptr->type = RII_LUII;
7078 		scsi_ulto2b(0xffff, riid_ptr->length);
7079 		riid_ptr++;
7080 		riid_ptr->type = RII_LUTII;
7081 		scsi_ulto2b(0xffff, riid_ptr->length);
7082 	}
7083 	scsi_ulto2b(len, rii_ptr->length);
7084 
7085 	ctl_set_success(ctsio);
7086 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7087 	ctsio->be_move_done = ctl_config_move_done;
7088 	ctl_datamove((union ctl_io *)ctsio);
7089 	return(retval);
7090 }
7091 
7092 int
7093 ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7094 {
7095 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
7096 	struct ctl_lun *lun = CTL_LUN(ctsio);
7097 	struct scsi_maintenance_in *cdb;
7098 	int retval;
7099 	int alloc_len, ext, total_len = 0, g, pc, pg, ts, os;
7100 	int num_ha_groups, num_target_ports, shared_group;
7101 	struct ctl_port *port;
7102 	struct scsi_target_group_data *rtg_ptr;
7103 	struct scsi_target_group_data_extended *rtg_ext_ptr;
7104 	struct scsi_target_port_group_descriptor *tpg_desc;
7105 
7106 	CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7107 
7108 	cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7109 	retval = CTL_RETVAL_COMPLETE;
7110 
7111 	switch (cdb->byte2 & STG_PDF_MASK) {
7112 	case STG_PDF_LENGTH:
7113 		ext = 0;
7114 		break;
7115 	case STG_PDF_EXTENDED:
7116 		ext = 1;
7117 		break;
7118 	default:
7119 		ctl_set_invalid_field(/*ctsio*/ ctsio,
7120 				      /*sks_valid*/ 1,
7121 				      /*command*/ 1,
7122 				      /*field*/ 2,
7123 				      /*bit_valid*/ 1,
7124 				      /*bit*/ 5);
7125 		ctl_done((union ctl_io *)ctsio);
7126 		return(retval);
7127 	}
7128 
7129 	num_target_ports = 0;
7130 	shared_group = (softc->is_single != 0);
7131 	mtx_lock(&softc->ctl_lock);
7132 	STAILQ_FOREACH(port, &softc->port_list, links) {
7133 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7134 			continue;
7135 		if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7136 			continue;
7137 		num_target_ports++;
7138 		if (port->status & CTL_PORT_STATUS_HA_SHARED)
7139 			shared_group = 1;
7140 	}
7141 	mtx_unlock(&softc->ctl_lock);
7142 	num_ha_groups = (softc->is_single) ? 0 : NUM_HA_SHELVES;
7143 
7144 	if (ext)
7145 		total_len = sizeof(struct scsi_target_group_data_extended);
7146 	else
7147 		total_len = sizeof(struct scsi_target_group_data);
7148 	total_len += sizeof(struct scsi_target_port_group_descriptor) *
7149 		(shared_group + num_ha_groups) +
7150 	    sizeof(struct scsi_target_port_descriptor) * num_target_ports;
7151 
7152 	alloc_len = scsi_4btoul(cdb->length);
7153 
7154 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7155 	ctsio->kern_sg_entries = 0;
7156 	ctsio->kern_rel_offset = 0;
7157 	ctsio->kern_data_len = min(total_len, alloc_len);
7158 	ctsio->kern_total_len = ctsio->kern_data_len;
7159 
7160 	if (ext) {
7161 		rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7162 		    ctsio->kern_data_ptr;
7163 		scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7164 		rtg_ext_ptr->format_type = 0x10;
7165 		rtg_ext_ptr->implicit_transition_time = 0;
7166 		tpg_desc = &rtg_ext_ptr->groups[0];
7167 	} else {
7168 		rtg_ptr = (struct scsi_target_group_data *)
7169 		    ctsio->kern_data_ptr;
7170 		scsi_ulto4b(total_len - 4, rtg_ptr->length);
7171 		tpg_desc = &rtg_ptr->groups[0];
7172 	}
7173 
7174 	mtx_lock(&softc->ctl_lock);
7175 	pg = softc->port_min / softc->port_cnt;
7176 	if (lun->flags & (CTL_LUN_PRIMARY_SC | CTL_LUN_PEER_SC_PRIMARY)) {
7177 		/* Some shelf is known to be primary. */
7178 		if (softc->ha_link == CTL_HA_LINK_OFFLINE)
7179 			os = TPG_ASYMMETRIC_ACCESS_UNAVAILABLE;
7180 		else if (softc->ha_link == CTL_HA_LINK_UNKNOWN)
7181 			os = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7182 		else if (softc->ha_mode == CTL_HA_MODE_ACT_STBY)
7183 			os = TPG_ASYMMETRIC_ACCESS_STANDBY;
7184 		else
7185 			os = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7186 		if (lun->flags & CTL_LUN_PRIMARY_SC) {
7187 			ts = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7188 		} else {
7189 			ts = os;
7190 			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7191 		}
7192 	} else {
7193 		/* No known primary shelf. */
7194 		if (softc->ha_link == CTL_HA_LINK_OFFLINE) {
7195 			ts = TPG_ASYMMETRIC_ACCESS_UNAVAILABLE;
7196 			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7197 		} else if (softc->ha_link == CTL_HA_LINK_UNKNOWN) {
7198 			ts = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7199 			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7200 		} else {
7201 			ts = os = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7202 		}
7203 	}
7204 	if (shared_group) {
7205 		tpg_desc->pref_state = ts;
7206 		tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP |
7207 		    TPG_U_SUP | TPG_T_SUP;
7208 		scsi_ulto2b(1, tpg_desc->target_port_group);
7209 		tpg_desc->status = TPG_IMPLICIT;
7210 		pc = 0;
7211 		STAILQ_FOREACH(port, &softc->port_list, links) {
7212 			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7213 				continue;
7214 			if (!softc->is_single &&
7215 			    (port->status & CTL_PORT_STATUS_HA_SHARED) == 0)
7216 				continue;
7217 			if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7218 				continue;
7219 			scsi_ulto2b(port->targ_port, tpg_desc->descriptors[pc].
7220 			    relative_target_port_identifier);
7221 			pc++;
7222 		}
7223 		tpg_desc->target_port_count = pc;
7224 		tpg_desc = (struct scsi_target_port_group_descriptor *)
7225 		    &tpg_desc->descriptors[pc];
7226 	}
7227 	for (g = 0; g < num_ha_groups; g++) {
7228 		tpg_desc->pref_state = (g == pg) ? ts : os;
7229 		tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP |
7230 		    TPG_U_SUP | TPG_T_SUP;
7231 		scsi_ulto2b(2 + g, tpg_desc->target_port_group);
7232 		tpg_desc->status = TPG_IMPLICIT;
7233 		pc = 0;
7234 		STAILQ_FOREACH(port, &softc->port_list, links) {
7235 			if (port->targ_port < g * softc->port_cnt ||
7236 			    port->targ_port >= (g + 1) * softc->port_cnt)
7237 				continue;
7238 			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7239 				continue;
7240 			if (port->status & CTL_PORT_STATUS_HA_SHARED)
7241 				continue;
7242 			if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7243 				continue;
7244 			scsi_ulto2b(port->targ_port, tpg_desc->descriptors[pc].
7245 			    relative_target_port_identifier);
7246 			pc++;
7247 		}
7248 		tpg_desc->target_port_count = pc;
7249 		tpg_desc = (struct scsi_target_port_group_descriptor *)
7250 		    &tpg_desc->descriptors[pc];
7251 	}
7252 	mtx_unlock(&softc->ctl_lock);
7253 
7254 	ctl_set_success(ctsio);
7255 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7256 	ctsio->be_move_done = ctl_config_move_done;
7257 	ctl_datamove((union ctl_io *)ctsio);
7258 	return(retval);
7259 }
7260 
7261 int
7262 ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7263 {
7264 	struct ctl_lun *lun = CTL_LUN(ctsio);
7265 	struct scsi_report_supported_opcodes *cdb;
7266 	const struct ctl_cmd_entry *entry, *sentry;
7267 	struct scsi_report_supported_opcodes_all *all;
7268 	struct scsi_report_supported_opcodes_descr *descr;
7269 	struct scsi_report_supported_opcodes_one *one;
7270 	int retval;
7271 	int alloc_len, total_len;
7272 	int opcode, service_action, i, j, num;
7273 
7274 	CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7275 
7276 	cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7277 	retval = CTL_RETVAL_COMPLETE;
7278 
7279 	opcode = cdb->requested_opcode;
7280 	service_action = scsi_2btoul(cdb->requested_service_action);
7281 	switch (cdb->options & RSO_OPTIONS_MASK) {
7282 	case RSO_OPTIONS_ALL:
7283 		num = 0;
7284 		for (i = 0; i < 256; i++) {
7285 			entry = &ctl_cmd_table[i];
7286 			if (entry->flags & CTL_CMD_FLAG_SA5) {
7287 				for (j = 0; j < 32; j++) {
7288 					sentry = &((const struct ctl_cmd_entry *)
7289 					    entry->execute)[j];
7290 					if (ctl_cmd_applicable(
7291 					    lun->be_lun->lun_type, sentry))
7292 						num++;
7293 				}
7294 			} else {
7295 				if (ctl_cmd_applicable(lun->be_lun->lun_type,
7296 				    entry))
7297 					num++;
7298 			}
7299 		}
7300 		total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7301 		    num * sizeof(struct scsi_report_supported_opcodes_descr);
7302 		break;
7303 	case RSO_OPTIONS_OC:
7304 		if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7305 			ctl_set_invalid_field(/*ctsio*/ ctsio,
7306 					      /*sks_valid*/ 1,
7307 					      /*command*/ 1,
7308 					      /*field*/ 2,
7309 					      /*bit_valid*/ 1,
7310 					      /*bit*/ 2);
7311 			ctl_done((union ctl_io *)ctsio);
7312 			return (CTL_RETVAL_COMPLETE);
7313 		}
7314 		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7315 		break;
7316 	case RSO_OPTIONS_OC_SA:
7317 		if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7318 		    service_action >= 32) {
7319 			ctl_set_invalid_field(/*ctsio*/ ctsio,
7320 					      /*sks_valid*/ 1,
7321 					      /*command*/ 1,
7322 					      /*field*/ 2,
7323 					      /*bit_valid*/ 1,
7324 					      /*bit*/ 2);
7325 			ctl_done((union ctl_io *)ctsio);
7326 			return (CTL_RETVAL_COMPLETE);
7327 		}
7328 		/* FALLTHROUGH */
7329 	case RSO_OPTIONS_OC_ASA:
7330 		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7331 		break;
7332 	default:
7333 		ctl_set_invalid_field(/*ctsio*/ ctsio,
7334 				      /*sks_valid*/ 1,
7335 				      /*command*/ 1,
7336 				      /*field*/ 2,
7337 				      /*bit_valid*/ 1,
7338 				      /*bit*/ 2);
7339 		ctl_done((union ctl_io *)ctsio);
7340 		return (CTL_RETVAL_COMPLETE);
7341 	}
7342 
7343 	alloc_len = scsi_4btoul(cdb->length);
7344 
7345 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7346 	ctsio->kern_sg_entries = 0;
7347 	ctsio->kern_rel_offset = 0;
7348 	ctsio->kern_data_len = min(total_len, alloc_len);
7349 	ctsio->kern_total_len = ctsio->kern_data_len;
7350 
7351 	switch (cdb->options & RSO_OPTIONS_MASK) {
7352 	case RSO_OPTIONS_ALL:
7353 		all = (struct scsi_report_supported_opcodes_all *)
7354 		    ctsio->kern_data_ptr;
7355 		num = 0;
7356 		for (i = 0; i < 256; i++) {
7357 			entry = &ctl_cmd_table[i];
7358 			if (entry->flags & CTL_CMD_FLAG_SA5) {
7359 				for (j = 0; j < 32; j++) {
7360 					sentry = &((const struct ctl_cmd_entry *)
7361 					    entry->execute)[j];
7362 					if (!ctl_cmd_applicable(
7363 					    lun->be_lun->lun_type, sentry))
7364 						continue;
7365 					descr = &all->descr[num++];
7366 					descr->opcode = i;
7367 					scsi_ulto2b(j, descr->service_action);
7368 					descr->flags = RSO_SERVACTV;
7369 					scsi_ulto2b(sentry->length,
7370 					    descr->cdb_length);
7371 				}
7372 			} else {
7373 				if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7374 				    entry))
7375 					continue;
7376 				descr = &all->descr[num++];
7377 				descr->opcode = i;
7378 				scsi_ulto2b(0, descr->service_action);
7379 				descr->flags = 0;
7380 				scsi_ulto2b(entry->length, descr->cdb_length);
7381 			}
7382 		}
7383 		scsi_ulto4b(
7384 		    num * sizeof(struct scsi_report_supported_opcodes_descr),
7385 		    all->length);
7386 		break;
7387 	case RSO_OPTIONS_OC:
7388 		one = (struct scsi_report_supported_opcodes_one *)
7389 		    ctsio->kern_data_ptr;
7390 		entry = &ctl_cmd_table[opcode];
7391 		goto fill_one;
7392 	case RSO_OPTIONS_OC_SA:
7393 		one = (struct scsi_report_supported_opcodes_one *)
7394 		    ctsio->kern_data_ptr;
7395 		entry = &ctl_cmd_table[opcode];
7396 		entry = &((const struct ctl_cmd_entry *)
7397 		    entry->execute)[service_action];
7398 fill_one:
7399 		if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7400 			one->support = 3;
7401 			scsi_ulto2b(entry->length, one->cdb_length);
7402 			one->cdb_usage[0] = opcode;
7403 			memcpy(&one->cdb_usage[1], entry->usage,
7404 			    entry->length - 1);
7405 		} else
7406 			one->support = 1;
7407 		break;
7408 	case RSO_OPTIONS_OC_ASA:
7409 		one = (struct scsi_report_supported_opcodes_one *)
7410 		    ctsio->kern_data_ptr;
7411 		entry = &ctl_cmd_table[opcode];
7412 		if (entry->flags & CTL_CMD_FLAG_SA5) {
7413 			entry = &((const struct ctl_cmd_entry *)
7414 			    entry->execute)[service_action];
7415 		} else if (service_action != 0) {
7416 			one->support = 1;
7417 			break;
7418 		}
7419 		goto fill_one;
7420 	}
7421 
7422 	ctl_set_success(ctsio);
7423 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7424 	ctsio->be_move_done = ctl_config_move_done;
7425 	ctl_datamove((union ctl_io *)ctsio);
7426 	return(retval);
7427 }
7428 
7429 int
7430 ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7431 {
7432 	struct scsi_report_supported_tmf *cdb;
7433 	struct scsi_report_supported_tmf_ext_data *data;
7434 	int retval;
7435 	int alloc_len, total_len;
7436 
7437 	CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7438 
7439 	cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7440 
7441 	retval = CTL_RETVAL_COMPLETE;
7442 
7443 	if (cdb->options & RST_REPD)
7444 		total_len = sizeof(struct scsi_report_supported_tmf_ext_data);
7445 	else
7446 		total_len = sizeof(struct scsi_report_supported_tmf_data);
7447 	alloc_len = scsi_4btoul(cdb->length);
7448 
7449 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7450 	ctsio->kern_sg_entries = 0;
7451 	ctsio->kern_rel_offset = 0;
7452 	ctsio->kern_data_len = min(total_len, alloc_len);
7453 	ctsio->kern_total_len = ctsio->kern_data_len;
7454 
7455 	data = (struct scsi_report_supported_tmf_ext_data *)ctsio->kern_data_ptr;
7456 	data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_QTS |
7457 	    RST_TRS;
7458 	data->byte2 |= RST_QAES | RST_QTSS | RST_ITNRS;
7459 	data->length = total_len - 4;
7460 
7461 	ctl_set_success(ctsio);
7462 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7463 	ctsio->be_move_done = ctl_config_move_done;
7464 	ctl_datamove((union ctl_io *)ctsio);
7465 	return (retval);
7466 }
7467 
7468 int
7469 ctl_report_timestamp(struct ctl_scsiio *ctsio)
7470 {
7471 	struct scsi_report_timestamp *cdb;
7472 	struct scsi_report_timestamp_data *data;
7473 	struct timeval tv;
7474 	int64_t timestamp;
7475 	int retval;
7476 	int alloc_len, total_len;
7477 
7478 	CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7479 
7480 	cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7481 
7482 	retval = CTL_RETVAL_COMPLETE;
7483 
7484 	total_len = sizeof(struct scsi_report_timestamp_data);
7485 	alloc_len = scsi_4btoul(cdb->length);
7486 
7487 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7488 	ctsio->kern_sg_entries = 0;
7489 	ctsio->kern_rel_offset = 0;
7490 	ctsio->kern_data_len = min(total_len, alloc_len);
7491 	ctsio->kern_total_len = ctsio->kern_data_len;
7492 
7493 	data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7494 	scsi_ulto2b(sizeof(*data) - 2, data->length);
7495 	data->origin = RTS_ORIG_OUTSIDE;
7496 	getmicrotime(&tv);
7497 	timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7498 	scsi_ulto4b(timestamp >> 16, data->timestamp);
7499 	scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7500 
7501 	ctl_set_success(ctsio);
7502 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7503 	ctsio->be_move_done = ctl_config_move_done;
7504 	ctl_datamove((union ctl_io *)ctsio);
7505 	return (retval);
7506 }
7507 
7508 int
7509 ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7510 {
7511 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
7512 	struct ctl_lun *lun = CTL_LUN(ctsio);
7513 	struct scsi_per_res_in *cdb;
7514 	int alloc_len, total_len = 0;
7515 	/* struct scsi_per_res_in_rsrv in_data; */
7516 	uint64_t key;
7517 
7518 	CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7519 
7520 	cdb = (struct scsi_per_res_in *)ctsio->cdb;
7521 
7522 	alloc_len = scsi_2btoul(cdb->length);
7523 
7524 retry:
7525 	mtx_lock(&lun->lun_lock);
7526 	switch (cdb->action) {
7527 	case SPRI_RK: /* read keys */
7528 		total_len = sizeof(struct scsi_per_res_in_keys) +
7529 			lun->pr_key_count *
7530 			sizeof(struct scsi_per_res_key);
7531 		break;
7532 	case SPRI_RR: /* read reservation */
7533 		if (lun->flags & CTL_LUN_PR_RESERVED)
7534 			total_len = sizeof(struct scsi_per_res_in_rsrv);
7535 		else
7536 			total_len = sizeof(struct scsi_per_res_in_header);
7537 		break;
7538 	case SPRI_RC: /* report capabilities */
7539 		total_len = sizeof(struct scsi_per_res_cap);
7540 		break;
7541 	case SPRI_RS: /* read full status */
7542 		total_len = sizeof(struct scsi_per_res_in_header) +
7543 		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7544 		    lun->pr_key_count;
7545 		break;
7546 	default:
7547 		panic("%s: Invalid PR type %#x", __func__, cdb->action);
7548 	}
7549 	mtx_unlock(&lun->lun_lock);
7550 
7551 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7552 	ctsio->kern_rel_offset = 0;
7553 	ctsio->kern_sg_entries = 0;
7554 	ctsio->kern_data_len = min(total_len, alloc_len);
7555 	ctsio->kern_total_len = ctsio->kern_data_len;
7556 
7557 	mtx_lock(&lun->lun_lock);
7558 	switch (cdb->action) {
7559 	case SPRI_RK: { // read keys
7560         struct scsi_per_res_in_keys *res_keys;
7561 		int i, key_count;
7562 
7563 		res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7564 
7565 		/*
7566 		 * We had to drop the lock to allocate our buffer, which
7567 		 * leaves time for someone to come in with another
7568 		 * persistent reservation.  (That is unlikely, though,
7569 		 * since this should be the only persistent reservation
7570 		 * command active right now.)
7571 		 */
7572 		if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7573 		    (lun->pr_key_count *
7574 		     sizeof(struct scsi_per_res_key)))){
7575 			mtx_unlock(&lun->lun_lock);
7576 			free(ctsio->kern_data_ptr, M_CTL);
7577 			printf("%s: reservation length changed, retrying\n",
7578 			       __func__);
7579 			goto retry;
7580 		}
7581 
7582 		scsi_ulto4b(lun->pr_generation, res_keys->header.generation);
7583 
7584 		scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7585 			     lun->pr_key_count, res_keys->header.length);
7586 
7587 		for (i = 0, key_count = 0; i < CTL_MAX_INITIATORS; i++) {
7588 			if ((key = ctl_get_prkey(lun, i)) == 0)
7589 				continue;
7590 
7591 			/*
7592 			 * We used lun->pr_key_count to calculate the
7593 			 * size to allocate.  If it turns out the number of
7594 			 * initiators with the registered flag set is
7595 			 * larger than that (i.e. they haven't been kept in
7596 			 * sync), we've got a problem.
7597 			 */
7598 			if (key_count >= lun->pr_key_count) {
7599 				key_count++;
7600 				continue;
7601 			}
7602 			scsi_u64to8b(key, res_keys->keys[key_count].key);
7603 			key_count++;
7604 		}
7605 		break;
7606 	}
7607 	case SPRI_RR: { // read reservation
7608 		struct scsi_per_res_in_rsrv *res;
7609 		int tmp_len, header_only;
7610 
7611 		res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7612 
7613 		scsi_ulto4b(lun->pr_generation, res->header.generation);
7614 
7615 		if (lun->flags & CTL_LUN_PR_RESERVED)
7616 		{
7617 			tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7618 			scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7619 				    res->header.length);
7620 			header_only = 0;
7621 		} else {
7622 			tmp_len = sizeof(struct scsi_per_res_in_header);
7623 			scsi_ulto4b(0, res->header.length);
7624 			header_only = 1;
7625 		}
7626 
7627 		/*
7628 		 * We had to drop the lock to allocate our buffer, which
7629 		 * leaves time for someone to come in with another
7630 		 * persistent reservation.  (That is unlikely, though,
7631 		 * since this should be the only persistent reservation
7632 		 * command active right now.)
7633 		 */
7634 		if (tmp_len != total_len) {
7635 			mtx_unlock(&lun->lun_lock);
7636 			free(ctsio->kern_data_ptr, M_CTL);
7637 			printf("%s: reservation status changed, retrying\n",
7638 			       __func__);
7639 			goto retry;
7640 		}
7641 
7642 		/*
7643 		 * No reservation held, so we're done.
7644 		 */
7645 		if (header_only != 0)
7646 			break;
7647 
7648 		/*
7649 		 * If the registration is an All Registrants type, the key
7650 		 * is 0, since it doesn't really matter.
7651 		 */
7652 		if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7653 			scsi_u64to8b(ctl_get_prkey(lun, lun->pr_res_idx),
7654 			    res->data.reservation);
7655 		}
7656 		res->data.scopetype = lun->pr_res_type;
7657 		break;
7658 	}
7659 	case SPRI_RC:     //report capabilities
7660 	{
7661 		struct scsi_per_res_cap *res_cap;
7662 		uint16_t type_mask;
7663 
7664 		res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7665 		scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7666 		res_cap->flags1 = SPRI_CRH;
7667 		res_cap->flags2 = SPRI_TMV | SPRI_ALLOW_5;
7668 		type_mask = SPRI_TM_WR_EX_AR |
7669 			    SPRI_TM_EX_AC_RO |
7670 			    SPRI_TM_WR_EX_RO |
7671 			    SPRI_TM_EX_AC |
7672 			    SPRI_TM_WR_EX |
7673 			    SPRI_TM_EX_AC_AR;
7674 		scsi_ulto2b(type_mask, res_cap->type_mask);
7675 		break;
7676 	}
7677 	case SPRI_RS: { // read full status
7678 		struct scsi_per_res_in_full *res_status;
7679 		struct scsi_per_res_in_full_desc *res_desc;
7680 		struct ctl_port *port;
7681 		int i, len;
7682 
7683 		res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7684 
7685 		/*
7686 		 * We had to drop the lock to allocate our buffer, which
7687 		 * leaves time for someone to come in with another
7688 		 * persistent reservation.  (That is unlikely, though,
7689 		 * since this should be the only persistent reservation
7690 		 * command active right now.)
7691 		 */
7692 		if (total_len < (sizeof(struct scsi_per_res_in_header) +
7693 		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7694 		     lun->pr_key_count)){
7695 			mtx_unlock(&lun->lun_lock);
7696 			free(ctsio->kern_data_ptr, M_CTL);
7697 			printf("%s: reservation length changed, retrying\n",
7698 			       __func__);
7699 			goto retry;
7700 		}
7701 
7702 		scsi_ulto4b(lun->pr_generation, res_status->header.generation);
7703 
7704 		res_desc = &res_status->desc[0];
7705 		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7706 			if ((key = ctl_get_prkey(lun, i)) == 0)
7707 				continue;
7708 
7709 			scsi_u64to8b(key, res_desc->res_key.key);
7710 			if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7711 			    (lun->pr_res_idx == i ||
7712 			     lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7713 				res_desc->flags = SPRI_FULL_R_HOLDER;
7714 				res_desc->scopetype = lun->pr_res_type;
7715 			}
7716 			scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7717 			    res_desc->rel_trgt_port_id);
7718 			len = 0;
7719 			port = softc->ctl_ports[i / CTL_MAX_INIT_PER_PORT];
7720 			if (port != NULL)
7721 				len = ctl_create_iid(port,
7722 				    i % CTL_MAX_INIT_PER_PORT,
7723 				    res_desc->transport_id);
7724 			scsi_ulto4b(len, res_desc->additional_length);
7725 			res_desc = (struct scsi_per_res_in_full_desc *)
7726 			    &res_desc->transport_id[len];
7727 		}
7728 		scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7729 		    res_status->header.length);
7730 		break;
7731 	}
7732 	default:
7733 		panic("%s: Invalid PR type %#x", __func__, cdb->action);
7734 	}
7735 	mtx_unlock(&lun->lun_lock);
7736 
7737 	ctl_set_success(ctsio);
7738 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7739 	ctsio->be_move_done = ctl_config_move_done;
7740 	ctl_datamove((union ctl_io *)ctsio);
7741 	return (CTL_RETVAL_COMPLETE);
7742 }
7743 
7744 /*
7745  * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
7746  * it should return.
7747  */
7748 static int
7749 ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
7750 		uint64_t sa_res_key, uint8_t type, uint32_t residx,
7751 		struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
7752 		struct scsi_per_res_out_parms* param)
7753 {
7754 	union ctl_ha_msg persis_io;
7755 	int i;
7756 
7757 	mtx_lock(&lun->lun_lock);
7758 	if (sa_res_key == 0) {
7759 		if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
7760 			/* validate scope and type */
7761 			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7762 			     SPR_LU_SCOPE) {
7763 				mtx_unlock(&lun->lun_lock);
7764 				ctl_set_invalid_field(/*ctsio*/ ctsio,
7765 						      /*sks_valid*/ 1,
7766 						      /*command*/ 1,
7767 						      /*field*/ 2,
7768 						      /*bit_valid*/ 1,
7769 						      /*bit*/ 4);
7770 				ctl_done((union ctl_io *)ctsio);
7771 				return (1);
7772 			}
7773 
7774 		        if (type>8 || type==2 || type==4 || type==0) {
7775 				mtx_unlock(&lun->lun_lock);
7776 				ctl_set_invalid_field(/*ctsio*/ ctsio,
7777        	           				      /*sks_valid*/ 1,
7778 						      /*command*/ 1,
7779 						      /*field*/ 2,
7780 						      /*bit_valid*/ 1,
7781 						      /*bit*/ 0);
7782 				ctl_done((union ctl_io *)ctsio);
7783 				return (1);
7784 		        }
7785 
7786 			/*
7787 			 * Unregister everybody else and build UA for
7788 			 * them
7789 			 */
7790 			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
7791 				if (i == residx || ctl_get_prkey(lun, i) == 0)
7792 					continue;
7793 
7794 				ctl_clr_prkey(lun, i);
7795 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7796 			}
7797 			lun->pr_key_count = 1;
7798 			lun->pr_res_type = type;
7799 			if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
7800 			    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
7801 				lun->pr_res_idx = residx;
7802 			lun->pr_generation++;
7803 			mtx_unlock(&lun->lun_lock);
7804 
7805 			/* send msg to other side */
7806 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7807 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7808 			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7809 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
7810 			persis_io.pr.pr_info.res_type = type;
7811 			memcpy(persis_io.pr.pr_info.sa_res_key,
7812 			       param->serv_act_res_key,
7813 			       sizeof(param->serv_act_res_key));
7814 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7815 			    sizeof(persis_io.pr), M_WAITOK);
7816 		} else {
7817 			/* not all registrants */
7818 			mtx_unlock(&lun->lun_lock);
7819 			free(ctsio->kern_data_ptr, M_CTL);
7820 			ctl_set_invalid_field(ctsio,
7821 					      /*sks_valid*/ 1,
7822 					      /*command*/ 0,
7823 					      /*field*/ 8,
7824 					      /*bit_valid*/ 0,
7825 					      /*bit*/ 0);
7826 			ctl_done((union ctl_io *)ctsio);
7827 			return (1);
7828 		}
7829 	} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
7830 		|| !(lun->flags & CTL_LUN_PR_RESERVED)) {
7831 		int found = 0;
7832 
7833 		if (res_key == sa_res_key) {
7834 			/* special case */
7835 			/*
7836 			 * The spec implies this is not good but doesn't
7837 			 * say what to do. There are two choices either
7838 			 * generate a res conflict or check condition
7839 			 * with illegal field in parameter data. Since
7840 			 * that is what is done when the sa_res_key is
7841 			 * zero I'll take that approach since this has
7842 			 * to do with the sa_res_key.
7843 			 */
7844 			mtx_unlock(&lun->lun_lock);
7845 			free(ctsio->kern_data_ptr, M_CTL);
7846 			ctl_set_invalid_field(ctsio,
7847 					      /*sks_valid*/ 1,
7848 					      /*command*/ 0,
7849 					      /*field*/ 8,
7850 					      /*bit_valid*/ 0,
7851 					      /*bit*/ 0);
7852 			ctl_done((union ctl_io *)ctsio);
7853 			return (1);
7854 		}
7855 
7856 		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7857 			if (ctl_get_prkey(lun, i) != sa_res_key)
7858 				continue;
7859 
7860 			found = 1;
7861 			ctl_clr_prkey(lun, i);
7862 			lun->pr_key_count--;
7863 			ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7864 		}
7865 		if (!found) {
7866 			mtx_unlock(&lun->lun_lock);
7867 			free(ctsio->kern_data_ptr, M_CTL);
7868 			ctl_set_reservation_conflict(ctsio);
7869 			ctl_done((union ctl_io *)ctsio);
7870 			return (CTL_RETVAL_COMPLETE);
7871 		}
7872 		lun->pr_generation++;
7873 		mtx_unlock(&lun->lun_lock);
7874 
7875 		/* send msg to other side */
7876 		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7877 		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7878 		persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7879 		persis_io.pr.pr_info.residx = lun->pr_res_idx;
7880 		persis_io.pr.pr_info.res_type = type;
7881 		memcpy(persis_io.pr.pr_info.sa_res_key,
7882 		       param->serv_act_res_key,
7883 		       sizeof(param->serv_act_res_key));
7884 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7885 		    sizeof(persis_io.pr), M_WAITOK);
7886 	} else {
7887 		/* Reserved but not all registrants */
7888 		/* sa_res_key is res holder */
7889 		if (sa_res_key == ctl_get_prkey(lun, lun->pr_res_idx)) {
7890 			/* validate scope and type */
7891 			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7892 			     SPR_LU_SCOPE) {
7893 				mtx_unlock(&lun->lun_lock);
7894 				ctl_set_invalid_field(/*ctsio*/ ctsio,
7895 						      /*sks_valid*/ 1,
7896 						      /*command*/ 1,
7897 						      /*field*/ 2,
7898 						      /*bit_valid*/ 1,
7899 						      /*bit*/ 4);
7900 				ctl_done((union ctl_io *)ctsio);
7901 				return (1);
7902 			}
7903 
7904 			if (type>8 || type==2 || type==4 || type==0) {
7905 				mtx_unlock(&lun->lun_lock);
7906 				ctl_set_invalid_field(/*ctsio*/ ctsio,
7907 						      /*sks_valid*/ 1,
7908 						      /*command*/ 1,
7909 						      /*field*/ 2,
7910 						      /*bit_valid*/ 1,
7911 						      /*bit*/ 0);
7912 				ctl_done((union ctl_io *)ctsio);
7913 				return (1);
7914 			}
7915 
7916 			/*
7917 			 * Do the following:
7918 			 * if sa_res_key != res_key remove all
7919 			 * registrants w/sa_res_key and generate UA
7920 			 * for these registrants(Registrations
7921 			 * Preempted) if it wasn't an exclusive
7922 			 * reservation generate UA(Reservations
7923 			 * Preempted) for all other registered nexuses
7924 			 * if the type has changed. Establish the new
7925 			 * reservation and holder. If res_key and
7926 			 * sa_res_key are the same do the above
7927 			 * except don't unregister the res holder.
7928 			 */
7929 
7930 			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
7931 				if (i == residx || ctl_get_prkey(lun, i) == 0)
7932 					continue;
7933 
7934 				if (sa_res_key == ctl_get_prkey(lun, i)) {
7935 					ctl_clr_prkey(lun, i);
7936 					lun->pr_key_count--;
7937 					ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7938 				} else if (type != lun->pr_res_type &&
7939 				    (lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
7940 				     lun->pr_res_type == SPR_TYPE_EX_AC_RO)) {
7941 					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
7942 				}
7943 			}
7944 			lun->pr_res_type = type;
7945 			if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
7946 			    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
7947 				lun->pr_res_idx = residx;
7948 			else
7949 				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
7950 			lun->pr_generation++;
7951 			mtx_unlock(&lun->lun_lock);
7952 
7953 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7954 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7955 			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7956 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
7957 			persis_io.pr.pr_info.res_type = type;
7958 			memcpy(persis_io.pr.pr_info.sa_res_key,
7959 			       param->serv_act_res_key,
7960 			       sizeof(param->serv_act_res_key));
7961 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7962 			    sizeof(persis_io.pr), M_WAITOK);
7963 		} else {
7964 			/*
7965 			 * sa_res_key is not the res holder just
7966 			 * remove registrants
7967 			 */
7968 			int found=0;
7969 
7970 			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7971 				if (sa_res_key != ctl_get_prkey(lun, i))
7972 					continue;
7973 
7974 				found = 1;
7975 				ctl_clr_prkey(lun, i);
7976 				lun->pr_key_count--;
7977 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7978 			}
7979 
7980 			if (!found) {
7981 				mtx_unlock(&lun->lun_lock);
7982 				free(ctsio->kern_data_ptr, M_CTL);
7983 				ctl_set_reservation_conflict(ctsio);
7984 				ctl_done((union ctl_io *)ctsio);
7985 		        	return (1);
7986 			}
7987 			lun->pr_generation++;
7988 			mtx_unlock(&lun->lun_lock);
7989 
7990 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7991 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7992 			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7993 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
7994 			persis_io.pr.pr_info.res_type = type;
7995 			memcpy(persis_io.pr.pr_info.sa_res_key,
7996 			       param->serv_act_res_key,
7997 			       sizeof(param->serv_act_res_key));
7998 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7999 			    sizeof(persis_io.pr), M_WAITOK);
8000 		}
8001 	}
8002 	return (0);
8003 }
8004 
8005 static void
8006 ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8007 {
8008 	uint64_t sa_res_key;
8009 	int i;
8010 
8011 	sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8012 
8013 	if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8014 	 || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8015 	 || sa_res_key != ctl_get_prkey(lun, lun->pr_res_idx)) {
8016 		if (sa_res_key == 0) {
8017 			/*
8018 			 * Unregister everybody else and build UA for
8019 			 * them
8020 			 */
8021 			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
8022 				if (i == msg->pr.pr_info.residx ||
8023 				    ctl_get_prkey(lun, i) == 0)
8024 					continue;
8025 
8026 				ctl_clr_prkey(lun, i);
8027 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8028 			}
8029 
8030 			lun->pr_key_count = 1;
8031 			lun->pr_res_type = msg->pr.pr_info.res_type;
8032 			if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8033 			    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8034 				lun->pr_res_idx = msg->pr.pr_info.residx;
8035 		} else {
8036 		        for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8037 				if (sa_res_key == ctl_get_prkey(lun, i))
8038 					continue;
8039 
8040 				ctl_clr_prkey(lun, i);
8041 				lun->pr_key_count--;
8042 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8043 			}
8044 		}
8045 	} else {
8046 		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8047 			if (i == msg->pr.pr_info.residx ||
8048 			    ctl_get_prkey(lun, i) == 0)
8049 				continue;
8050 
8051 			if (sa_res_key == ctl_get_prkey(lun, i)) {
8052 				ctl_clr_prkey(lun, i);
8053 				lun->pr_key_count--;
8054 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8055 			} else if (msg->pr.pr_info.res_type != lun->pr_res_type
8056 			    && (lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8057 			     lun->pr_res_type == SPR_TYPE_EX_AC_RO)) {
8058 				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8059 			}
8060 		}
8061 		lun->pr_res_type = msg->pr.pr_info.res_type;
8062 		if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8063 		    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8064 			lun->pr_res_idx = msg->pr.pr_info.residx;
8065 		else
8066 			lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8067 	}
8068 	lun->pr_generation++;
8069 
8070 }
8071 
8072 int
8073 ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8074 {
8075 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
8076 	struct ctl_lun *lun = CTL_LUN(ctsio);
8077 	int retval;
8078 	uint32_t param_len;
8079 	struct scsi_per_res_out *cdb;
8080 	struct scsi_per_res_out_parms* param;
8081 	uint32_t residx;
8082 	uint64_t res_key, sa_res_key, key;
8083 	uint8_t type;
8084 	union ctl_ha_msg persis_io;
8085 	int    i;
8086 
8087 	CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8088 
8089 	cdb = (struct scsi_per_res_out *)ctsio->cdb;
8090 	retval = CTL_RETVAL_COMPLETE;
8091 
8092 	/*
8093 	 * We only support whole-LUN scope.  The scope & type are ignored for
8094 	 * register, register and ignore existing key and clear.
8095 	 * We sometimes ignore scope and type on preempts too!!
8096 	 * Verify reservation type here as well.
8097 	 */
8098 	type = cdb->scope_type & SPR_TYPE_MASK;
8099 	if ((cdb->action == SPRO_RESERVE)
8100 	 || (cdb->action == SPRO_RELEASE)) {
8101 		if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8102 			ctl_set_invalid_field(/*ctsio*/ ctsio,
8103 					      /*sks_valid*/ 1,
8104 					      /*command*/ 1,
8105 					      /*field*/ 2,
8106 					      /*bit_valid*/ 1,
8107 					      /*bit*/ 4);
8108 			ctl_done((union ctl_io *)ctsio);
8109 			return (CTL_RETVAL_COMPLETE);
8110 		}
8111 
8112 		if (type>8 || type==2 || type==4 || type==0) {
8113 			ctl_set_invalid_field(/*ctsio*/ ctsio,
8114 					      /*sks_valid*/ 1,
8115 					      /*command*/ 1,
8116 					      /*field*/ 2,
8117 					      /*bit_valid*/ 1,
8118 					      /*bit*/ 0);
8119 			ctl_done((union ctl_io *)ctsio);
8120 			return (CTL_RETVAL_COMPLETE);
8121 		}
8122 	}
8123 
8124 	param_len = scsi_4btoul(cdb->length);
8125 
8126 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8127 		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8128 		ctsio->kern_data_len = param_len;
8129 		ctsio->kern_total_len = param_len;
8130 		ctsio->kern_rel_offset = 0;
8131 		ctsio->kern_sg_entries = 0;
8132 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8133 		ctsio->be_move_done = ctl_config_move_done;
8134 		ctl_datamove((union ctl_io *)ctsio);
8135 
8136 		return (CTL_RETVAL_COMPLETE);
8137 	}
8138 
8139 	param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8140 
8141 	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
8142 	res_key = scsi_8btou64(param->res_key.key);
8143 	sa_res_key = scsi_8btou64(param->serv_act_res_key);
8144 
8145 	/*
8146 	 * Validate the reservation key here except for SPRO_REG_IGNO
8147 	 * This must be done for all other service actions
8148 	 */
8149 	if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8150 		mtx_lock(&lun->lun_lock);
8151 		if ((key = ctl_get_prkey(lun, residx)) != 0) {
8152 			if (res_key != key) {
8153 				/*
8154 				 * The current key passed in doesn't match
8155 				 * the one the initiator previously
8156 				 * registered.
8157 				 */
8158 				mtx_unlock(&lun->lun_lock);
8159 				free(ctsio->kern_data_ptr, M_CTL);
8160 				ctl_set_reservation_conflict(ctsio);
8161 				ctl_done((union ctl_io *)ctsio);
8162 				return (CTL_RETVAL_COMPLETE);
8163 			}
8164 		} else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8165 			/*
8166 			 * We are not registered
8167 			 */
8168 			mtx_unlock(&lun->lun_lock);
8169 			free(ctsio->kern_data_ptr, M_CTL);
8170 			ctl_set_reservation_conflict(ctsio);
8171 			ctl_done((union ctl_io *)ctsio);
8172 			return (CTL_RETVAL_COMPLETE);
8173 		} else if (res_key != 0) {
8174 			/*
8175 			 * We are not registered and trying to register but
8176 			 * the register key isn't zero.
8177 			 */
8178 			mtx_unlock(&lun->lun_lock);
8179 			free(ctsio->kern_data_ptr, M_CTL);
8180 			ctl_set_reservation_conflict(ctsio);
8181 			ctl_done((union ctl_io *)ctsio);
8182 			return (CTL_RETVAL_COMPLETE);
8183 		}
8184 		mtx_unlock(&lun->lun_lock);
8185 	}
8186 
8187 	switch (cdb->action & SPRO_ACTION_MASK) {
8188 	case SPRO_REGISTER:
8189 	case SPRO_REG_IGNO: {
8190 		/*
8191 		 * We don't support any of these options, as we report in
8192 		 * the read capabilities request (see
8193 		 * ctl_persistent_reserve_in(), above).
8194 		 */
8195 		if ((param->flags & SPR_SPEC_I_PT)
8196 		 || (param->flags & SPR_ALL_TG_PT)
8197 		 || (param->flags & SPR_APTPL)) {
8198 			int bit_ptr;
8199 
8200 			if (param->flags & SPR_APTPL)
8201 				bit_ptr = 0;
8202 			else if (param->flags & SPR_ALL_TG_PT)
8203 				bit_ptr = 2;
8204 			else /* SPR_SPEC_I_PT */
8205 				bit_ptr = 3;
8206 
8207 			free(ctsio->kern_data_ptr, M_CTL);
8208 			ctl_set_invalid_field(ctsio,
8209 					      /*sks_valid*/ 1,
8210 					      /*command*/ 0,
8211 					      /*field*/ 20,
8212 					      /*bit_valid*/ 1,
8213 					      /*bit*/ bit_ptr);
8214 			ctl_done((union ctl_io *)ctsio);
8215 			return (CTL_RETVAL_COMPLETE);
8216 		}
8217 
8218 		mtx_lock(&lun->lun_lock);
8219 
8220 		/*
8221 		 * The initiator wants to clear the
8222 		 * key/unregister.
8223 		 */
8224 		if (sa_res_key == 0) {
8225 			if ((res_key == 0
8226 			  && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8227 			 || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8228 			  && ctl_get_prkey(lun, residx) == 0)) {
8229 				mtx_unlock(&lun->lun_lock);
8230 				goto done;
8231 			}
8232 
8233 			ctl_clr_prkey(lun, residx);
8234 			lun->pr_key_count--;
8235 
8236 			if (residx == lun->pr_res_idx) {
8237 				lun->flags &= ~CTL_LUN_PR_RESERVED;
8238 				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8239 
8240 				if ((lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8241 				     lun->pr_res_type == SPR_TYPE_EX_AC_RO) &&
8242 				    lun->pr_key_count) {
8243 					/*
8244 					 * If the reservation is a registrants
8245 					 * only type we need to generate a UA
8246 					 * for other registered inits.  The
8247 					 * sense code should be RESERVATIONS
8248 					 * RELEASED
8249 					 */
8250 
8251 					for (i = softc->init_min; i < softc->init_max; i++){
8252 						if (ctl_get_prkey(lun, i) == 0)
8253 							continue;
8254 						ctl_est_ua(lun, i,
8255 						    CTL_UA_RES_RELEASE);
8256 					}
8257 				}
8258 				lun->pr_res_type = 0;
8259 			} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8260 				if (lun->pr_key_count==0) {
8261 					lun->flags &= ~CTL_LUN_PR_RESERVED;
8262 					lun->pr_res_type = 0;
8263 					lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8264 				}
8265 			}
8266 			lun->pr_generation++;
8267 			mtx_unlock(&lun->lun_lock);
8268 
8269 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8270 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8271 			persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8272 			persis_io.pr.pr_info.residx = residx;
8273 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8274 			    sizeof(persis_io.pr), M_WAITOK);
8275 		} else /* sa_res_key != 0 */ {
8276 			/*
8277 			 * If we aren't registered currently then increment
8278 			 * the key count and set the registered flag.
8279 			 */
8280 			ctl_alloc_prkey(lun, residx);
8281 			if (ctl_get_prkey(lun, residx) == 0)
8282 				lun->pr_key_count++;
8283 			ctl_set_prkey(lun, residx, sa_res_key);
8284 			lun->pr_generation++;
8285 			mtx_unlock(&lun->lun_lock);
8286 
8287 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8288 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8289 			persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8290 			persis_io.pr.pr_info.residx = residx;
8291 			memcpy(persis_io.pr.pr_info.sa_res_key,
8292 			       param->serv_act_res_key,
8293 			       sizeof(param->serv_act_res_key));
8294 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8295 			    sizeof(persis_io.pr), M_WAITOK);
8296 		}
8297 
8298 		break;
8299 	}
8300 	case SPRO_RESERVE:
8301 		mtx_lock(&lun->lun_lock);
8302 		if (lun->flags & CTL_LUN_PR_RESERVED) {
8303 			/*
8304 			 * if this isn't the reservation holder and it's
8305 			 * not a "all registrants" type or if the type is
8306 			 * different then we have a conflict
8307 			 */
8308 			if ((lun->pr_res_idx != residx
8309 			  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8310 			 || lun->pr_res_type != type) {
8311 				mtx_unlock(&lun->lun_lock);
8312 				free(ctsio->kern_data_ptr, M_CTL);
8313 				ctl_set_reservation_conflict(ctsio);
8314 				ctl_done((union ctl_io *)ctsio);
8315 				return (CTL_RETVAL_COMPLETE);
8316 			}
8317 			mtx_unlock(&lun->lun_lock);
8318 		} else /* create a reservation */ {
8319 			/*
8320 			 * If it's not an "all registrants" type record
8321 			 * reservation holder
8322 			 */
8323 			if (type != SPR_TYPE_WR_EX_AR
8324 			 && type != SPR_TYPE_EX_AC_AR)
8325 				lun->pr_res_idx = residx; /* Res holder */
8326 			else
8327 				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8328 
8329 			lun->flags |= CTL_LUN_PR_RESERVED;
8330 			lun->pr_res_type = type;
8331 
8332 			mtx_unlock(&lun->lun_lock);
8333 
8334 			/* send msg to other side */
8335 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8336 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8337 			persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8338 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8339 			persis_io.pr.pr_info.res_type = type;
8340 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8341 			    sizeof(persis_io.pr), M_WAITOK);
8342 		}
8343 		break;
8344 
8345 	case SPRO_RELEASE:
8346 		mtx_lock(&lun->lun_lock);
8347 		if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8348 			/* No reservation exists return good status */
8349 			mtx_unlock(&lun->lun_lock);
8350 			goto done;
8351 		}
8352 		/*
8353 		 * Is this nexus a reservation holder?
8354 		 */
8355 		if (lun->pr_res_idx != residx
8356 		 && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8357 			/*
8358 			 * not a res holder return good status but
8359 			 * do nothing
8360 			 */
8361 			mtx_unlock(&lun->lun_lock);
8362 			goto done;
8363 		}
8364 
8365 		if (lun->pr_res_type != type) {
8366 			mtx_unlock(&lun->lun_lock);
8367 			free(ctsio->kern_data_ptr, M_CTL);
8368 			ctl_set_illegal_pr_release(ctsio);
8369 			ctl_done((union ctl_io *)ctsio);
8370 			return (CTL_RETVAL_COMPLETE);
8371 		}
8372 
8373 		/* okay to release */
8374 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8375 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8376 		lun->pr_res_type = 0;
8377 
8378 		/*
8379 		 * If this isn't an exclusive access reservation and NUAR
8380 		 * is not set, generate UA for all other registrants.
8381 		 */
8382 		if (type != SPR_TYPE_EX_AC && type != SPR_TYPE_WR_EX &&
8383 		    (lun->MODE_CTRL.queue_flags & SCP_NUAR) == 0) {
8384 			for (i = softc->init_min; i < softc->init_max; i++) {
8385 				if (i == residx || ctl_get_prkey(lun, i) == 0)
8386 					continue;
8387 				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8388 			}
8389 		}
8390 		mtx_unlock(&lun->lun_lock);
8391 
8392 		/* Send msg to other side */
8393 		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8394 		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8395 		persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8396 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8397 		     sizeof(persis_io.pr), M_WAITOK);
8398 		break;
8399 
8400 	case SPRO_CLEAR:
8401 		/* send msg to other side */
8402 
8403 		mtx_lock(&lun->lun_lock);
8404 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8405 		lun->pr_res_type = 0;
8406 		lun->pr_key_count = 0;
8407 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8408 
8409 		ctl_clr_prkey(lun, residx);
8410 		for (i = 0; i < CTL_MAX_INITIATORS; i++)
8411 			if (ctl_get_prkey(lun, i) != 0) {
8412 				ctl_clr_prkey(lun, i);
8413 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8414 			}
8415 		lun->pr_generation++;
8416 		mtx_unlock(&lun->lun_lock);
8417 
8418 		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8419 		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8420 		persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8421 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8422 		     sizeof(persis_io.pr), M_WAITOK);
8423 		break;
8424 
8425 	case SPRO_PREEMPT:
8426 	case SPRO_PRE_ABO: {
8427 		int nretval;
8428 
8429 		nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8430 					  residx, ctsio, cdb, param);
8431 		if (nretval != 0)
8432 			return (CTL_RETVAL_COMPLETE);
8433 		break;
8434 	}
8435 	default:
8436 		panic("%s: Invalid PR type %#x", __func__, cdb->action);
8437 	}
8438 
8439 done:
8440 	free(ctsio->kern_data_ptr, M_CTL);
8441 	ctl_set_success(ctsio);
8442 	ctl_done((union ctl_io *)ctsio);
8443 
8444 	return (retval);
8445 }
8446 
8447 /*
8448  * This routine is for handling a message from the other SC pertaining to
8449  * persistent reserve out. All the error checking will have been done
8450  * so only performing the action need be done here to keep the two
8451  * in sync.
8452  */
8453 static void
8454 ctl_hndl_per_res_out_on_other_sc(union ctl_io *io)
8455 {
8456 	struct ctl_softc *softc = CTL_SOFTC(io);
8457 	union ctl_ha_msg *msg = (union ctl_ha_msg *)&io->presio.pr_msg;
8458 	struct ctl_lun *lun;
8459 	int i;
8460 	uint32_t residx, targ_lun;
8461 
8462 	targ_lun = msg->hdr.nexus.targ_mapped_lun;
8463 	mtx_lock(&softc->ctl_lock);
8464 	if (targ_lun >= ctl_max_luns ||
8465 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
8466 		mtx_unlock(&softc->ctl_lock);
8467 		return;
8468 	}
8469 	mtx_lock(&lun->lun_lock);
8470 	mtx_unlock(&softc->ctl_lock);
8471 	if (lun->flags & CTL_LUN_DISABLED) {
8472 		mtx_unlock(&lun->lun_lock);
8473 		return;
8474 	}
8475 	residx = ctl_get_initindex(&msg->hdr.nexus);
8476 	switch(msg->pr.pr_info.action) {
8477 	case CTL_PR_REG_KEY:
8478 		ctl_alloc_prkey(lun, msg->pr.pr_info.residx);
8479 		if (ctl_get_prkey(lun, msg->pr.pr_info.residx) == 0)
8480 			lun->pr_key_count++;
8481 		ctl_set_prkey(lun, msg->pr.pr_info.residx,
8482 		    scsi_8btou64(msg->pr.pr_info.sa_res_key));
8483 		lun->pr_generation++;
8484 		break;
8485 
8486 	case CTL_PR_UNREG_KEY:
8487 		ctl_clr_prkey(lun, msg->pr.pr_info.residx);
8488 		lun->pr_key_count--;
8489 
8490 		/* XXX Need to see if the reservation has been released */
8491 		/* if so do we need to generate UA? */
8492 		if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8493 			lun->flags &= ~CTL_LUN_PR_RESERVED;
8494 			lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8495 
8496 			if ((lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8497 			     lun->pr_res_type == SPR_TYPE_EX_AC_RO) &&
8498 			    lun->pr_key_count) {
8499 				/*
8500 				 * If the reservation is a registrants
8501 				 * only type we need to generate a UA
8502 				 * for other registered inits.  The
8503 				 * sense code should be RESERVATIONS
8504 				 * RELEASED
8505 				 */
8506 
8507 				for (i = softc->init_min; i < softc->init_max; i++) {
8508 					if (ctl_get_prkey(lun, i) == 0)
8509 						continue;
8510 
8511 					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8512 				}
8513 			}
8514 			lun->pr_res_type = 0;
8515 		} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8516 			if (lun->pr_key_count==0) {
8517 				lun->flags &= ~CTL_LUN_PR_RESERVED;
8518 				lun->pr_res_type = 0;
8519 				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8520 			}
8521 		}
8522 		lun->pr_generation++;
8523 		break;
8524 
8525 	case CTL_PR_RESERVE:
8526 		lun->flags |= CTL_LUN_PR_RESERVED;
8527 		lun->pr_res_type = msg->pr.pr_info.res_type;
8528 		lun->pr_res_idx = msg->pr.pr_info.residx;
8529 
8530 		break;
8531 
8532 	case CTL_PR_RELEASE:
8533 		/*
8534 		 * If this isn't an exclusive access reservation and NUAR
8535 		 * is not set, generate UA for all other registrants.
8536 		 */
8537 		if (lun->pr_res_type != SPR_TYPE_EX_AC &&
8538 		    lun->pr_res_type != SPR_TYPE_WR_EX &&
8539 		    (lun->MODE_CTRL.queue_flags & SCP_NUAR) == 0) {
8540 			for (i = softc->init_min; i < softc->init_max; i++) {
8541 				if (i == residx || ctl_get_prkey(lun, i) == 0)
8542 					continue;
8543 				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8544 			}
8545 		}
8546 
8547 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8548 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8549 		lun->pr_res_type = 0;
8550 		break;
8551 
8552 	case CTL_PR_PREEMPT:
8553 		ctl_pro_preempt_other(lun, msg);
8554 		break;
8555 	case CTL_PR_CLEAR:
8556 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8557 		lun->pr_res_type = 0;
8558 		lun->pr_key_count = 0;
8559 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8560 
8561 		for (i=0; i < CTL_MAX_INITIATORS; i++) {
8562 			if (ctl_get_prkey(lun, i) == 0)
8563 				continue;
8564 			ctl_clr_prkey(lun, i);
8565 			ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8566 		}
8567 		lun->pr_generation++;
8568 		break;
8569 	}
8570 
8571 	mtx_unlock(&lun->lun_lock);
8572 }
8573 
8574 int
8575 ctl_read_write(struct ctl_scsiio *ctsio)
8576 {
8577 	struct ctl_lun *lun = CTL_LUN(ctsio);
8578 	struct ctl_lba_len_flags *lbalen;
8579 	uint64_t lba;
8580 	uint32_t num_blocks;
8581 	int flags, retval;
8582 	int isread;
8583 
8584 	CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8585 
8586 	flags = 0;
8587 	isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8588 	      || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8589 	switch (ctsio->cdb[0]) {
8590 	case READ_6:
8591 	case WRITE_6: {
8592 		struct scsi_rw_6 *cdb;
8593 
8594 		cdb = (struct scsi_rw_6 *)ctsio->cdb;
8595 
8596 		lba = scsi_3btoul(cdb->addr);
8597 		/* only 5 bits are valid in the most significant address byte */
8598 		lba &= 0x1fffff;
8599 		num_blocks = cdb->length;
8600 		/*
8601 		 * This is correct according to SBC-2.
8602 		 */
8603 		if (num_blocks == 0)
8604 			num_blocks = 256;
8605 		break;
8606 	}
8607 	case READ_10:
8608 	case WRITE_10: {
8609 		struct scsi_rw_10 *cdb;
8610 
8611 		cdb = (struct scsi_rw_10 *)ctsio->cdb;
8612 		if (cdb->byte2 & SRW10_FUA)
8613 			flags |= CTL_LLF_FUA;
8614 		if (cdb->byte2 & SRW10_DPO)
8615 			flags |= CTL_LLF_DPO;
8616 		lba = scsi_4btoul(cdb->addr);
8617 		num_blocks = scsi_2btoul(cdb->length);
8618 		break;
8619 	}
8620 	case WRITE_VERIFY_10: {
8621 		struct scsi_write_verify_10 *cdb;
8622 
8623 		cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
8624 		flags |= CTL_LLF_FUA;
8625 		if (cdb->byte2 & SWV_DPO)
8626 			flags |= CTL_LLF_DPO;
8627 		lba = scsi_4btoul(cdb->addr);
8628 		num_blocks = scsi_2btoul(cdb->length);
8629 		break;
8630 	}
8631 	case READ_12:
8632 	case WRITE_12: {
8633 		struct scsi_rw_12 *cdb;
8634 
8635 		cdb = (struct scsi_rw_12 *)ctsio->cdb;
8636 		if (cdb->byte2 & SRW12_FUA)
8637 			flags |= CTL_LLF_FUA;
8638 		if (cdb->byte2 & SRW12_DPO)
8639 			flags |= CTL_LLF_DPO;
8640 		lba = scsi_4btoul(cdb->addr);
8641 		num_blocks = scsi_4btoul(cdb->length);
8642 		break;
8643 	}
8644 	case WRITE_VERIFY_12: {
8645 		struct scsi_write_verify_12 *cdb;
8646 
8647 		cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
8648 		flags |= CTL_LLF_FUA;
8649 		if (cdb->byte2 & SWV_DPO)
8650 			flags |= CTL_LLF_DPO;
8651 		lba = scsi_4btoul(cdb->addr);
8652 		num_blocks = scsi_4btoul(cdb->length);
8653 		break;
8654 	}
8655 	case READ_16:
8656 	case WRITE_16: {
8657 		struct scsi_rw_16 *cdb;
8658 
8659 		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8660 		if (cdb->byte2 & SRW12_FUA)
8661 			flags |= CTL_LLF_FUA;
8662 		if (cdb->byte2 & SRW12_DPO)
8663 			flags |= CTL_LLF_DPO;
8664 		lba = scsi_8btou64(cdb->addr);
8665 		num_blocks = scsi_4btoul(cdb->length);
8666 		break;
8667 	}
8668 	case WRITE_ATOMIC_16: {
8669 		struct scsi_write_atomic_16 *cdb;
8670 
8671 		if (lun->be_lun->atomicblock == 0) {
8672 			ctl_set_invalid_opcode(ctsio);
8673 			ctl_done((union ctl_io *)ctsio);
8674 			return (CTL_RETVAL_COMPLETE);
8675 		}
8676 
8677 		cdb = (struct scsi_write_atomic_16 *)ctsio->cdb;
8678 		if (cdb->byte2 & SRW12_FUA)
8679 			flags |= CTL_LLF_FUA;
8680 		if (cdb->byte2 & SRW12_DPO)
8681 			flags |= CTL_LLF_DPO;
8682 		lba = scsi_8btou64(cdb->addr);
8683 		num_blocks = scsi_2btoul(cdb->length);
8684 		if (num_blocks > lun->be_lun->atomicblock) {
8685 			ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
8686 			    /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
8687 			    /*bit*/ 0);
8688 			ctl_done((union ctl_io *)ctsio);
8689 			return (CTL_RETVAL_COMPLETE);
8690 		}
8691 		break;
8692 	}
8693 	case WRITE_VERIFY_16: {
8694 		struct scsi_write_verify_16 *cdb;
8695 
8696 		cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
8697 		flags |= CTL_LLF_FUA;
8698 		if (cdb->byte2 & SWV_DPO)
8699 			flags |= CTL_LLF_DPO;
8700 		lba = scsi_8btou64(cdb->addr);
8701 		num_blocks = scsi_4btoul(cdb->length);
8702 		break;
8703 	}
8704 	default:
8705 		/*
8706 		 * We got a command we don't support.  This shouldn't
8707 		 * happen, commands should be filtered out above us.
8708 		 */
8709 		ctl_set_invalid_opcode(ctsio);
8710 		ctl_done((union ctl_io *)ctsio);
8711 
8712 		return (CTL_RETVAL_COMPLETE);
8713 		break; /* NOTREACHED */
8714 	}
8715 
8716 	/*
8717 	 * The first check is to make sure we're in bounds, the second
8718 	 * check is to catch wrap-around problems.  If the lba + num blocks
8719 	 * is less than the lba, then we've wrapped around and the block
8720 	 * range is invalid anyway.
8721 	 */
8722 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8723 	 || ((lba + num_blocks) < lba)) {
8724 		ctl_set_lba_out_of_range(ctsio,
8725 		    MAX(lba, lun->be_lun->maxlba + 1));
8726 		ctl_done((union ctl_io *)ctsio);
8727 		return (CTL_RETVAL_COMPLETE);
8728 	}
8729 
8730 	/*
8731 	 * According to SBC-3, a transfer length of 0 is not an error.
8732 	 * Note that this cannot happen with WRITE(6) or READ(6), since 0
8733 	 * translates to 256 blocks for those commands.
8734 	 */
8735 	if (num_blocks == 0) {
8736 		ctl_set_success(ctsio);
8737 		ctl_done((union ctl_io *)ctsio);
8738 		return (CTL_RETVAL_COMPLETE);
8739 	}
8740 
8741 	/* Set FUA and/or DPO if caches are disabled. */
8742 	if (isread) {
8743 		if ((lun->MODE_CACHING.flags1 & SCP_RCD) != 0)
8744 			flags |= CTL_LLF_FUA | CTL_LLF_DPO;
8745 	} else {
8746 		if ((lun->MODE_CACHING.flags1 & SCP_WCE) == 0)
8747 			flags |= CTL_LLF_FUA;
8748 	}
8749 
8750 	lbalen = (struct ctl_lba_len_flags *)
8751 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8752 	lbalen->lba = lba;
8753 	lbalen->len = num_blocks;
8754 	lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
8755 
8756 	ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
8757 	ctsio->kern_rel_offset = 0;
8758 
8759 	CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
8760 
8761 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8762 	return (retval);
8763 }
8764 
8765 static int
8766 ctl_cnw_cont(union ctl_io *io)
8767 {
8768 	struct ctl_lun *lun = CTL_LUN(io);
8769 	struct ctl_scsiio *ctsio;
8770 	struct ctl_lba_len_flags *lbalen;
8771 	int retval;
8772 
8773 	ctsio = &io->scsiio;
8774 	ctsio->io_hdr.status = CTL_STATUS_NONE;
8775 	ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
8776 	lbalen = (struct ctl_lba_len_flags *)
8777 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8778 	lbalen->flags &= ~CTL_LLF_COMPARE;
8779 	lbalen->flags |= CTL_LLF_WRITE;
8780 
8781 	CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
8782 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8783 	return (retval);
8784 }
8785 
8786 int
8787 ctl_cnw(struct ctl_scsiio *ctsio)
8788 {
8789 	struct ctl_lun *lun = CTL_LUN(ctsio);
8790 	struct ctl_lba_len_flags *lbalen;
8791 	uint64_t lba;
8792 	uint32_t num_blocks;
8793 	int flags, retval;
8794 
8795 	CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
8796 
8797 	flags = 0;
8798 	switch (ctsio->cdb[0]) {
8799 	case COMPARE_AND_WRITE: {
8800 		struct scsi_compare_and_write *cdb;
8801 
8802 		cdb = (struct scsi_compare_and_write *)ctsio->cdb;
8803 		if (cdb->byte2 & SRW10_FUA)
8804 			flags |= CTL_LLF_FUA;
8805 		if (cdb->byte2 & SRW10_DPO)
8806 			flags |= CTL_LLF_DPO;
8807 		lba = scsi_8btou64(cdb->addr);
8808 		num_blocks = cdb->length;
8809 		break;
8810 	}
8811 	default:
8812 		/*
8813 		 * We got a command we don't support.  This shouldn't
8814 		 * happen, commands should be filtered out above us.
8815 		 */
8816 		ctl_set_invalid_opcode(ctsio);
8817 		ctl_done((union ctl_io *)ctsio);
8818 
8819 		return (CTL_RETVAL_COMPLETE);
8820 		break; /* NOTREACHED */
8821 	}
8822 
8823 	/*
8824 	 * The first check is to make sure we're in bounds, the second
8825 	 * check is to catch wrap-around problems.  If the lba + num blocks
8826 	 * is less than the lba, then we've wrapped around and the block
8827 	 * range is invalid anyway.
8828 	 */
8829 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8830 	 || ((lba + num_blocks) < lba)) {
8831 		ctl_set_lba_out_of_range(ctsio,
8832 		    MAX(lba, lun->be_lun->maxlba + 1));
8833 		ctl_done((union ctl_io *)ctsio);
8834 		return (CTL_RETVAL_COMPLETE);
8835 	}
8836 
8837 	/*
8838 	 * According to SBC-3, a transfer length of 0 is not an error.
8839 	 */
8840 	if (num_blocks == 0) {
8841 		ctl_set_success(ctsio);
8842 		ctl_done((union ctl_io *)ctsio);
8843 		return (CTL_RETVAL_COMPLETE);
8844 	}
8845 
8846 	/* Set FUA if write cache is disabled. */
8847 	if ((lun->MODE_CACHING.flags1 & SCP_WCE) == 0)
8848 		flags |= CTL_LLF_FUA;
8849 
8850 	ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
8851 	ctsio->kern_rel_offset = 0;
8852 
8853 	/*
8854 	 * Set the IO_CONT flag, so that if this I/O gets passed to
8855 	 * ctl_data_submit_done(), it'll get passed back to
8856 	 * ctl_ctl_cnw_cont() for further processing.
8857 	 */
8858 	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
8859 	ctsio->io_cont = ctl_cnw_cont;
8860 
8861 	lbalen = (struct ctl_lba_len_flags *)
8862 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8863 	lbalen->lba = lba;
8864 	lbalen->len = num_blocks;
8865 	lbalen->flags = CTL_LLF_COMPARE | flags;
8866 
8867 	CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
8868 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8869 	return (retval);
8870 }
8871 
8872 int
8873 ctl_verify(struct ctl_scsiio *ctsio)
8874 {
8875 	struct ctl_lun *lun = CTL_LUN(ctsio);
8876 	struct ctl_lba_len_flags *lbalen;
8877 	uint64_t lba;
8878 	uint32_t num_blocks;
8879 	int bytchk, flags;
8880 	int retval;
8881 
8882 	CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
8883 
8884 	bytchk = 0;
8885 	flags = CTL_LLF_FUA;
8886 	switch (ctsio->cdb[0]) {
8887 	case VERIFY_10: {
8888 		struct scsi_verify_10 *cdb;
8889 
8890 		cdb = (struct scsi_verify_10 *)ctsio->cdb;
8891 		if (cdb->byte2 & SVFY_BYTCHK)
8892 			bytchk = 1;
8893 		if (cdb->byte2 & SVFY_DPO)
8894 			flags |= CTL_LLF_DPO;
8895 		lba = scsi_4btoul(cdb->addr);
8896 		num_blocks = scsi_2btoul(cdb->length);
8897 		break;
8898 	}
8899 	case VERIFY_12: {
8900 		struct scsi_verify_12 *cdb;
8901 
8902 		cdb = (struct scsi_verify_12 *)ctsio->cdb;
8903 		if (cdb->byte2 & SVFY_BYTCHK)
8904 			bytchk = 1;
8905 		if (cdb->byte2 & SVFY_DPO)
8906 			flags |= CTL_LLF_DPO;
8907 		lba = scsi_4btoul(cdb->addr);
8908 		num_blocks = scsi_4btoul(cdb->length);
8909 		break;
8910 	}
8911 	case VERIFY_16: {
8912 		struct scsi_rw_16 *cdb;
8913 
8914 		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8915 		if (cdb->byte2 & SVFY_BYTCHK)
8916 			bytchk = 1;
8917 		if (cdb->byte2 & SVFY_DPO)
8918 			flags |= CTL_LLF_DPO;
8919 		lba = scsi_8btou64(cdb->addr);
8920 		num_blocks = scsi_4btoul(cdb->length);
8921 		break;
8922 	}
8923 	default:
8924 		/*
8925 		 * We got a command we don't support.  This shouldn't
8926 		 * happen, commands should be filtered out above us.
8927 		 */
8928 		ctl_set_invalid_opcode(ctsio);
8929 		ctl_done((union ctl_io *)ctsio);
8930 		return (CTL_RETVAL_COMPLETE);
8931 	}
8932 
8933 	/*
8934 	 * The first check is to make sure we're in bounds, the second
8935 	 * check is to catch wrap-around problems.  If the lba + num blocks
8936 	 * is less than the lba, then we've wrapped around and the block
8937 	 * range is invalid anyway.
8938 	 */
8939 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8940 	 || ((lba + num_blocks) < lba)) {
8941 		ctl_set_lba_out_of_range(ctsio,
8942 		    MAX(lba, lun->be_lun->maxlba + 1));
8943 		ctl_done((union ctl_io *)ctsio);
8944 		return (CTL_RETVAL_COMPLETE);
8945 	}
8946 
8947 	/*
8948 	 * According to SBC-3, a transfer length of 0 is not an error.
8949 	 */
8950 	if (num_blocks == 0) {
8951 		ctl_set_success(ctsio);
8952 		ctl_done((union ctl_io *)ctsio);
8953 		return (CTL_RETVAL_COMPLETE);
8954 	}
8955 
8956 	lbalen = (struct ctl_lba_len_flags *)
8957 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8958 	lbalen->lba = lba;
8959 	lbalen->len = num_blocks;
8960 	if (bytchk) {
8961 		lbalen->flags = CTL_LLF_COMPARE | flags;
8962 		ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
8963 	} else {
8964 		lbalen->flags = CTL_LLF_VERIFY | flags;
8965 		ctsio->kern_total_len = 0;
8966 	}
8967 	ctsio->kern_rel_offset = 0;
8968 
8969 	CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
8970 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8971 	return (retval);
8972 }
8973 
8974 int
8975 ctl_report_luns(struct ctl_scsiio *ctsio)
8976 {
8977 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
8978 	struct ctl_port *port = CTL_PORT(ctsio);
8979 	struct ctl_lun *lun, *request_lun = CTL_LUN(ctsio);
8980 	struct scsi_report_luns *cdb;
8981 	struct scsi_report_luns_data *lun_data;
8982 	int num_filled, num_luns, num_port_luns, retval;
8983 	uint32_t alloc_len, lun_datalen;
8984 	uint32_t initidx, targ_lun_id, lun_id;
8985 
8986 	retval = CTL_RETVAL_COMPLETE;
8987 	cdb = (struct scsi_report_luns *)ctsio->cdb;
8988 
8989 	CTL_DEBUG_PRINT(("ctl_report_luns\n"));
8990 
8991 	num_luns = 0;
8992 	num_port_luns = port->lun_map ? port->lun_map_size : ctl_max_luns;
8993 	mtx_lock(&softc->ctl_lock);
8994 	for (targ_lun_id = 0; targ_lun_id < num_port_luns; targ_lun_id++) {
8995 		if (ctl_lun_map_from_port(port, targ_lun_id) != UINT32_MAX)
8996 			num_luns++;
8997 	}
8998 	mtx_unlock(&softc->ctl_lock);
8999 
9000 	switch (cdb->select_report) {
9001 	case RPL_REPORT_DEFAULT:
9002 	case RPL_REPORT_ALL:
9003 	case RPL_REPORT_NONSUBSID:
9004 		break;
9005 	case RPL_REPORT_WELLKNOWN:
9006 	case RPL_REPORT_ADMIN:
9007 	case RPL_REPORT_CONGLOM:
9008 		num_luns = 0;
9009 		break;
9010 	default:
9011 		ctl_set_invalid_field(ctsio,
9012 				      /*sks_valid*/ 1,
9013 				      /*command*/ 1,
9014 				      /*field*/ 2,
9015 				      /*bit_valid*/ 0,
9016 				      /*bit*/ 0);
9017 		ctl_done((union ctl_io *)ctsio);
9018 		return (retval);
9019 		break; /* NOTREACHED */
9020 	}
9021 
9022 	alloc_len = scsi_4btoul(cdb->length);
9023 	/*
9024 	 * The initiator has to allocate at least 16 bytes for this request,
9025 	 * so he can at least get the header and the first LUN.  Otherwise
9026 	 * we reject the request (per SPC-3 rev 14, section 6.21).
9027 	 */
9028 	if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9029 	    sizeof(struct scsi_report_luns_lundata))) {
9030 		ctl_set_invalid_field(ctsio,
9031 				      /*sks_valid*/ 1,
9032 				      /*command*/ 1,
9033 				      /*field*/ 6,
9034 				      /*bit_valid*/ 0,
9035 				      /*bit*/ 0);
9036 		ctl_done((union ctl_io *)ctsio);
9037 		return (retval);
9038 	}
9039 
9040 	lun_datalen = sizeof(*lun_data) +
9041 		(num_luns * sizeof(struct scsi_report_luns_lundata));
9042 
9043 	ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9044 	lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9045 	ctsio->kern_sg_entries = 0;
9046 
9047 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9048 
9049 	mtx_lock(&softc->ctl_lock);
9050 	for (targ_lun_id = 0, num_filled = 0;
9051 	    targ_lun_id < num_port_luns && num_filled < num_luns;
9052 	    targ_lun_id++) {
9053 		lun_id = ctl_lun_map_from_port(port, targ_lun_id);
9054 		if (lun_id == UINT32_MAX)
9055 			continue;
9056 		lun = softc->ctl_luns[lun_id];
9057 		if (lun == NULL)
9058 			continue;
9059 
9060 		be64enc(lun_data->luns[num_filled++].lundata,
9061 		    ctl_encode_lun(targ_lun_id));
9062 
9063 		/*
9064 		 * According to SPC-3, rev 14 section 6.21:
9065 		 *
9066 		 * "The execution of a REPORT LUNS command to any valid and
9067 		 * installed logical unit shall clear the REPORTED LUNS DATA
9068 		 * HAS CHANGED unit attention condition for all logical
9069 		 * units of that target with respect to the requesting
9070 		 * initiator. A valid and installed logical unit is one
9071 		 * having a PERIPHERAL QUALIFIER of 000b in the standard
9072 		 * INQUIRY data (see 6.4.2)."
9073 		 *
9074 		 * If request_lun is NULL, the LUN this report luns command
9075 		 * was issued to is either disabled or doesn't exist. In that
9076 		 * case, we shouldn't clear any pending lun change unit
9077 		 * attention.
9078 		 */
9079 		if (request_lun != NULL) {
9080 			mtx_lock(&lun->lun_lock);
9081 			ctl_clr_ua(lun, initidx, CTL_UA_LUN_CHANGE);
9082 			mtx_unlock(&lun->lun_lock);
9083 		}
9084 	}
9085 	mtx_unlock(&softc->ctl_lock);
9086 
9087 	/*
9088 	 * It's quite possible that we've returned fewer LUNs than we allocated
9089 	 * space for.  Trim it.
9090 	 */
9091 	lun_datalen = sizeof(*lun_data) +
9092 		(num_filled * sizeof(struct scsi_report_luns_lundata));
9093 	ctsio->kern_rel_offset = 0;
9094 	ctsio->kern_sg_entries = 0;
9095 	ctsio->kern_data_len = min(lun_datalen, alloc_len);
9096 	ctsio->kern_total_len = ctsio->kern_data_len;
9097 
9098 	/*
9099 	 * We set this to the actual data length, regardless of how much
9100 	 * space we actually have to return results.  If the user looks at
9101 	 * this value, he'll know whether or not he allocated enough space
9102 	 * and reissue the command if necessary.  We don't support well
9103 	 * known logical units, so if the user asks for that, return none.
9104 	 */
9105 	scsi_ulto4b(lun_datalen - 8, lun_data->length);
9106 
9107 	/*
9108 	 * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9109 	 * this request.
9110 	 */
9111 	ctl_set_success(ctsio);
9112 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9113 	ctsio->be_move_done = ctl_config_move_done;
9114 	ctl_datamove((union ctl_io *)ctsio);
9115 	return (retval);
9116 }
9117 
9118 int
9119 ctl_request_sense(struct ctl_scsiio *ctsio)
9120 {
9121 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9122 	struct ctl_lun *lun = CTL_LUN(ctsio);
9123 	struct scsi_request_sense *cdb;
9124 	struct scsi_sense_data *sense_ptr, *ps;
9125 	uint32_t initidx;
9126 	int have_error;
9127 	u_int sense_len = SSD_FULL_SIZE;
9128 	scsi_sense_data_type sense_format;
9129 	ctl_ua_type ua_type;
9130 	uint8_t asc = 0, ascq = 0;
9131 
9132 	cdb = (struct scsi_request_sense *)ctsio->cdb;
9133 
9134 	CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9135 
9136 	/*
9137 	 * Determine which sense format the user wants.
9138 	 */
9139 	if (cdb->byte2 & SRS_DESC)
9140 		sense_format = SSD_TYPE_DESC;
9141 	else
9142 		sense_format = SSD_TYPE_FIXED;
9143 
9144 	ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9145 	sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9146 	ctsio->kern_sg_entries = 0;
9147 	ctsio->kern_rel_offset = 0;
9148 
9149 	/*
9150 	 * struct scsi_sense_data, which is currently set to 256 bytes, is
9151 	 * larger than the largest allowed value for the length field in the
9152 	 * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9153 	 */
9154 	ctsio->kern_data_len = cdb->length;
9155 	ctsio->kern_total_len = cdb->length;
9156 
9157 	/*
9158 	 * If we don't have a LUN, we don't have any pending sense.
9159 	 */
9160 	if (lun == NULL ||
9161 	    ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
9162 	     softc->ha_link < CTL_HA_LINK_UNKNOWN)) {
9163 		/* "Logical unit not supported" */
9164 		ctl_set_sense_data(sense_ptr, &sense_len, NULL, sense_format,
9165 		    /*current_error*/ 1,
9166 		    /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
9167 		    /*asc*/ 0x25,
9168 		    /*ascq*/ 0x00,
9169 		    SSD_ELEM_NONE);
9170 		goto send;
9171 	}
9172 
9173 	have_error = 0;
9174 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9175 	/*
9176 	 * Check for pending sense, and then for pending unit attentions.
9177 	 * Pending sense gets returned first, then pending unit attentions.
9178 	 */
9179 	mtx_lock(&lun->lun_lock);
9180 	ps = lun->pending_sense[initidx / CTL_MAX_INIT_PER_PORT];
9181 	if (ps != NULL)
9182 		ps += initidx % CTL_MAX_INIT_PER_PORT;
9183 	if (ps != NULL && ps->error_code != 0) {
9184 		scsi_sense_data_type stored_format;
9185 
9186 		/*
9187 		 * Check to see which sense format was used for the stored
9188 		 * sense data.
9189 		 */
9190 		stored_format = scsi_sense_type(ps);
9191 
9192 		/*
9193 		 * If the user requested a different sense format than the
9194 		 * one we stored, then we need to convert it to the other
9195 		 * format.  If we're going from descriptor to fixed format
9196 		 * sense data, we may lose things in translation, depending
9197 		 * on what options were used.
9198 		 *
9199 		 * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9200 		 * for some reason we'll just copy it out as-is.
9201 		 */
9202 		if ((stored_format == SSD_TYPE_FIXED)
9203 		 && (sense_format == SSD_TYPE_DESC))
9204 			ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9205 			    ps, (struct scsi_sense_data_desc *)sense_ptr);
9206 		else if ((stored_format == SSD_TYPE_DESC)
9207 		      && (sense_format == SSD_TYPE_FIXED))
9208 			ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9209 			    ps, (struct scsi_sense_data_fixed *)sense_ptr);
9210 		else
9211 			memcpy(sense_ptr, ps, sizeof(*sense_ptr));
9212 
9213 		ps->error_code = 0;
9214 		have_error = 1;
9215 	} else {
9216 		ua_type = ctl_build_ua(lun, initidx, sense_ptr, &sense_len,
9217 		    sense_format);
9218 		if (ua_type != CTL_UA_NONE)
9219 			have_error = 1;
9220 	}
9221 	if (have_error == 0) {
9222 		/*
9223 		 * Report informational exception if have one and allowed.
9224 		 */
9225 		if (lun->MODE_IE.mrie != SIEP_MRIE_NO) {
9226 			asc = lun->ie_asc;
9227 			ascq = lun->ie_ascq;
9228 		}
9229 		ctl_set_sense_data(sense_ptr, &sense_len, lun, sense_format,
9230 		    /*current_error*/ 1,
9231 		    /*sense_key*/ SSD_KEY_NO_SENSE,
9232 		    /*asc*/ asc,
9233 		    /*ascq*/ ascq,
9234 		    SSD_ELEM_NONE);
9235 	}
9236 	mtx_unlock(&lun->lun_lock);
9237 
9238 send:
9239 	/*
9240 	 * We report the SCSI status as OK, since the status of the command
9241 	 * itself is OK.  We're reporting sense as parameter data.
9242 	 */
9243 	ctl_set_success(ctsio);
9244 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9245 	ctsio->be_move_done = ctl_config_move_done;
9246 	ctl_datamove((union ctl_io *)ctsio);
9247 	return (CTL_RETVAL_COMPLETE);
9248 }
9249 
9250 int
9251 ctl_tur(struct ctl_scsiio *ctsio)
9252 {
9253 
9254 	CTL_DEBUG_PRINT(("ctl_tur\n"));
9255 
9256 	ctl_set_success(ctsio);
9257 	ctl_done((union ctl_io *)ctsio);
9258 
9259 	return (CTL_RETVAL_COMPLETE);
9260 }
9261 
9262 /*
9263  * SCSI VPD page 0x00, the Supported VPD Pages page.
9264  */
9265 static int
9266 ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9267 {
9268 	struct ctl_lun *lun = CTL_LUN(ctsio);
9269 	struct scsi_vpd_supported_pages *pages;
9270 	int sup_page_size;
9271 	int p;
9272 
9273 	sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9274 	    SCSI_EVPD_NUM_SUPPORTED_PAGES;
9275 	ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9276 	pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9277 	ctsio->kern_rel_offset = 0;
9278 	ctsio->kern_sg_entries = 0;
9279 	ctsio->kern_data_len = min(sup_page_size, alloc_len);
9280 	ctsio->kern_total_len = ctsio->kern_data_len;
9281 
9282 	/*
9283 	 * The control device is always connected.  The disk device, on the
9284 	 * other hand, may not be online all the time.  Need to change this
9285 	 * to figure out whether the disk device is actually online or not.
9286 	 */
9287 	if (lun != NULL)
9288 		pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9289 				lun->be_lun->lun_type;
9290 	else
9291 		pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9292 
9293 	p = 0;
9294 	/* Supported VPD pages */
9295 	pages->page_list[p++] = SVPD_SUPPORTED_PAGES;
9296 	/* Serial Number */
9297 	pages->page_list[p++] = SVPD_UNIT_SERIAL_NUMBER;
9298 	/* Device Identification */
9299 	pages->page_list[p++] = SVPD_DEVICE_ID;
9300 	/* Extended INQUIRY Data */
9301 	pages->page_list[p++] = SVPD_EXTENDED_INQUIRY_DATA;
9302 	/* Mode Page Policy */
9303 	pages->page_list[p++] = SVPD_MODE_PAGE_POLICY;
9304 	/* SCSI Ports */
9305 	pages->page_list[p++] = SVPD_SCSI_PORTS;
9306 	/* Third-party Copy */
9307 	pages->page_list[p++] = SVPD_SCSI_TPC;
9308 	/* SCSI Feature Sets */
9309 	pages->page_list[p++] = SVPD_SCSI_SFS;
9310 	if (lun != NULL && lun->be_lun->lun_type == T_DIRECT) {
9311 		/* Block limits */
9312 		pages->page_list[p++] = SVPD_BLOCK_LIMITS;
9313 		/* Block Device Characteristics */
9314 		pages->page_list[p++] = SVPD_BDC;
9315 		/* Logical Block Provisioning */
9316 		pages->page_list[p++] = SVPD_LBP;
9317 	}
9318 	pages->length = p;
9319 
9320 	ctl_set_success(ctsio);
9321 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9322 	ctsio->be_move_done = ctl_config_move_done;
9323 	ctl_datamove((union ctl_io *)ctsio);
9324 	return (CTL_RETVAL_COMPLETE);
9325 }
9326 
9327 /*
9328  * SCSI VPD page 0x80, the Unit Serial Number page.
9329  */
9330 static int
9331 ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9332 {
9333 	struct ctl_lun *lun = CTL_LUN(ctsio);
9334 	struct scsi_vpd_unit_serial_number *sn_ptr;
9335 	int data_len;
9336 
9337 	data_len = 4 + CTL_SN_LEN;
9338 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9339 	sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9340 	ctsio->kern_rel_offset = 0;
9341 	ctsio->kern_sg_entries = 0;
9342 	ctsio->kern_data_len = min(data_len, alloc_len);
9343 	ctsio->kern_total_len = ctsio->kern_data_len;
9344 
9345 	/*
9346 	 * The control device is always connected.  The disk device, on the
9347 	 * other hand, may not be online all the time.  Need to change this
9348 	 * to figure out whether the disk device is actually online or not.
9349 	 */
9350 	if (lun != NULL)
9351 		sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9352 				  lun->be_lun->lun_type;
9353 	else
9354 		sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9355 
9356 	sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9357 	sn_ptr->length = CTL_SN_LEN;
9358 	/*
9359 	 * If we don't have a LUN, we just leave the serial number as
9360 	 * all spaces.
9361 	 */
9362 	if (lun != NULL) {
9363 		strncpy((char *)sn_ptr->serial_num,
9364 			(char *)lun->be_lun->serial_num, CTL_SN_LEN);
9365 	} else
9366 		memset(sn_ptr->serial_num, 0x20, CTL_SN_LEN);
9367 
9368 	ctl_set_success(ctsio);
9369 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9370 	ctsio->be_move_done = ctl_config_move_done;
9371 	ctl_datamove((union ctl_io *)ctsio);
9372 	return (CTL_RETVAL_COMPLETE);
9373 }
9374 
9375 /*
9376  * SCSI VPD page 0x86, the Extended INQUIRY Data page.
9377  */
9378 static int
9379 ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9380 {
9381 	struct ctl_lun *lun = CTL_LUN(ctsio);
9382 	struct scsi_vpd_extended_inquiry_data *eid_ptr;
9383 	int data_len;
9384 
9385 	data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
9386 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9387 	eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9388 	ctsio->kern_sg_entries = 0;
9389 	ctsio->kern_rel_offset = 0;
9390 	ctsio->kern_data_len = min(data_len, alloc_len);
9391 	ctsio->kern_total_len = ctsio->kern_data_len;
9392 
9393 	/*
9394 	 * The control device is always connected.  The disk device, on the
9395 	 * other hand, may not be online all the time.
9396 	 */
9397 	if (lun != NULL)
9398 		eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9399 				     lun->be_lun->lun_type;
9400 	else
9401 		eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9402 	eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9403 	scsi_ulto2b(data_len - 4, eid_ptr->page_length);
9404 	/*
9405 	 * We support head of queue, ordered and simple tags.
9406 	 */
9407 	eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9408 	/*
9409 	 * Volatile cache supported.
9410 	 */
9411 	eid_ptr->flags3 = SVPD_EID_V_SUP;
9412 
9413 	/*
9414 	 * This means that we clear the REPORTED LUNS DATA HAS CHANGED unit
9415 	 * attention for a particular IT nexus on all LUNs once we report
9416 	 * it to that nexus once.  This bit is required as of SPC-4.
9417 	 */
9418 	eid_ptr->flags4 = SVPD_EID_LUICLR;
9419 
9420 	/*
9421 	 * We support revert to defaults (RTD) bit in MODE SELECT.
9422 	 */
9423 	eid_ptr->flags5 = SVPD_EID_RTD_SUP;
9424 
9425 	/*
9426 	 * XXX KDM in order to correctly answer this, we would need
9427 	 * information from the SIM to determine how much sense data it
9428 	 * can send.  So this would really be a path inquiry field, most
9429 	 * likely.  This can be set to a maximum of 252 according to SPC-4,
9430 	 * but the hardware may or may not be able to support that much.
9431 	 * 0 just means that the maximum sense data length is not reported.
9432 	 */
9433 	eid_ptr->max_sense_length = 0;
9434 
9435 	ctl_set_success(ctsio);
9436 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9437 	ctsio->be_move_done = ctl_config_move_done;
9438 	ctl_datamove((union ctl_io *)ctsio);
9439 	return (CTL_RETVAL_COMPLETE);
9440 }
9441 
9442 static int
9443 ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
9444 {
9445 	struct ctl_lun *lun = CTL_LUN(ctsio);
9446 	struct scsi_vpd_mode_page_policy *mpp_ptr;
9447 	int data_len;
9448 
9449 	data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9450 	    sizeof(struct scsi_vpd_mode_page_policy_descr);
9451 
9452 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9453 	mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
9454 	ctsio->kern_rel_offset = 0;
9455 	ctsio->kern_sg_entries = 0;
9456 	ctsio->kern_data_len = min(data_len, alloc_len);
9457 	ctsio->kern_total_len = ctsio->kern_data_len;
9458 
9459 	/*
9460 	 * The control device is always connected.  The disk device, on the
9461 	 * other hand, may not be online all the time.
9462 	 */
9463 	if (lun != NULL)
9464 		mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9465 				     lun->be_lun->lun_type;
9466 	else
9467 		mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9468 	mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
9469 	scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
9470 	mpp_ptr->descr[0].page_code = 0x3f;
9471 	mpp_ptr->descr[0].subpage_code = 0xff;
9472 	mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
9473 
9474 	ctl_set_success(ctsio);
9475 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9476 	ctsio->be_move_done = ctl_config_move_done;
9477 	ctl_datamove((union ctl_io *)ctsio);
9478 	return (CTL_RETVAL_COMPLETE);
9479 }
9480 
9481 /*
9482  * SCSI VPD page 0x83, the Device Identification page.
9483  */
9484 static int
9485 ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9486 {
9487 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9488 	struct ctl_port *port = CTL_PORT(ctsio);
9489 	struct ctl_lun *lun = CTL_LUN(ctsio);
9490 	struct scsi_vpd_device_id *devid_ptr;
9491 	struct scsi_vpd_id_descriptor *desc;
9492 	int data_len, g;
9493 	uint8_t proto;
9494 
9495 	data_len = sizeof(struct scsi_vpd_device_id) +
9496 	    sizeof(struct scsi_vpd_id_descriptor) +
9497 		sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9498 	    sizeof(struct scsi_vpd_id_descriptor) +
9499 		sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9500 	if (lun && lun->lun_devid)
9501 		data_len += lun->lun_devid->len;
9502 	if (port && port->port_devid)
9503 		data_len += port->port_devid->len;
9504 	if (port && port->target_devid)
9505 		data_len += port->target_devid->len;
9506 
9507 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9508 	devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9509 	ctsio->kern_sg_entries = 0;
9510 	ctsio->kern_rel_offset = 0;
9511 	ctsio->kern_sg_entries = 0;
9512 	ctsio->kern_data_len = min(data_len, alloc_len);
9513 	ctsio->kern_total_len = ctsio->kern_data_len;
9514 
9515 	/*
9516 	 * The control device is always connected.  The disk device, on the
9517 	 * other hand, may not be online all the time.
9518 	 */
9519 	if (lun != NULL)
9520 		devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9521 				     lun->be_lun->lun_type;
9522 	else
9523 		devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9524 	devid_ptr->page_code = SVPD_DEVICE_ID;
9525 	scsi_ulto2b(data_len - 4, devid_ptr->length);
9526 
9527 	if (port && port->port_type == CTL_PORT_FC)
9528 		proto = SCSI_PROTO_FC << 4;
9529 	else if (port && port->port_type == CTL_PORT_SAS)
9530 		proto = SCSI_PROTO_SAS << 4;
9531 	else if (port && port->port_type == CTL_PORT_ISCSI)
9532 		proto = SCSI_PROTO_ISCSI << 4;
9533 	else
9534 		proto = SCSI_PROTO_SPI << 4;
9535 	desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
9536 
9537 	/*
9538 	 * We're using a LUN association here.  i.e., this device ID is a
9539 	 * per-LUN identifier.
9540 	 */
9541 	if (lun && lun->lun_devid) {
9542 		memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
9543 		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9544 		    lun->lun_devid->len);
9545 	}
9546 
9547 	/*
9548 	 * This is for the WWPN which is a port association.
9549 	 */
9550 	if (port && port->port_devid) {
9551 		memcpy(desc, port->port_devid->data, port->port_devid->len);
9552 		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9553 		    port->port_devid->len);
9554 	}
9555 
9556 	/*
9557 	 * This is for the Relative Target Port(type 4h) identifier
9558 	 */
9559 	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9560 	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9561 	    SVPD_ID_TYPE_RELTARG;
9562 	desc->length = 4;
9563 	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
9564 	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9565 	    sizeof(struct scsi_vpd_id_rel_trgt_port_id));
9566 
9567 	/*
9568 	 * This is for the Target Port Group(type 5h) identifier
9569 	 */
9570 	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9571 	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9572 	    SVPD_ID_TYPE_TPORTGRP;
9573 	desc->length = 4;
9574 	if (softc->is_single ||
9575 	    (port && port->status & CTL_PORT_STATUS_HA_SHARED))
9576 		g = 1;
9577 	else
9578 		g = 2 + ctsio->io_hdr.nexus.targ_port / softc->port_cnt;
9579 	scsi_ulto2b(g, &desc->identifier[2]);
9580 	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9581 	    sizeof(struct scsi_vpd_id_trgt_port_grp_id));
9582 
9583 	/*
9584 	 * This is for the Target identifier
9585 	 */
9586 	if (port && port->target_devid) {
9587 		memcpy(desc, port->target_devid->data, port->target_devid->len);
9588 	}
9589 
9590 	ctl_set_success(ctsio);
9591 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9592 	ctsio->be_move_done = ctl_config_move_done;
9593 	ctl_datamove((union ctl_io *)ctsio);
9594 	return (CTL_RETVAL_COMPLETE);
9595 }
9596 
9597 static int
9598 ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
9599 {
9600 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9601 	struct ctl_lun *lun = CTL_LUN(ctsio);
9602 	struct scsi_vpd_scsi_ports *sp;
9603 	struct scsi_vpd_port_designation *pd;
9604 	struct scsi_vpd_port_designation_cont *pdc;
9605 	struct ctl_port *port;
9606 	int data_len, num_target_ports, iid_len, id_len;
9607 
9608 	num_target_ports = 0;
9609 	iid_len = 0;
9610 	id_len = 0;
9611 	mtx_lock(&softc->ctl_lock);
9612 	STAILQ_FOREACH(port, &softc->port_list, links) {
9613 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9614 			continue;
9615 		if (lun != NULL &&
9616 		    ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
9617 			continue;
9618 		num_target_ports++;
9619 		if (port->init_devid)
9620 			iid_len += port->init_devid->len;
9621 		if (port->port_devid)
9622 			id_len += port->port_devid->len;
9623 	}
9624 	mtx_unlock(&softc->ctl_lock);
9625 
9626 	data_len = sizeof(struct scsi_vpd_scsi_ports) +
9627 	    num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
9628 	     sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
9629 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9630 	sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
9631 	ctsio->kern_sg_entries = 0;
9632 	ctsio->kern_rel_offset = 0;
9633 	ctsio->kern_sg_entries = 0;
9634 	ctsio->kern_data_len = min(data_len, alloc_len);
9635 	ctsio->kern_total_len = ctsio->kern_data_len;
9636 
9637 	/*
9638 	 * The control device is always connected.  The disk device, on the
9639 	 * other hand, may not be online all the time.  Need to change this
9640 	 * to figure out whether the disk device is actually online or not.
9641 	 */
9642 	if (lun != NULL)
9643 		sp->device = (SID_QUAL_LU_CONNECTED << 5) |
9644 				  lun->be_lun->lun_type;
9645 	else
9646 		sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9647 
9648 	sp->page_code = SVPD_SCSI_PORTS;
9649 	scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
9650 	    sp->page_length);
9651 	pd = &sp->design[0];
9652 
9653 	mtx_lock(&softc->ctl_lock);
9654 	STAILQ_FOREACH(port, &softc->port_list, links) {
9655 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9656 			continue;
9657 		if (lun != NULL &&
9658 		    ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
9659 			continue;
9660 		scsi_ulto2b(port->targ_port, pd->relative_port_id);
9661 		if (port->init_devid) {
9662 			iid_len = port->init_devid->len;
9663 			memcpy(pd->initiator_transportid,
9664 			    port->init_devid->data, port->init_devid->len);
9665 		} else
9666 			iid_len = 0;
9667 		scsi_ulto2b(iid_len, pd->initiator_transportid_length);
9668 		pdc = (struct scsi_vpd_port_designation_cont *)
9669 		    (&pd->initiator_transportid[iid_len]);
9670 		if (port->port_devid) {
9671 			id_len = port->port_devid->len;
9672 			memcpy(pdc->target_port_descriptors,
9673 			    port->port_devid->data, port->port_devid->len);
9674 		} else
9675 			id_len = 0;
9676 		scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
9677 		pd = (struct scsi_vpd_port_designation *)
9678 		    ((uint8_t *)pdc->target_port_descriptors + id_len);
9679 	}
9680 	mtx_unlock(&softc->ctl_lock);
9681 
9682 	ctl_set_success(ctsio);
9683 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9684 	ctsio->be_move_done = ctl_config_move_done;
9685 	ctl_datamove((union ctl_io *)ctsio);
9686 	return (CTL_RETVAL_COMPLETE);
9687 }
9688 
9689 static int
9690 ctl_inquiry_evpd_sfs(struct ctl_scsiio *ctsio, int alloc_len)
9691 {
9692 	struct ctl_lun *lun = CTL_LUN(ctsio);
9693 	struct scsi_vpd_sfs *sfs_ptr;
9694 	int sfs_page_size, n;
9695 
9696 	sfs_page_size = sizeof(*sfs_ptr) + 5 * 2;
9697 	ctsio->kern_data_ptr = malloc(sfs_page_size, M_CTL, M_WAITOK | M_ZERO);
9698 	sfs_ptr = (struct scsi_vpd_sfs *)ctsio->kern_data_ptr;
9699 	ctsio->kern_sg_entries = 0;
9700 	ctsio->kern_rel_offset = 0;
9701 	ctsio->kern_sg_entries = 0;
9702 	ctsio->kern_data_len = min(sfs_page_size, alloc_len);
9703 	ctsio->kern_total_len = ctsio->kern_data_len;
9704 
9705 	/*
9706 	 * The control device is always connected.  The disk device, on the
9707 	 * other hand, may not be online all the time.  Need to change this
9708 	 * to figure out whether the disk device is actually online or not.
9709 	 */
9710 	if (lun != NULL)
9711 		sfs_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9712 				  lun->be_lun->lun_type;
9713 	else
9714 		sfs_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9715 
9716 	sfs_ptr->page_code = SVPD_SCSI_SFS;
9717 	n = 0;
9718 	/* Discovery 2016 */
9719 	scsi_ulto2b(0x0001, &sfs_ptr->codes[2 * n++]);
9720 	if (lun != NULL && lun->be_lun->lun_type == T_DIRECT) {
9721 		 /* SBC Base 2016 */
9722 		scsi_ulto2b(0x0101, &sfs_ptr->codes[2 * n++]);
9723 		 /* SBC Base 2010 */
9724 		scsi_ulto2b(0x0102, &sfs_ptr->codes[2 * n++]);
9725 		if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9726 			/* Basic Provisioning 2016 */
9727 			scsi_ulto2b(0x0103, &sfs_ptr->codes[2 * n++]);
9728 		}
9729 		/* Drive Maintenance 2016 */
9730 		//scsi_ulto2b(0x0104, &sfs_ptr->codes[2 * n++]);
9731 	}
9732 	scsi_ulto2b(4 + 2 * n, sfs_ptr->page_length);
9733 
9734 	ctl_set_success(ctsio);
9735 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9736 	ctsio->be_move_done = ctl_config_move_done;
9737 	ctl_datamove((union ctl_io *)ctsio);
9738 	return (CTL_RETVAL_COMPLETE);
9739 }
9740 
9741 static int
9742 ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
9743 {
9744 	struct ctl_lun *lun = CTL_LUN(ctsio);
9745 	struct scsi_vpd_block_limits *bl_ptr;
9746 	const char *val;
9747 	uint64_t ival;
9748 
9749 	ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
9750 	bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
9751 	ctsio->kern_sg_entries = 0;
9752 	ctsio->kern_rel_offset = 0;
9753 	ctsio->kern_sg_entries = 0;
9754 	ctsio->kern_data_len = min(sizeof(*bl_ptr), alloc_len);
9755 	ctsio->kern_total_len = ctsio->kern_data_len;
9756 
9757 	/*
9758 	 * The control device is always connected.  The disk device, on the
9759 	 * other hand, may not be online all the time.  Need to change this
9760 	 * to figure out whether the disk device is actually online or not.
9761 	 */
9762 	if (lun != NULL)
9763 		bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9764 				  lun->be_lun->lun_type;
9765 	else
9766 		bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9767 
9768 	bl_ptr->page_code = SVPD_BLOCK_LIMITS;
9769 	scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
9770 	bl_ptr->max_cmp_write_len = 0xff;
9771 	scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
9772 	if (lun != NULL) {
9773 		scsi_ulto4b(lun->be_lun->opttxferlen, bl_ptr->opt_txfer_len);
9774 		if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9775 			ival = 0xffffffff;
9776 			val = dnvlist_get_string(lun->be_lun->options,
9777 			    "unmap_max_lba", NULL);
9778 			if (val != NULL)
9779 				ctl_expand_number(val, &ival);
9780 			scsi_ulto4b(ival, bl_ptr->max_unmap_lba_cnt);
9781 			ival = 0xffffffff;
9782 			val = dnvlist_get_string(lun->be_lun->options,
9783 			    "unmap_max_descr", NULL);
9784 			if (val != NULL)
9785 				ctl_expand_number(val, &ival);
9786 			scsi_ulto4b(ival, bl_ptr->max_unmap_blk_cnt);
9787 			if (lun->be_lun->ublockexp != 0) {
9788 				scsi_ulto4b((1 << lun->be_lun->ublockexp),
9789 				    bl_ptr->opt_unmap_grain);
9790 				scsi_ulto4b(0x80000000 | lun->be_lun->ublockoff,
9791 				    bl_ptr->unmap_grain_align);
9792 			}
9793 		}
9794 		scsi_ulto4b(lun->be_lun->atomicblock,
9795 		    bl_ptr->max_atomic_transfer_length);
9796 		scsi_ulto4b(0, bl_ptr->atomic_alignment);
9797 		scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
9798 		scsi_ulto4b(0, bl_ptr->max_atomic_transfer_length_with_atomic_boundary);
9799 		scsi_ulto4b(0, bl_ptr->max_atomic_boundary_size);
9800 		ival = UINT64_MAX;
9801 		val = dnvlist_get_string(lun->be_lun->options,
9802 		    "write_same_max_lba", NULL);
9803 		if (val != NULL)
9804 			ctl_expand_number(val, &ival);
9805 		scsi_u64to8b(ival, bl_ptr->max_write_same_length);
9806 		if (lun->be_lun->maxlba + 1 > ival)
9807 			bl_ptr->flags |= SVPD_BL_WSNZ;
9808 	}
9809 
9810 	ctl_set_success(ctsio);
9811 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9812 	ctsio->be_move_done = ctl_config_move_done;
9813 	ctl_datamove((union ctl_io *)ctsio);
9814 	return (CTL_RETVAL_COMPLETE);
9815 }
9816 
9817 static int
9818 ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
9819 {
9820 	struct ctl_lun *lun = CTL_LUN(ctsio);
9821 	struct scsi_vpd_block_device_characteristics *bdc_ptr;
9822 	const char *value;
9823 	u_int i;
9824 
9825 	ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
9826 	bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
9827 	ctsio->kern_sg_entries = 0;
9828 	ctsio->kern_rel_offset = 0;
9829 	ctsio->kern_data_len = min(sizeof(*bdc_ptr), alloc_len);
9830 	ctsio->kern_total_len = ctsio->kern_data_len;
9831 
9832 	/*
9833 	 * The control device is always connected.  The disk device, on the
9834 	 * other hand, may not be online all the time.  Need to change this
9835 	 * to figure out whether the disk device is actually online or not.
9836 	 */
9837 	if (lun != NULL)
9838 		bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9839 				  lun->be_lun->lun_type;
9840 	else
9841 		bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9842 	bdc_ptr->page_code = SVPD_BDC;
9843 	scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
9844 	if (lun != NULL &&
9845 	    (value = dnvlist_get_string(lun->be_lun->options, "rpm", NULL)) != NULL)
9846 		i = strtol(value, NULL, 0);
9847 	else
9848 		i = CTL_DEFAULT_ROTATION_RATE;
9849 	scsi_ulto2b(i, bdc_ptr->medium_rotation_rate);
9850 	if (lun != NULL &&
9851 	    (value = dnvlist_get_string(lun->be_lun->options, "formfactor", NULL)) != NULL)
9852 		i = strtol(value, NULL, 0);
9853 	else
9854 		i = 0;
9855 	bdc_ptr->wab_wac_ff = (i & 0x0f);
9856 	bdc_ptr->flags = SVPD_RBWZ | SVPD_FUAB | SVPD_VBULS;
9857 
9858 	ctl_set_success(ctsio);
9859 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9860 	ctsio->be_move_done = ctl_config_move_done;
9861 	ctl_datamove((union ctl_io *)ctsio);
9862 	return (CTL_RETVAL_COMPLETE);
9863 }
9864 
9865 static int
9866 ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
9867 {
9868 	struct ctl_lun *lun = CTL_LUN(ctsio);
9869 	struct scsi_vpd_logical_block_prov *lbp_ptr;
9870 	const char *value;
9871 
9872 	ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
9873 	lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
9874 	ctsio->kern_sg_entries = 0;
9875 	ctsio->kern_rel_offset = 0;
9876 	ctsio->kern_data_len = min(sizeof(*lbp_ptr), alloc_len);
9877 	ctsio->kern_total_len = ctsio->kern_data_len;
9878 
9879 	/*
9880 	 * The control device is always connected.  The disk device, on the
9881 	 * other hand, may not be online all the time.  Need to change this
9882 	 * to figure out whether the disk device is actually online or not.
9883 	 */
9884 	if (lun != NULL)
9885 		lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9886 				  lun->be_lun->lun_type;
9887 	else
9888 		lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9889 
9890 	lbp_ptr->page_code = SVPD_LBP;
9891 	scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
9892 	lbp_ptr->threshold_exponent = CTL_LBP_EXPONENT;
9893 	if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9894 		lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
9895 		    SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
9896 		value = dnvlist_get_string(lun->be_lun->options,
9897 		    "provisioning_type", NULL);
9898 		if (value != NULL) {
9899 			if (strcmp(value, "resource") == 0)
9900 				lbp_ptr->prov_type = SVPD_LBP_RESOURCE;
9901 			else if (strcmp(value, "thin") == 0)
9902 				lbp_ptr->prov_type = SVPD_LBP_THIN;
9903 		} else
9904 			lbp_ptr->prov_type = SVPD_LBP_THIN;
9905 	}
9906 
9907 	ctl_set_success(ctsio);
9908 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9909 	ctsio->be_move_done = ctl_config_move_done;
9910 	ctl_datamove((union ctl_io *)ctsio);
9911 	return (CTL_RETVAL_COMPLETE);
9912 }
9913 
9914 /*
9915  * INQUIRY with the EVPD bit set.
9916  */
9917 static int
9918 ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
9919 {
9920 	struct ctl_lun *lun = CTL_LUN(ctsio);
9921 	struct scsi_inquiry *cdb;
9922 	int alloc_len, retval;
9923 
9924 	cdb = (struct scsi_inquiry *)ctsio->cdb;
9925 	alloc_len = scsi_2btoul(cdb->length);
9926 
9927 	switch (cdb->page_code) {
9928 	case SVPD_SUPPORTED_PAGES:
9929 		retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
9930 		break;
9931 	case SVPD_UNIT_SERIAL_NUMBER:
9932 		retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
9933 		break;
9934 	case SVPD_DEVICE_ID:
9935 		retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
9936 		break;
9937 	case SVPD_EXTENDED_INQUIRY_DATA:
9938 		retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
9939 		break;
9940 	case SVPD_MODE_PAGE_POLICY:
9941 		retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
9942 		break;
9943 	case SVPD_SCSI_PORTS:
9944 		retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
9945 		break;
9946 	case SVPD_SCSI_TPC:
9947 		retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
9948 		break;
9949 	case SVPD_SCSI_SFS:
9950 		retval = ctl_inquiry_evpd_sfs(ctsio, alloc_len);
9951 		break;
9952 	case SVPD_BLOCK_LIMITS:
9953 		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
9954 			goto err;
9955 		retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
9956 		break;
9957 	case SVPD_BDC:
9958 		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
9959 			goto err;
9960 		retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
9961 		break;
9962 	case SVPD_LBP:
9963 		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
9964 			goto err;
9965 		retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
9966 		break;
9967 	default:
9968 err:
9969 		ctl_set_invalid_field(ctsio,
9970 				      /*sks_valid*/ 1,
9971 				      /*command*/ 1,
9972 				      /*field*/ 2,
9973 				      /*bit_valid*/ 0,
9974 				      /*bit*/ 0);
9975 		ctl_done((union ctl_io *)ctsio);
9976 		retval = CTL_RETVAL_COMPLETE;
9977 		break;
9978 	}
9979 
9980 	return (retval);
9981 }
9982 
9983 /*
9984  * Standard INQUIRY data.
9985  */
9986 static int
9987 ctl_inquiry_std(struct ctl_scsiio *ctsio)
9988 {
9989 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9990 	struct ctl_port *port = CTL_PORT(ctsio);
9991 	struct ctl_lun *lun = CTL_LUN(ctsio);
9992 	struct scsi_inquiry_data *inq_ptr;
9993 	struct scsi_inquiry *cdb;
9994 	const char *val;
9995 	uint32_t alloc_len, data_len;
9996 	ctl_port_type port_type;
9997 
9998 	port_type = port->port_type;
9999 	if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10000 		port_type = CTL_PORT_SCSI;
10001 
10002 	cdb = (struct scsi_inquiry *)ctsio->cdb;
10003 	alloc_len = scsi_2btoul(cdb->length);
10004 
10005 	/*
10006 	 * We malloc the full inquiry data size here and fill it
10007 	 * in.  If the user only asks for less, we'll give him
10008 	 * that much.
10009 	 */
10010 	data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
10011 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10012 	inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10013 	ctsio->kern_sg_entries = 0;
10014 	ctsio->kern_rel_offset = 0;
10015 	ctsio->kern_data_len = min(data_len, alloc_len);
10016 	ctsio->kern_total_len = ctsio->kern_data_len;
10017 
10018 	if (lun != NULL) {
10019 		if ((lun->flags & CTL_LUN_PRIMARY_SC) ||
10020 		    softc->ha_link >= CTL_HA_LINK_UNKNOWN) {
10021 			inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10022 			    lun->be_lun->lun_type;
10023 		} else {
10024 			inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) |
10025 			    lun->be_lun->lun_type;
10026 		}
10027 		if (lun->flags & CTL_LUN_REMOVABLE)
10028 			inq_ptr->dev_qual2 |= SID_RMB;
10029 	} else
10030 		inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10031 
10032 	/* RMB in byte 2 is 0 */
10033 	inq_ptr->version = SCSI_REV_SPC5;
10034 
10035 	/*
10036 	 * According to SAM-3, even if a device only supports a single
10037 	 * level of LUN addressing, it should still set the HISUP bit:
10038 	 *
10039 	 * 4.9.1 Logical unit numbers overview
10040 	 *
10041 	 * All logical unit number formats described in this standard are
10042 	 * hierarchical in structure even when only a single level in that
10043 	 * hierarchy is used. The HISUP bit shall be set to one in the
10044 	 * standard INQUIRY data (see SPC-2) when any logical unit number
10045 	 * format described in this standard is used.  Non-hierarchical
10046 	 * formats are outside the scope of this standard.
10047 	 *
10048 	 * Therefore we set the HiSup bit here.
10049 	 *
10050 	 * The response format is 2, per SPC-3.
10051 	 */
10052 	inq_ptr->response_format = SID_HiSup | 2;
10053 
10054 	inq_ptr->additional_length = data_len -
10055 	    (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10056 	CTL_DEBUG_PRINT(("additional_length = %d\n",
10057 			 inq_ptr->additional_length));
10058 
10059 	inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10060 	if (port_type == CTL_PORT_SCSI)
10061 		inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10062 	inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10063 	inq_ptr->flags = SID_CmdQue;
10064 	if (port_type == CTL_PORT_SCSI)
10065 		inq_ptr->flags |= SID_WBus16 | SID_Sync;
10066 
10067 	/*
10068 	 * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10069 	 * We have 8 bytes for the vendor name, and 16 bytes for the device
10070 	 * name and 4 bytes for the revision.
10071 	 */
10072 	if (lun == NULL || (val = dnvlist_get_string(lun->be_lun->options,
10073 	    "vendor", NULL)) == NULL) {
10074 		strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10075 	} else {
10076 		memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10077 		strncpy(inq_ptr->vendor, val,
10078 		    min(sizeof(inq_ptr->vendor), strlen(val)));
10079 	}
10080 	if (lun == NULL) {
10081 		strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10082 		    sizeof(inq_ptr->product));
10083 	} else if ((val = dnvlist_get_string(lun->be_lun->options, "product",
10084 	    NULL)) == NULL) {
10085 		switch (lun->be_lun->lun_type) {
10086 		case T_DIRECT:
10087 			strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10088 			    sizeof(inq_ptr->product));
10089 			break;
10090 		case T_PROCESSOR:
10091 			strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10092 			    sizeof(inq_ptr->product));
10093 			break;
10094 		case T_CDROM:
10095 			strncpy(inq_ptr->product, CTL_CDROM_PRODUCT,
10096 			    sizeof(inq_ptr->product));
10097 			break;
10098 		default:
10099 			strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10100 			    sizeof(inq_ptr->product));
10101 			break;
10102 		}
10103 	} else {
10104 		memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10105 		strncpy(inq_ptr->product, val,
10106 		    min(sizeof(inq_ptr->product), strlen(val)));
10107 	}
10108 
10109 	/*
10110 	 * XXX make this a macro somewhere so it automatically gets
10111 	 * incremented when we make changes.
10112 	 */
10113 	if (lun == NULL || (val = dnvlist_get_string(lun->be_lun->options,
10114 	    "revision", NULL)) == NULL) {
10115 		strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10116 	} else {
10117 		memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10118 		strncpy(inq_ptr->revision, val,
10119 		    min(sizeof(inq_ptr->revision), strlen(val)));
10120 	}
10121 
10122 	/*
10123 	 * For parallel SCSI, we support double transition and single
10124 	 * transition clocking.  We also support QAS (Quick Arbitration
10125 	 * and Selection) and Information Unit transfers on both the
10126 	 * control and array devices.
10127 	 */
10128 	if (port_type == CTL_PORT_SCSI)
10129 		inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10130 				    SID_SPI_IUS;
10131 
10132 	/* SAM-6 (no version claimed) */
10133 	scsi_ulto2b(0x00C0, inq_ptr->version1);
10134 	/* SPC-5 (no version claimed) */
10135 	scsi_ulto2b(0x05C0, inq_ptr->version2);
10136 	if (port_type == CTL_PORT_FC) {
10137 		/* FCP-2 ANSI INCITS.350:2003 */
10138 		scsi_ulto2b(0x0917, inq_ptr->version3);
10139 	} else if (port_type == CTL_PORT_SCSI) {
10140 		/* SPI-4 ANSI INCITS.362:200x */
10141 		scsi_ulto2b(0x0B56, inq_ptr->version3);
10142 	} else if (port_type == CTL_PORT_ISCSI) {
10143 		/* iSCSI (no version claimed) */
10144 		scsi_ulto2b(0x0960, inq_ptr->version3);
10145 	} else if (port_type == CTL_PORT_SAS) {
10146 		/* SAS (no version claimed) */
10147 		scsi_ulto2b(0x0BE0, inq_ptr->version3);
10148 	} else if (port_type == CTL_PORT_UMASS) {
10149 		/* USB Mass Storage Class Bulk-Only Transport, Revision 1.0 */
10150 		scsi_ulto2b(0x1730, inq_ptr->version3);
10151 	}
10152 
10153 	if (lun == NULL) {
10154 		/* SBC-4 (no version claimed) */
10155 		scsi_ulto2b(0x0600, inq_ptr->version4);
10156 	} else {
10157 		switch (lun->be_lun->lun_type) {
10158 		case T_DIRECT:
10159 			/* SBC-4 (no version claimed) */
10160 			scsi_ulto2b(0x0600, inq_ptr->version4);
10161 			break;
10162 		case T_PROCESSOR:
10163 			break;
10164 		case T_CDROM:
10165 			/* MMC-6 (no version claimed) */
10166 			scsi_ulto2b(0x04E0, inq_ptr->version4);
10167 			break;
10168 		default:
10169 			break;
10170 		}
10171 	}
10172 
10173 	ctl_set_success(ctsio);
10174 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10175 	ctsio->be_move_done = ctl_config_move_done;
10176 	ctl_datamove((union ctl_io *)ctsio);
10177 	return (CTL_RETVAL_COMPLETE);
10178 }
10179 
10180 int
10181 ctl_inquiry(struct ctl_scsiio *ctsio)
10182 {
10183 	struct scsi_inquiry *cdb;
10184 	int retval;
10185 
10186 	CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10187 
10188 	cdb = (struct scsi_inquiry *)ctsio->cdb;
10189 	if (cdb->byte2 & SI_EVPD)
10190 		retval = ctl_inquiry_evpd(ctsio);
10191 	else if (cdb->page_code == 0)
10192 		retval = ctl_inquiry_std(ctsio);
10193 	else {
10194 		ctl_set_invalid_field(ctsio,
10195 				      /*sks_valid*/ 1,
10196 				      /*command*/ 1,
10197 				      /*field*/ 2,
10198 				      /*bit_valid*/ 0,
10199 				      /*bit*/ 0);
10200 		ctl_done((union ctl_io *)ctsio);
10201 		return (CTL_RETVAL_COMPLETE);
10202 	}
10203 
10204 	return (retval);
10205 }
10206 
10207 int
10208 ctl_get_config(struct ctl_scsiio *ctsio)
10209 {
10210 	struct ctl_lun *lun = CTL_LUN(ctsio);
10211 	struct scsi_get_config_header *hdr;
10212 	struct scsi_get_config_feature *feature;
10213 	struct scsi_get_config *cdb;
10214 	uint32_t alloc_len, data_len;
10215 	int rt, starting;
10216 
10217 	cdb = (struct scsi_get_config *)ctsio->cdb;
10218 	rt = (cdb->rt & SGC_RT_MASK);
10219 	starting = scsi_2btoul(cdb->starting_feature);
10220 	alloc_len = scsi_2btoul(cdb->length);
10221 
10222 	data_len = sizeof(struct scsi_get_config_header) +
10223 	    sizeof(struct scsi_get_config_feature) + 8 +
10224 	    sizeof(struct scsi_get_config_feature) + 8 +
10225 	    sizeof(struct scsi_get_config_feature) + 4 +
10226 	    sizeof(struct scsi_get_config_feature) + 4 +
10227 	    sizeof(struct scsi_get_config_feature) + 8 +
10228 	    sizeof(struct scsi_get_config_feature) +
10229 	    sizeof(struct scsi_get_config_feature) + 4 +
10230 	    sizeof(struct scsi_get_config_feature) + 4 +
10231 	    sizeof(struct scsi_get_config_feature) + 4 +
10232 	    sizeof(struct scsi_get_config_feature) + 4 +
10233 	    sizeof(struct scsi_get_config_feature) + 4 +
10234 	    sizeof(struct scsi_get_config_feature) + 4;
10235 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10236 	ctsio->kern_sg_entries = 0;
10237 	ctsio->kern_rel_offset = 0;
10238 
10239 	hdr = (struct scsi_get_config_header *)ctsio->kern_data_ptr;
10240 	if (lun->flags & CTL_LUN_NO_MEDIA)
10241 		scsi_ulto2b(0x0000, hdr->current_profile);
10242 	else
10243 		scsi_ulto2b(0x0010, hdr->current_profile);
10244 	feature = (struct scsi_get_config_feature *)(hdr + 1);
10245 
10246 	if (starting > 0x003b)
10247 		goto done;
10248 	if (starting > 0x003a)
10249 		goto f3b;
10250 	if (starting > 0x002b)
10251 		goto f3a;
10252 	if (starting > 0x002a)
10253 		goto f2b;
10254 	if (starting > 0x001f)
10255 		goto f2a;
10256 	if (starting > 0x001e)
10257 		goto f1f;
10258 	if (starting > 0x001d)
10259 		goto f1e;
10260 	if (starting > 0x0010)
10261 		goto f1d;
10262 	if (starting > 0x0003)
10263 		goto f10;
10264 	if (starting > 0x0002)
10265 		goto f3;
10266 	if (starting > 0x0001)
10267 		goto f2;
10268 	if (starting > 0x0000)
10269 		goto f1;
10270 
10271 	/* Profile List */
10272 	scsi_ulto2b(0x0000, feature->feature_code);
10273 	feature->flags = SGC_F_PERSISTENT | SGC_F_CURRENT;
10274 	feature->add_length = 8;
10275 	scsi_ulto2b(0x0008, &feature->feature_data[0]);	/* CD-ROM */
10276 	feature->feature_data[2] = 0x00;
10277 	scsi_ulto2b(0x0010, &feature->feature_data[4]);	/* DVD-ROM */
10278 	feature->feature_data[6] = 0x01;
10279 	feature = (struct scsi_get_config_feature *)
10280 	    &feature->feature_data[feature->add_length];
10281 
10282 f1:	/* Core */
10283 	scsi_ulto2b(0x0001, feature->feature_code);
10284 	feature->flags = 0x08 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10285 	feature->add_length = 8;
10286 	scsi_ulto4b(0x00000000, &feature->feature_data[0]);
10287 	feature->feature_data[4] = 0x03;
10288 	feature = (struct scsi_get_config_feature *)
10289 	    &feature->feature_data[feature->add_length];
10290 
10291 f2:	/* Morphing */
10292 	scsi_ulto2b(0x0002, feature->feature_code);
10293 	feature->flags = 0x04 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10294 	feature->add_length = 4;
10295 	feature->feature_data[0] = 0x02;
10296 	feature = (struct scsi_get_config_feature *)
10297 	    &feature->feature_data[feature->add_length];
10298 
10299 f3:	/* Removable Medium */
10300 	scsi_ulto2b(0x0003, feature->feature_code);
10301 	feature->flags = 0x04 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10302 	feature->add_length = 4;
10303 	feature->feature_data[0] = 0x39;
10304 	feature = (struct scsi_get_config_feature *)
10305 	    &feature->feature_data[feature->add_length];
10306 
10307 	if (rt == SGC_RT_CURRENT && (lun->flags & CTL_LUN_NO_MEDIA))
10308 		goto done;
10309 
10310 f10:	/* Random Read */
10311 	scsi_ulto2b(0x0010, feature->feature_code);
10312 	feature->flags = 0x00;
10313 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10314 		feature->flags |= SGC_F_CURRENT;
10315 	feature->add_length = 8;
10316 	scsi_ulto4b(lun->be_lun->blocksize, &feature->feature_data[0]);
10317 	scsi_ulto2b(1, &feature->feature_data[4]);
10318 	feature->feature_data[6] = 0x00;
10319 	feature = (struct scsi_get_config_feature *)
10320 	    &feature->feature_data[feature->add_length];
10321 
10322 f1d:	/* Multi-Read */
10323 	scsi_ulto2b(0x001D, feature->feature_code);
10324 	feature->flags = 0x00;
10325 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10326 		feature->flags |= SGC_F_CURRENT;
10327 	feature->add_length = 0;
10328 	feature = (struct scsi_get_config_feature *)
10329 	    &feature->feature_data[feature->add_length];
10330 
10331 f1e:	/* CD Read */
10332 	scsi_ulto2b(0x001E, feature->feature_code);
10333 	feature->flags = 0x00;
10334 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10335 		feature->flags |= SGC_F_CURRENT;
10336 	feature->add_length = 4;
10337 	feature->feature_data[0] = 0x00;
10338 	feature = (struct scsi_get_config_feature *)
10339 	    &feature->feature_data[feature->add_length];
10340 
10341 f1f:	/* DVD Read */
10342 	scsi_ulto2b(0x001F, feature->feature_code);
10343 	feature->flags = 0x08;
10344 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10345 		feature->flags |= SGC_F_CURRENT;
10346 	feature->add_length = 4;
10347 	feature->feature_data[0] = 0x01;
10348 	feature->feature_data[2] = 0x03;
10349 	feature = (struct scsi_get_config_feature *)
10350 	    &feature->feature_data[feature->add_length];
10351 
10352 f2a:	/* DVD+RW */
10353 	scsi_ulto2b(0x002A, feature->feature_code);
10354 	feature->flags = 0x04;
10355 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10356 		feature->flags |= SGC_F_CURRENT;
10357 	feature->add_length = 4;
10358 	feature->feature_data[0] = 0x00;
10359 	feature->feature_data[1] = 0x00;
10360 	feature = (struct scsi_get_config_feature *)
10361 	    &feature->feature_data[feature->add_length];
10362 
10363 f2b:	/* DVD+R */
10364 	scsi_ulto2b(0x002B, feature->feature_code);
10365 	feature->flags = 0x00;
10366 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10367 		feature->flags |= SGC_F_CURRENT;
10368 	feature->add_length = 4;
10369 	feature->feature_data[0] = 0x00;
10370 	feature = (struct scsi_get_config_feature *)
10371 	    &feature->feature_data[feature->add_length];
10372 
10373 f3a:	/* DVD+RW Dual Layer */
10374 	scsi_ulto2b(0x003A, feature->feature_code);
10375 	feature->flags = 0x00;
10376 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10377 		feature->flags |= SGC_F_CURRENT;
10378 	feature->add_length = 4;
10379 	feature->feature_data[0] = 0x00;
10380 	feature->feature_data[1] = 0x00;
10381 	feature = (struct scsi_get_config_feature *)
10382 	    &feature->feature_data[feature->add_length];
10383 
10384 f3b:	/* DVD+R Dual Layer */
10385 	scsi_ulto2b(0x003B, feature->feature_code);
10386 	feature->flags = 0x00;
10387 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10388 		feature->flags |= SGC_F_CURRENT;
10389 	feature->add_length = 4;
10390 	feature->feature_data[0] = 0x00;
10391 	feature = (struct scsi_get_config_feature *)
10392 	    &feature->feature_data[feature->add_length];
10393 
10394 done:
10395 	data_len = (uint8_t *)feature - (uint8_t *)hdr;
10396 	if (rt == SGC_RT_SPECIFIC && data_len > 4) {
10397 		feature = (struct scsi_get_config_feature *)(hdr + 1);
10398 		if (scsi_2btoul(feature->feature_code) == starting)
10399 			feature = (struct scsi_get_config_feature *)
10400 			    &feature->feature_data[feature->add_length];
10401 		data_len = (uint8_t *)feature - (uint8_t *)hdr;
10402 	}
10403 	scsi_ulto4b(data_len - 4, hdr->data_length);
10404 	ctsio->kern_data_len = min(data_len, alloc_len);
10405 	ctsio->kern_total_len = ctsio->kern_data_len;
10406 
10407 	ctl_set_success(ctsio);
10408 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10409 	ctsio->be_move_done = ctl_config_move_done;
10410 	ctl_datamove((union ctl_io *)ctsio);
10411 	return (CTL_RETVAL_COMPLETE);
10412 }
10413 
10414 int
10415 ctl_get_event_status(struct ctl_scsiio *ctsio)
10416 {
10417 	struct scsi_get_event_status_header *hdr;
10418 	struct scsi_get_event_status *cdb;
10419 	uint32_t alloc_len, data_len;
10420 
10421 	cdb = (struct scsi_get_event_status *)ctsio->cdb;
10422 	if ((cdb->byte2 & SGESN_POLLED) == 0) {
10423 		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1, /*command*/ 1,
10424 		    /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
10425 		ctl_done((union ctl_io *)ctsio);
10426 		return (CTL_RETVAL_COMPLETE);
10427 	}
10428 	alloc_len = scsi_2btoul(cdb->length);
10429 
10430 	data_len = sizeof(struct scsi_get_event_status_header);
10431 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10432 	ctsio->kern_sg_entries = 0;
10433 	ctsio->kern_rel_offset = 0;
10434 	ctsio->kern_data_len = min(data_len, alloc_len);
10435 	ctsio->kern_total_len = ctsio->kern_data_len;
10436 
10437 	hdr = (struct scsi_get_event_status_header *)ctsio->kern_data_ptr;
10438 	scsi_ulto2b(0, hdr->descr_length);
10439 	hdr->nea_class = SGESN_NEA;
10440 	hdr->supported_class = 0;
10441 
10442 	ctl_set_success(ctsio);
10443 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10444 	ctsio->be_move_done = ctl_config_move_done;
10445 	ctl_datamove((union ctl_io *)ctsio);
10446 	return (CTL_RETVAL_COMPLETE);
10447 }
10448 
10449 int
10450 ctl_mechanism_status(struct ctl_scsiio *ctsio)
10451 {
10452 	struct scsi_mechanism_status_header *hdr;
10453 	struct scsi_mechanism_status *cdb;
10454 	uint32_t alloc_len, data_len;
10455 
10456 	cdb = (struct scsi_mechanism_status *)ctsio->cdb;
10457 	alloc_len = scsi_2btoul(cdb->length);
10458 
10459 	data_len = sizeof(struct scsi_mechanism_status_header);
10460 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10461 	ctsio->kern_sg_entries = 0;
10462 	ctsio->kern_rel_offset = 0;
10463 	ctsio->kern_data_len = min(data_len, alloc_len);
10464 	ctsio->kern_total_len = ctsio->kern_data_len;
10465 
10466 	hdr = (struct scsi_mechanism_status_header *)ctsio->kern_data_ptr;
10467 	hdr->state1 = 0x00;
10468 	hdr->state2 = 0xe0;
10469 	scsi_ulto3b(0, hdr->lba);
10470 	hdr->slots_num = 0;
10471 	scsi_ulto2b(0, hdr->slots_length);
10472 
10473 	ctl_set_success(ctsio);
10474 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10475 	ctsio->be_move_done = ctl_config_move_done;
10476 	ctl_datamove((union ctl_io *)ctsio);
10477 	return (CTL_RETVAL_COMPLETE);
10478 }
10479 
10480 static void
10481 ctl_ultomsf(uint32_t lba, uint8_t *buf)
10482 {
10483 
10484 	lba += 150;
10485 	buf[0] = 0;
10486 	buf[1] = bin2bcd((lba / 75) / 60);
10487 	buf[2] = bin2bcd((lba / 75) % 60);
10488 	buf[3] = bin2bcd(lba % 75);
10489 }
10490 
10491 int
10492 ctl_read_toc(struct ctl_scsiio *ctsio)
10493 {
10494 	struct ctl_lun *lun = CTL_LUN(ctsio);
10495 	struct scsi_read_toc_hdr *hdr;
10496 	struct scsi_read_toc_type01_descr *descr;
10497 	struct scsi_read_toc *cdb;
10498 	uint32_t alloc_len, data_len;
10499 	int format, msf;
10500 
10501 	cdb = (struct scsi_read_toc *)ctsio->cdb;
10502 	msf = (cdb->byte2 & CD_MSF) != 0;
10503 	format = cdb->format;
10504 	alloc_len = scsi_2btoul(cdb->data_len);
10505 
10506 	data_len = sizeof(struct scsi_read_toc_hdr);
10507 	if (format == 0)
10508 		data_len += 2 * sizeof(struct scsi_read_toc_type01_descr);
10509 	else
10510 		data_len += sizeof(struct scsi_read_toc_type01_descr);
10511 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10512 	ctsio->kern_sg_entries = 0;
10513 	ctsio->kern_rel_offset = 0;
10514 	ctsio->kern_data_len = min(data_len, alloc_len);
10515 	ctsio->kern_total_len = ctsio->kern_data_len;
10516 
10517 	hdr = (struct scsi_read_toc_hdr *)ctsio->kern_data_ptr;
10518 	if (format == 0) {
10519 		scsi_ulto2b(0x12, hdr->data_length);
10520 		hdr->first = 1;
10521 		hdr->last = 1;
10522 		descr = (struct scsi_read_toc_type01_descr *)(hdr + 1);
10523 		descr->addr_ctl = 0x14;
10524 		descr->track_number = 1;
10525 		if (msf)
10526 			ctl_ultomsf(0, descr->track_start);
10527 		else
10528 			scsi_ulto4b(0, descr->track_start);
10529 		descr++;
10530 		descr->addr_ctl = 0x14;
10531 		descr->track_number = 0xaa;
10532 		if (msf)
10533 			ctl_ultomsf(lun->be_lun->maxlba+1, descr->track_start);
10534 		else
10535 			scsi_ulto4b(lun->be_lun->maxlba+1, descr->track_start);
10536 	} else {
10537 		scsi_ulto2b(0x0a, hdr->data_length);
10538 		hdr->first = 1;
10539 		hdr->last = 1;
10540 		descr = (struct scsi_read_toc_type01_descr *)(hdr + 1);
10541 		descr->addr_ctl = 0x14;
10542 		descr->track_number = 1;
10543 		if (msf)
10544 			ctl_ultomsf(0, descr->track_start);
10545 		else
10546 			scsi_ulto4b(0, descr->track_start);
10547 	}
10548 
10549 	ctl_set_success(ctsio);
10550 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10551 	ctsio->be_move_done = ctl_config_move_done;
10552 	ctl_datamove((union ctl_io *)ctsio);
10553 	return (CTL_RETVAL_COMPLETE);
10554 }
10555 
10556 /*
10557  * For known CDB types, parse the LBA and length.
10558  */
10559 static int
10560 ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10561 {
10562 
10563 	KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
10564 	    ("%s: unexpected I/O type %x", __func__, io->io_hdr.io_type));
10565 
10566 	switch (io->scsiio.cdb[0]) {
10567 	case COMPARE_AND_WRITE: {
10568 		struct scsi_compare_and_write *cdb;
10569 
10570 		cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10571 
10572 		*lba = scsi_8btou64(cdb->addr);
10573 		*len = cdb->length;
10574 		break;
10575 	}
10576 	case READ_6:
10577 	case WRITE_6: {
10578 		struct scsi_rw_6 *cdb;
10579 
10580 		cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10581 
10582 		*lba = scsi_3btoul(cdb->addr);
10583 		/* only 5 bits are valid in the most significant address byte */
10584 		*lba &= 0x1fffff;
10585 		*len = cdb->length;
10586 		break;
10587 	}
10588 	case READ_10:
10589 	case WRITE_10: {
10590 		struct scsi_rw_10 *cdb;
10591 
10592 		cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10593 
10594 		*lba = scsi_4btoul(cdb->addr);
10595 		*len = scsi_2btoul(cdb->length);
10596 		break;
10597 	}
10598 	case WRITE_VERIFY_10: {
10599 		struct scsi_write_verify_10 *cdb;
10600 
10601 		cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10602 
10603 		*lba = scsi_4btoul(cdb->addr);
10604 		*len = scsi_2btoul(cdb->length);
10605 		break;
10606 	}
10607 	case READ_12:
10608 	case WRITE_12: {
10609 		struct scsi_rw_12 *cdb;
10610 
10611 		cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10612 
10613 		*lba = scsi_4btoul(cdb->addr);
10614 		*len = scsi_4btoul(cdb->length);
10615 		break;
10616 	}
10617 	case WRITE_VERIFY_12: {
10618 		struct scsi_write_verify_12 *cdb;
10619 
10620 		cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10621 
10622 		*lba = scsi_4btoul(cdb->addr);
10623 		*len = scsi_4btoul(cdb->length);
10624 		break;
10625 	}
10626 	case READ_16:
10627 	case WRITE_16: {
10628 		struct scsi_rw_16 *cdb;
10629 
10630 		cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10631 
10632 		*lba = scsi_8btou64(cdb->addr);
10633 		*len = scsi_4btoul(cdb->length);
10634 		break;
10635 	}
10636 	case WRITE_ATOMIC_16: {
10637 		struct scsi_write_atomic_16 *cdb;
10638 
10639 		cdb = (struct scsi_write_atomic_16 *)io->scsiio.cdb;
10640 
10641 		*lba = scsi_8btou64(cdb->addr);
10642 		*len = scsi_2btoul(cdb->length);
10643 		break;
10644 	}
10645 	case WRITE_VERIFY_16: {
10646 		struct scsi_write_verify_16 *cdb;
10647 
10648 		cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10649 
10650 		*lba = scsi_8btou64(cdb->addr);
10651 		*len = scsi_4btoul(cdb->length);
10652 		break;
10653 	}
10654 	case WRITE_SAME_10: {
10655 		struct scsi_write_same_10 *cdb;
10656 
10657 		cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10658 
10659 		*lba = scsi_4btoul(cdb->addr);
10660 		*len = scsi_2btoul(cdb->length);
10661 		break;
10662 	}
10663 	case WRITE_SAME_16: {
10664 		struct scsi_write_same_16 *cdb;
10665 
10666 		cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10667 
10668 		*lba = scsi_8btou64(cdb->addr);
10669 		*len = scsi_4btoul(cdb->length);
10670 		break;
10671 	}
10672 	case VERIFY_10: {
10673 		struct scsi_verify_10 *cdb;
10674 
10675 		cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10676 
10677 		*lba = scsi_4btoul(cdb->addr);
10678 		*len = scsi_2btoul(cdb->length);
10679 		break;
10680 	}
10681 	case VERIFY_12: {
10682 		struct scsi_verify_12 *cdb;
10683 
10684 		cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10685 
10686 		*lba = scsi_4btoul(cdb->addr);
10687 		*len = scsi_4btoul(cdb->length);
10688 		break;
10689 	}
10690 	case VERIFY_16: {
10691 		struct scsi_verify_16 *cdb;
10692 
10693 		cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10694 
10695 		*lba = scsi_8btou64(cdb->addr);
10696 		*len = scsi_4btoul(cdb->length);
10697 		break;
10698 	}
10699 	case UNMAP: {
10700 		*lba = 0;
10701 		*len = UINT64_MAX;
10702 		break;
10703 	}
10704 	case SERVICE_ACTION_IN: {	/* GET LBA STATUS */
10705 		struct scsi_get_lba_status *cdb;
10706 
10707 		cdb = (struct scsi_get_lba_status *)io->scsiio.cdb;
10708 		*lba = scsi_8btou64(cdb->addr);
10709 		*len = UINT32_MAX;
10710 		break;
10711 	}
10712 	default:
10713 		*lba = 0;
10714 		*len = UINT64_MAX;
10715 		return (1);
10716 	}
10717 
10718 	return (0);
10719 }
10720 
10721 static ctl_action
10722 ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2,
10723     bool seq)
10724 {
10725 	uint64_t endlba1, endlba2;
10726 
10727 	endlba1 = lba1 + len1 - (seq ? 0 : 1);
10728 	endlba2 = lba2 + len2 - 1;
10729 
10730 	if ((endlba1 < lba2) || (endlba2 < lba1))
10731 		return (CTL_ACTION_PASS);
10732 	else
10733 		return (CTL_ACTION_BLOCK);
10734 }
10735 
10736 static int
10737 ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
10738 {
10739 	struct ctl_ptr_len_flags *ptrlen;
10740 	struct scsi_unmap_desc *buf, *end, *range;
10741 	uint64_t lba;
10742 	uint32_t len;
10743 
10744 	KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
10745 	    ("%s: unexpected I/O type %x", __func__, io->io_hdr.io_type));
10746 
10747 	/* If not UNMAP -- go other way. */
10748 	if (io->scsiio.cdb[0] != UNMAP)
10749 		return (CTL_ACTION_SKIP);
10750 
10751 	/* If UNMAP without data -- block and wait for data. */
10752 	ptrlen = (struct ctl_ptr_len_flags *)
10753 	    &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10754 	if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
10755 	    ptrlen->ptr == NULL)
10756 		return (CTL_ACTION_BLOCK);
10757 
10758 	/* UNMAP with data -- check for collision. */
10759 	buf = (struct scsi_unmap_desc *)ptrlen->ptr;
10760 	end = buf + ptrlen->len / sizeof(*buf);
10761 	for (range = buf; range < end; range++) {
10762 		lba = scsi_8btou64(range->lba);
10763 		len = scsi_4btoul(range->length);
10764 		if ((lba < lba2 + len2) && (lba + len > lba2))
10765 			return (CTL_ACTION_BLOCK);
10766 	}
10767 	return (CTL_ACTION_PASS);
10768 }
10769 
10770 static ctl_action
10771 ctl_extent_check(union ctl_io *io1, union ctl_io *io2, bool seq)
10772 {
10773 	uint64_t lba1, lba2;
10774 	uint64_t len1, len2;
10775 	int retval;
10776 
10777 	retval = ctl_get_lba_len(io2, &lba2, &len2);
10778 	KASSERT(retval == 0, ("ctl_get_lba_len() error"));
10779 
10780 	retval = ctl_extent_check_unmap(io1, lba2, len2);
10781 	if (retval != CTL_ACTION_SKIP)
10782 		return (retval);
10783 
10784 	retval = ctl_get_lba_len(io1, &lba1, &len1);
10785 	KASSERT(retval == 0, ("ctl_get_lba_len() error"));
10786 
10787 	if (seq && (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE))
10788 		seq = FALSE;
10789 	return (ctl_extent_check_lba(lba1, len1, lba2, len2, seq));
10790 }
10791 
10792 static ctl_action
10793 ctl_seq_check(union ctl_io *io1, union ctl_io *io2)
10794 {
10795 	uint64_t lba1, lba2;
10796 	uint64_t len1, len2;
10797 	int retval __diagused;
10798 
10799 	if (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE)
10800 		return (CTL_ACTION_PASS);
10801 	retval = ctl_get_lba_len(io1, &lba1, &len1);
10802 	KASSERT(retval == 0, ("ctl_get_lba_len() error"));
10803 	retval = ctl_get_lba_len(io2, &lba2, &len2);
10804 	KASSERT(retval == 0, ("ctl_get_lba_len() error"));
10805 
10806 	if (lba1 + len1 == lba2)
10807 		return (CTL_ACTION_BLOCK);
10808 	return (CTL_ACTION_PASS);
10809 }
10810 
10811 static ctl_action
10812 ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
10813     const uint8_t *serialize_row, union ctl_io *ooa_io)
10814 {
10815 
10816 	/*
10817 	 * The initiator attempted multiple untagged commands at the same
10818 	 * time.  Can't do that.
10819 	 */
10820 	if (__predict_false(pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10821 	 && __predict_false(ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10822 	 && ((pending_io->io_hdr.nexus.targ_port ==
10823 	      ooa_io->io_hdr.nexus.targ_port)
10824 	  && (pending_io->io_hdr.nexus.initid ==
10825 	      ooa_io->io_hdr.nexus.initid))
10826 	 && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
10827 	      CTL_FLAG_STATUS_SENT)) == 0))
10828 		return (CTL_ACTION_OVERLAP);
10829 
10830 	/*
10831 	 * The initiator attempted to send multiple tagged commands with
10832 	 * the same ID.  (It's fine if different initiators have the same
10833 	 * tag ID.)
10834 	 *
10835 	 * Even if all of those conditions are true, we don't kill the I/O
10836 	 * if the command ahead of us has been aborted.  We won't end up
10837 	 * sending it to the FETD, and it's perfectly legal to resend a
10838 	 * command with the same tag number as long as the previous
10839 	 * instance of this tag number has been aborted somehow.
10840 	 */
10841 	if (__predict_true(pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10842 	 && __predict_true(ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10843 	 && __predict_false(pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
10844 	 && ((pending_io->io_hdr.nexus.targ_port ==
10845 	      ooa_io->io_hdr.nexus.targ_port)
10846 	  && (pending_io->io_hdr.nexus.initid ==
10847 	      ooa_io->io_hdr.nexus.initid))
10848 	 && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
10849 	      CTL_FLAG_STATUS_SENT)) == 0))
10850 		return (CTL_ACTION_OVERLAP_TAG);
10851 
10852 	/*
10853 	 * If we get a head of queue tag, SAM-3 says that we should
10854 	 * immediately execute it.
10855 	 *
10856 	 * What happens if this command would normally block for some other
10857 	 * reason?  e.g. a request sense with a head of queue tag
10858 	 * immediately after a write.  Normally that would block, but this
10859 	 * will result in its getting executed immediately...
10860 	 *
10861 	 * We currently return "pass" instead of "skip", so we'll end up
10862 	 * going through the rest of the queue to check for overlapped tags.
10863 	 *
10864 	 * XXX KDM check for other types of blockage first??
10865 	 */
10866 	if (__predict_false(pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE))
10867 		return (CTL_ACTION_PASS);
10868 
10869 	/*
10870 	 * Simple tags get blocked until all head of queue and ordered tags
10871 	 * ahead of them have completed.  I'm lumping untagged commands in
10872 	 * with simple tags here.  XXX KDM is that the right thing to do?
10873 	 */
10874 	if (__predict_false(ooa_io->scsiio.tag_type == CTL_TAG_ORDERED) ||
10875 	    __predict_false(ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE))
10876 		return (CTL_ACTION_BLOCK);
10877 
10878 	/* Unsupported command in OOA queue. */
10879 	if (__predict_false(ooa_io->scsiio.seridx == CTL_SERIDX_INVLD))
10880 		return (CTL_ACTION_PASS);
10881 
10882 	switch (serialize_row[ooa_io->scsiio.seridx]) {
10883 	case CTL_SER_SEQ:
10884 		if (lun->be_lun->serseq != CTL_LUN_SERSEQ_OFF)
10885 			return (ctl_seq_check(ooa_io, pending_io));
10886 		/* FALLTHROUGH */
10887 	case CTL_SER_PASS:
10888 		return (CTL_ACTION_PASS);
10889 	case CTL_SER_EXTENTOPT:
10890 		if ((lun->MODE_CTRL.queue_flags & SCP_QUEUE_ALG_MASK) ==
10891 		    SCP_QUEUE_ALG_UNRESTRICTED)
10892 			return (CTL_ACTION_PASS);
10893 		/* FALLTHROUGH */
10894 	case CTL_SER_EXTENT:
10895 		return (ctl_extent_check(ooa_io, pending_io,
10896 		    (lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
10897 	case CTL_SER_BLOCKOPT:
10898 		if ((lun->MODE_CTRL.queue_flags & SCP_QUEUE_ALG_MASK) ==
10899 		    SCP_QUEUE_ALG_UNRESTRICTED)
10900 			return (CTL_ACTION_PASS);
10901 		/* FALLTHROUGH */
10902 	case CTL_SER_BLOCK:
10903 		return (CTL_ACTION_BLOCK);
10904 	default:
10905 		__assert_unreachable();
10906 	}
10907 }
10908 
10909 /*
10910  * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
10911  * Assumptions:
10912  * - pending_io is generally either incoming, or on the blocked queue
10913  * - starting I/O is the I/O we want to start the check with.
10914  */
10915 static ctl_action
10916 ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
10917 	      union ctl_io **starting_io)
10918 {
10919 	union ctl_io *ooa_io = *starting_io;
10920 	const uint8_t *serialize_row;
10921 	ctl_action action;
10922 
10923 	mtx_assert(&lun->lun_lock, MA_OWNED);
10924 
10925 	/*
10926 	 * Aborted commands are not going to be executed and may even
10927 	 * not report completion, so we don't care about their order.
10928 	 * Let them complete ASAP to clean the OOA queue.
10929 	 */
10930 	if (__predict_false(pending_io->io_hdr.flags & CTL_FLAG_ABORT))
10931 		return (CTL_ACTION_SKIP);
10932 
10933 	/*
10934 	 * Ordered tags have to block until all items ahead of them have
10935 	 * completed.  If we get called with an ordered tag, we always
10936 	 * block, if something else is ahead of us in the queue.
10937 	 */
10938 	if ((pending_io->scsiio.tag_type == CTL_TAG_ORDERED) &&
10939 	    (ooa_io != NULL))
10940 		return (CTL_ACTION_BLOCK);
10941 
10942 	serialize_row = ctl_serialize_table[pending_io->scsiio.seridx];
10943 
10944 	/*
10945 	 * Run back along the OOA queue, starting with the current
10946 	 * blocked I/O and going through every I/O before it on the
10947 	 * queue.  If starting_io is NULL, we'll just end up returning
10948 	 * CTL_ACTION_PASS.
10949 	 */
10950 	for (; ooa_io != NULL;
10951 	     ooa_io = (union ctl_io *)LIST_NEXT(&ooa_io->io_hdr, ooa_links)) {
10952 		action = ctl_check_for_blockage(lun, pending_io, serialize_row,
10953 		    ooa_io);
10954 		if (action != CTL_ACTION_PASS) {
10955 			*starting_io = ooa_io;
10956 			return (action);
10957 		}
10958 	}
10959 
10960 	*starting_io = NULL;
10961 	return (CTL_ACTION_PASS);
10962 }
10963 
10964 /*
10965  * Try to unblock the specified I/O.
10966  *
10967  * skip parameter allows explicitly skip present blocker of the I/O,
10968  * starting from the previous one on OOA queue.  It can be used when
10969  * we know for sure that the blocker I/O does no longer count.
10970  */
10971 static void
10972 ctl_try_unblock_io(struct ctl_lun *lun, union ctl_io *io, bool skip)
10973 {
10974 	struct ctl_softc *softc = lun->ctl_softc;
10975 	union ctl_io *bio, *obio;
10976 	const struct ctl_cmd_entry *entry;
10977 	union ctl_ha_msg msg_info;
10978 	ctl_action action;
10979 
10980 	mtx_assert(&lun->lun_lock, MA_OWNED);
10981 
10982 	if (io->io_hdr.blocker == NULL)
10983 		return;
10984 
10985 	obio = bio = io->io_hdr.blocker;
10986 	if (skip)
10987 		bio = (union ctl_io *)LIST_NEXT(&bio->io_hdr, ooa_links);
10988 	action = ctl_check_ooa(lun, io, &bio);
10989 	if (action == CTL_ACTION_BLOCK) {
10990 		/* Still blocked, but may be by different I/O now. */
10991 		if (bio != obio) {
10992 			TAILQ_REMOVE(&obio->io_hdr.blocked_queue,
10993 			    &io->io_hdr, blocked_links);
10994 			TAILQ_INSERT_TAIL(&bio->io_hdr.blocked_queue,
10995 			    &io->io_hdr, blocked_links);
10996 			io->io_hdr.blocker = bio;
10997 		}
10998 		return;
10999 	}
11000 
11001 	/* No longer blocked, one way or another. */
11002 	TAILQ_REMOVE(&obio->io_hdr.blocked_queue, &io->io_hdr, blocked_links);
11003 	io->io_hdr.blocker = NULL;
11004 
11005 	switch (action) {
11006 	case CTL_ACTION_PASS:
11007 	case CTL_ACTION_SKIP:
11008 
11009 		/* Serializing commands from the other SC retire there. */
11010 		if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) &&
11011 		    (softc->ha_mode != CTL_HA_MODE_XFER)) {
11012 			io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11013 			msg_info.hdr.original_sc = io->io_hdr.remote_io;
11014 			msg_info.hdr.serializing_sc = io;
11015 			msg_info.hdr.msg_type = CTL_MSG_R2R;
11016 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11017 			    sizeof(msg_info.hdr), M_NOWAIT);
11018 			break;
11019 		}
11020 
11021 		/*
11022 		 * Check this I/O for LUN state changes that may have happened
11023 		 * while this command was blocked. The LUN state may have been
11024 		 * changed by a command ahead of us in the queue.
11025 		 */
11026 		entry = ctl_get_cmd_entry(&io->scsiio, NULL);
11027 		if (ctl_scsiio_lun_check(lun, entry, &io->scsiio) != 0) {
11028 			ctl_done(io);
11029 			break;
11030 		}
11031 
11032 		io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11033 		ctl_enqueue_rtr(io);
11034 		break;
11035 	default:
11036 		__assert_unreachable();
11037 	case CTL_ACTION_OVERLAP:
11038 		ctl_set_overlapped_cmd(&io->scsiio);
11039 		goto error;
11040 	case CTL_ACTION_OVERLAP_TAG:
11041 		ctl_set_overlapped_tag(&io->scsiio,
11042 		    io->scsiio.tag_num & 0xff);
11043 error:
11044 		/* Serializing commands from the other SC are done here. */
11045 		if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) &&
11046 		    (softc->ha_mode != CTL_HA_MODE_XFER)) {
11047 			ctl_try_unblock_others(lun, io, TRUE);
11048 			LIST_REMOVE(&io->io_hdr, ooa_links);
11049 
11050 			ctl_copy_sense_data_back(io, &msg_info);
11051 			msg_info.hdr.original_sc = io->io_hdr.remote_io;
11052 			msg_info.hdr.serializing_sc = NULL;
11053 			msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
11054 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11055 			    sizeof(msg_info.scsi), M_WAITOK);
11056 			ctl_free_io(io);
11057 			break;
11058 		}
11059 
11060 		ctl_done(io);
11061 		break;
11062 	}
11063 }
11064 
11065 /*
11066  * Try to unblock I/Os blocked by the specified I/O.
11067  *
11068  * skip parameter allows explicitly skip the specified I/O as blocker,
11069  * starting from the previous one on the OOA queue.  It can be used when
11070  * we know for sure that the specified I/O does no longer count (done).
11071  * It has to be still on OOA queue though so that we know where to start.
11072  */
11073 static void
11074 ctl_try_unblock_others(struct ctl_lun *lun, union ctl_io *bio, bool skip)
11075 {
11076 	union ctl_io *io, *next_io;
11077 
11078 	mtx_assert(&lun->lun_lock, MA_OWNED);
11079 
11080 	for (io = (union ctl_io *)TAILQ_FIRST(&bio->io_hdr.blocked_queue);
11081 	     io != NULL; io = next_io) {
11082 		next_io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr, blocked_links);
11083 
11084 		KASSERT(io->io_hdr.blocker != NULL,
11085 		    ("I/O %p on blocked list without blocker", io));
11086 		ctl_try_unblock_io(lun, io, skip);
11087 	}
11088 	KASSERT(!skip || TAILQ_EMPTY(&bio->io_hdr.blocked_queue),
11089 	    ("blocked_queue is not empty after skipping %p", bio));
11090 }
11091 
11092 /*
11093  * This routine (with one exception) checks LUN flags that can be set by
11094  * commands ahead of us in the OOA queue.  These flags have to be checked
11095  * when a command initially comes in, and when we pull a command off the
11096  * blocked queue and are preparing to execute it.  The reason we have to
11097  * check these flags for commands on the blocked queue is that the LUN
11098  * state may have been changed by a command ahead of us while we're on the
11099  * blocked queue.
11100  *
11101  * Ordering is somewhat important with these checks, so please pay
11102  * careful attention to the placement of any new checks.
11103  */
11104 static int
11105 ctl_scsiio_lun_check(struct ctl_lun *lun,
11106     const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11107 {
11108 	struct ctl_softc *softc = lun->ctl_softc;
11109 	int retval;
11110 	uint32_t residx;
11111 
11112 	retval = 0;
11113 
11114 	mtx_assert(&lun->lun_lock, MA_OWNED);
11115 
11116 	/*
11117 	 * If this shelf is a secondary shelf controller, we may have to
11118 	 * reject some commands disallowed by HA mode and link state.
11119 	 */
11120 	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11121 		if (softc->ha_link == CTL_HA_LINK_OFFLINE &&
11122 		    (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11123 			ctl_set_lun_unavail(ctsio);
11124 			retval = 1;
11125 			goto bailout;
11126 		}
11127 		if ((lun->flags & CTL_LUN_PEER_SC_PRIMARY) == 0 &&
11128 		    (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11129 			ctl_set_lun_transit(ctsio);
11130 			retval = 1;
11131 			goto bailout;
11132 		}
11133 		if (softc->ha_mode == CTL_HA_MODE_ACT_STBY &&
11134 		    (entry->flags & CTL_CMD_FLAG_OK_ON_STANDBY) == 0) {
11135 			ctl_set_lun_standby(ctsio);
11136 			retval = 1;
11137 			goto bailout;
11138 		}
11139 
11140 		/* The rest of checks are only done on executing side */
11141 		if (softc->ha_mode == CTL_HA_MODE_XFER)
11142 			goto bailout;
11143 	}
11144 
11145 	if (entry->pattern & CTL_LUN_PAT_WRITE) {
11146 		if (lun->be_lun->flags & CTL_LUN_FLAG_READONLY) {
11147 			ctl_set_hw_write_protected(ctsio);
11148 			retval = 1;
11149 			goto bailout;
11150 		}
11151 		if ((lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0) {
11152 			ctl_set_sense(ctsio, /*current_error*/ 1,
11153 			    /*sense_key*/ SSD_KEY_DATA_PROTECT,
11154 			    /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
11155 			retval = 1;
11156 			goto bailout;
11157 		}
11158 	}
11159 
11160 	/*
11161 	 * Check for a reservation conflict.  If this command isn't allowed
11162 	 * even on reserved LUNs, and if this initiator isn't the one who
11163 	 * reserved us, reject the command with a reservation conflict.
11164 	 */
11165 	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11166 	if ((lun->flags & CTL_LUN_RESERVED)
11167 	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11168 		if (lun->res_idx != residx) {
11169 			ctl_set_reservation_conflict(ctsio);
11170 			retval = 1;
11171 			goto bailout;
11172 		}
11173 	}
11174 
11175 	if ((lun->flags & CTL_LUN_PR_RESERVED) == 0 ||
11176 	    (entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV)) {
11177 		/* No reservation or command is allowed. */;
11178 	} else if ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_WRESV) &&
11179 	    (lun->pr_res_type == SPR_TYPE_WR_EX ||
11180 	     lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
11181 	     lun->pr_res_type == SPR_TYPE_WR_EX_AR)) {
11182 		/* The command is allowed for Write Exclusive resv. */;
11183 	} else {
11184 		/*
11185 		 * if we aren't registered or it's a res holder type
11186 		 * reservation and this isn't the res holder then set a
11187 		 * conflict.
11188 		 */
11189 		if (ctl_get_prkey(lun, residx) == 0 ||
11190 		    (residx != lun->pr_res_idx && lun->pr_res_type < 4)) {
11191 			ctl_set_reservation_conflict(ctsio);
11192 			retval = 1;
11193 			goto bailout;
11194 		}
11195 	}
11196 
11197 	if ((entry->flags & CTL_CMD_FLAG_OK_ON_NO_MEDIA) == 0) {
11198 		if (lun->flags & CTL_LUN_EJECTED)
11199 			ctl_set_lun_ejected(ctsio);
11200 		else if (lun->flags & CTL_LUN_NO_MEDIA) {
11201 			if (lun->flags & CTL_LUN_REMOVABLE)
11202 				ctl_set_lun_no_media(ctsio);
11203 			else
11204 				ctl_set_lun_int_reqd(ctsio);
11205 		} else if (lun->flags & CTL_LUN_STOPPED)
11206 			ctl_set_lun_stopped(ctsio);
11207 		else
11208 			goto bailout;
11209 		retval = 1;
11210 		goto bailout;
11211 	}
11212 
11213 bailout:
11214 	return (retval);
11215 }
11216 
11217 static void
11218 ctl_failover_io(union ctl_io *io, int have_lock)
11219 {
11220 	ctl_set_busy(&io->scsiio);
11221 	ctl_done(io);
11222 }
11223 
11224 static void
11225 ctl_failover_lun(union ctl_io *rio)
11226 {
11227 	struct ctl_softc *softc = CTL_SOFTC(rio);
11228 	struct ctl_lun *lun;
11229 	struct ctl_io_hdr *io, *next_io;
11230 	uint32_t targ_lun;
11231 
11232 	targ_lun = rio->io_hdr.nexus.targ_mapped_lun;
11233 	CTL_DEBUG_PRINT(("FAILOVER for lun %u\n", targ_lun));
11234 
11235 	/* Find and lock the LUN. */
11236 	mtx_lock(&softc->ctl_lock);
11237 	if (targ_lun > ctl_max_luns ||
11238 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11239 		mtx_unlock(&softc->ctl_lock);
11240 		return;
11241 	}
11242 	mtx_lock(&lun->lun_lock);
11243 	mtx_unlock(&softc->ctl_lock);
11244 	if (lun->flags & CTL_LUN_DISABLED) {
11245 		mtx_unlock(&lun->lun_lock);
11246 		return;
11247 	}
11248 
11249 	if (softc->ha_mode == CTL_HA_MODE_XFER) {
11250 		LIST_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11251 			/* We are master */
11252 			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11253 				if (io->flags & CTL_FLAG_IO_ACTIVE) {
11254 					io->flags |= CTL_FLAG_ABORT |
11255 					    CTL_FLAG_FAILOVER;
11256 					ctl_try_unblock_io(lun,
11257 					    (union ctl_io *)io, FALSE);
11258 				} else { /* This can be only due to DATAMOVE */
11259 					io->msg_type = CTL_MSG_DATAMOVE_DONE;
11260 					io->flags &= ~CTL_FLAG_DMA_INPROG;
11261 					io->flags |= CTL_FLAG_IO_ACTIVE;
11262 					io->port_status = 31340;
11263 					ctl_enqueue_isc((union ctl_io *)io);
11264 				}
11265 			} else
11266 			/* We are slave */
11267 			if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11268 				io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11269 				if (io->flags & CTL_FLAG_IO_ACTIVE) {
11270 					io->flags |= CTL_FLAG_FAILOVER;
11271 				} else {
11272 					ctl_set_busy(&((union ctl_io *)io)->
11273 					    scsiio);
11274 					ctl_done((union ctl_io *)io);
11275 				}
11276 			}
11277 		}
11278 	} else { /* SERIALIZE modes */
11279 		LIST_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11280 			/* We are master */
11281 			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11282 				if (io->blocker != NULL) {
11283 					TAILQ_REMOVE(&io->blocker->io_hdr.blocked_queue,
11284 					    io, blocked_links);
11285 					io->blocker = NULL;
11286 				}
11287 				ctl_try_unblock_others(lun, (union ctl_io *)io,
11288 				    TRUE);
11289 				LIST_REMOVE(io, ooa_links);
11290 				ctl_free_io((union ctl_io *)io);
11291 			} else
11292 			/* We are slave */
11293 			if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11294 				io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11295 				if (!(io->flags & CTL_FLAG_IO_ACTIVE)) {
11296 					ctl_set_busy(&((union ctl_io *)io)->
11297 					    scsiio);
11298 					ctl_done((union ctl_io *)io);
11299 				}
11300 			}
11301 		}
11302 	}
11303 	mtx_unlock(&lun->lun_lock);
11304 }
11305 
11306 static void
11307 ctl_scsiio_precheck(struct ctl_scsiio *ctsio)
11308 {
11309 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
11310 	struct ctl_lun *lun;
11311 	const struct ctl_cmd_entry *entry;
11312 	union ctl_io *bio;
11313 	uint32_t initidx, targ_lun;
11314 
11315 	lun = NULL;
11316 	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11317 	if (targ_lun < ctl_max_luns)
11318 		lun = softc->ctl_luns[targ_lun];
11319 	if (lun) {
11320 		/*
11321 		 * If the LUN is invalid, pretend that it doesn't exist.
11322 		 * It will go away as soon as all pending I/O has been
11323 		 * completed.
11324 		 */
11325 		mtx_lock(&lun->lun_lock);
11326 		if (lun->flags & CTL_LUN_DISABLED) {
11327 			mtx_unlock(&lun->lun_lock);
11328 			lun = NULL;
11329 		}
11330 	}
11331 	CTL_LUN(ctsio) = lun;
11332 	if (lun) {
11333 		CTL_BACKEND_LUN(ctsio) = lun->be_lun;
11334 
11335 		/*
11336 		 * Every I/O goes into the OOA queue for a particular LUN,
11337 		 * and stays there until completion.
11338 		 */
11339 #ifdef CTL_TIME_IO
11340 		if (LIST_EMPTY(&lun->ooa_queue))
11341 			lun->idle_time += getsbinuptime() - lun->last_busy;
11342 #endif
11343 		LIST_INSERT_HEAD(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
11344 	}
11345 
11346 	/* Get command entry and return error if it is unsuppotyed. */
11347 	entry = ctl_validate_command(ctsio);
11348 	if (entry == NULL) {
11349 		if (lun)
11350 			mtx_unlock(&lun->lun_lock);
11351 		return;
11352 	}
11353 
11354 	ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11355 	ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11356 
11357 	/*
11358 	 * Check to see whether we can send this command to LUNs that don't
11359 	 * exist.  This should pretty much only be the case for inquiry
11360 	 * and request sense.  Further checks, below, really require having
11361 	 * a LUN, so we can't really check the command anymore.  Just put
11362 	 * it on the rtr queue.
11363 	 */
11364 	if (lun == NULL) {
11365 		if (entry->flags & CTL_CMD_FLAG_OK_ON_NO_LUN) {
11366 			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11367 			ctl_enqueue_rtr((union ctl_io *)ctsio);
11368 			return;
11369 		}
11370 
11371 		ctl_set_unsupported_lun(ctsio);
11372 		ctl_done((union ctl_io *)ctsio);
11373 		CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11374 		return;
11375 	} else {
11376 		/*
11377 		 * Make sure we support this particular command on this LUN.
11378 		 * e.g., we don't support writes to the control LUN.
11379 		 */
11380 		if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11381 			mtx_unlock(&lun->lun_lock);
11382 			ctl_set_invalid_opcode(ctsio);
11383 			ctl_done((union ctl_io *)ctsio);
11384 			return;
11385 		}
11386 	}
11387 
11388 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11389 
11390 	/*
11391 	 * If we've got a request sense, it'll clear the contingent
11392 	 * allegiance condition.  Otherwise, if we have a CA condition for
11393 	 * this initiator, clear it, because it sent down a command other
11394 	 * than request sense.
11395 	 */
11396 	if (ctsio->cdb[0] != REQUEST_SENSE) {
11397 		struct scsi_sense_data *ps;
11398 
11399 		ps = lun->pending_sense[initidx / CTL_MAX_INIT_PER_PORT];
11400 		if (ps != NULL)
11401 			ps[initidx % CTL_MAX_INIT_PER_PORT].error_code = 0;
11402 	}
11403 
11404 	/*
11405 	 * If the command has this flag set, it handles its own unit
11406 	 * attention reporting, we shouldn't do anything.  Otherwise we
11407 	 * check for any pending unit attentions, and send them back to the
11408 	 * initiator.  We only do this when a command initially comes in,
11409 	 * not when we pull it off the blocked queue.
11410 	 *
11411 	 * According to SAM-3, section 5.3.2, the order that things get
11412 	 * presented back to the host is basically unit attentions caused
11413 	 * by some sort of reset event, busy status, reservation conflicts
11414 	 * or task set full, and finally any other status.
11415 	 *
11416 	 * One issue here is that some of the unit attentions we report
11417 	 * don't fall into the "reset" category (e.g. "reported luns data
11418 	 * has changed").  So reporting it here, before the reservation
11419 	 * check, may be technically wrong.  I guess the only thing to do
11420 	 * would be to check for and report the reset events here, and then
11421 	 * check for the other unit attention types after we check for a
11422 	 * reservation conflict.
11423 	 *
11424 	 * XXX KDM need to fix this
11425 	 */
11426 	if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11427 		ctl_ua_type ua_type;
11428 		u_int sense_len = 0;
11429 
11430 		ua_type = ctl_build_ua(lun, initidx, &ctsio->sense_data,
11431 		    &sense_len, SSD_TYPE_NONE);
11432 		if (ua_type != CTL_UA_NONE) {
11433 			mtx_unlock(&lun->lun_lock);
11434 			ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11435 			ctsio->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
11436 			ctsio->sense_len = sense_len;
11437 			ctl_done((union ctl_io *)ctsio);
11438 			return;
11439 		}
11440 	}
11441 
11442 	if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
11443 		mtx_unlock(&lun->lun_lock);
11444 		ctl_done((union ctl_io *)ctsio);
11445 		return;
11446 	}
11447 
11448 	/*
11449 	 * XXX CHD this is where we want to send IO to other side if
11450 	 * this LUN is secondary on this SC. We will need to make a copy
11451 	 * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11452 	 * the copy we send as FROM_OTHER.
11453 	 * We also need to stuff the address of the original IO so we can
11454 	 * find it easily. Something similar will need be done on the other
11455 	 * side so when we are done we can find the copy.
11456 	 */
11457 	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
11458 	    (lun->flags & CTL_LUN_PEER_SC_PRIMARY) != 0 &&
11459 	    (entry->flags & CTL_CMD_FLAG_RUN_HERE) == 0) {
11460 		union ctl_ha_msg msg_info;
11461 		int isc_retval;
11462 
11463 		ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11464 		ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11465 		mtx_unlock(&lun->lun_lock);
11466 
11467 		msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11468 		msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11469 		msg_info.hdr.serializing_sc = NULL;
11470 		msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11471 		msg_info.scsi.tag_num = ctsio->tag_num;
11472 		msg_info.scsi.tag_type = ctsio->tag_type;
11473 		memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11474 		msg_info.scsi.cdb_len = ctsio->cdb_len;
11475 		msg_info.scsi.priority = ctsio->priority;
11476 
11477 		if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11478 		    sizeof(msg_info.scsi) - sizeof(msg_info.scsi.sense_data),
11479 		    M_WAITOK)) > CTL_HA_STATUS_SUCCESS) {
11480 			ctsio->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11481 			ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
11482 			ctl_set_busy(ctsio);
11483 			ctl_done((union ctl_io *)ctsio);
11484 			return;
11485 		}
11486 		return;
11487 	}
11488 
11489 	bio = (union ctl_io *)LIST_NEXT(&ctsio->io_hdr, ooa_links);
11490 	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio, &bio)) {
11491 	case CTL_ACTION_PASS:
11492 	case CTL_ACTION_SKIP:
11493 		ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11494 		mtx_unlock(&lun->lun_lock);
11495 		ctl_enqueue_rtr((union ctl_io *)ctsio);
11496 		break;
11497 	case CTL_ACTION_BLOCK:
11498 		ctsio->io_hdr.blocker = bio;
11499 		TAILQ_INSERT_TAIL(&bio->io_hdr.blocked_queue, &ctsio->io_hdr,
11500 				  blocked_links);
11501 		mtx_unlock(&lun->lun_lock);
11502 		break;
11503 	case CTL_ACTION_OVERLAP:
11504 		mtx_unlock(&lun->lun_lock);
11505 		ctl_set_overlapped_cmd(ctsio);
11506 		ctl_done((union ctl_io *)ctsio);
11507 		break;
11508 	case CTL_ACTION_OVERLAP_TAG:
11509 		mtx_unlock(&lun->lun_lock);
11510 		ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11511 		ctl_done((union ctl_io *)ctsio);
11512 		break;
11513 	default:
11514 		__assert_unreachable();
11515 	}
11516 }
11517 
11518 const struct ctl_cmd_entry *
11519 ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11520 {
11521 	const struct ctl_cmd_entry *entry;
11522 	int service_action;
11523 
11524 	entry = &ctl_cmd_table[ctsio->cdb[0]];
11525 	if (sa)
11526 		*sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11527 	if (entry->flags & CTL_CMD_FLAG_SA5) {
11528 		service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11529 		entry = &((const struct ctl_cmd_entry *)
11530 		    entry->execute)[service_action];
11531 	}
11532 	return (entry);
11533 }
11534 
11535 const struct ctl_cmd_entry *
11536 ctl_validate_command(struct ctl_scsiio *ctsio)
11537 {
11538 	const struct ctl_cmd_entry *entry;
11539 	int i, sa;
11540 	uint8_t diff;
11541 
11542 	entry = ctl_get_cmd_entry(ctsio, &sa);
11543 	ctsio->seridx = entry->seridx;
11544 	if (entry->execute == NULL) {
11545 		if (sa)
11546 			ctl_set_invalid_field(ctsio,
11547 					      /*sks_valid*/ 1,
11548 					      /*command*/ 1,
11549 					      /*field*/ 1,
11550 					      /*bit_valid*/ 1,
11551 					      /*bit*/ 4);
11552 		else
11553 			ctl_set_invalid_opcode(ctsio);
11554 		ctl_done((union ctl_io *)ctsio);
11555 		return (NULL);
11556 	}
11557 	KASSERT(entry->length > 0,
11558 	    ("Not defined length for command 0x%02x/0x%02x",
11559 	     ctsio->cdb[0], ctsio->cdb[1]));
11560 	for (i = 1; i < entry->length; i++) {
11561 		diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11562 		if (diff == 0)
11563 			continue;
11564 		ctl_set_invalid_field(ctsio,
11565 				      /*sks_valid*/ 1,
11566 				      /*command*/ 1,
11567 				      /*field*/ i,
11568 				      /*bit_valid*/ 1,
11569 				      /*bit*/ fls(diff) - 1);
11570 		ctl_done((union ctl_io *)ctsio);
11571 		return (NULL);
11572 	}
11573 	return (entry);
11574 }
11575 
11576 static int
11577 ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11578 {
11579 
11580 	switch (lun_type) {
11581 	case T_DIRECT:
11582 		if ((entry->flags & CTL_CMD_FLAG_OK_ON_DIRECT) == 0)
11583 			return (0);
11584 		break;
11585 	case T_PROCESSOR:
11586 		if ((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0)
11587 			return (0);
11588 		break;
11589 	case T_CDROM:
11590 		if ((entry->flags & CTL_CMD_FLAG_OK_ON_CDROM) == 0)
11591 			return (0);
11592 		break;
11593 	default:
11594 		return (0);
11595 	}
11596 	return (1);
11597 }
11598 
11599 static int
11600 ctl_scsiio(struct ctl_scsiio *ctsio)
11601 {
11602 	int retval;
11603 	const struct ctl_cmd_entry *entry;
11604 
11605 	retval = CTL_RETVAL_COMPLETE;
11606 
11607 	CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11608 
11609 	entry = ctl_get_cmd_entry(ctsio, NULL);
11610 
11611 	/*
11612 	 * If this I/O has been aborted, just send it straight to
11613 	 * ctl_done() without executing it.
11614 	 */
11615 	if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11616 		ctl_done((union ctl_io *)ctsio);
11617 		goto bailout;
11618 	}
11619 
11620 	/*
11621 	 * All the checks should have been handled by ctl_scsiio_precheck().
11622 	 * We should be clear now to just execute the I/O.
11623 	 */
11624 	retval = entry->execute(ctsio);
11625 
11626 bailout:
11627 	return (retval);
11628 }
11629 
11630 static int
11631 ctl_target_reset(union ctl_io *io)
11632 {
11633 	struct ctl_softc *softc = CTL_SOFTC(io);
11634 	struct ctl_port *port = CTL_PORT(io);
11635 	struct ctl_lun *lun;
11636 	uint32_t initidx;
11637 	ctl_ua_type ua_type;
11638 
11639 	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11640 		union ctl_ha_msg msg_info;
11641 
11642 		msg_info.hdr.nexus = io->io_hdr.nexus;
11643 		msg_info.task.task_action = io->taskio.task_action;
11644 		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11645 		msg_info.hdr.original_sc = NULL;
11646 		msg_info.hdr.serializing_sc = NULL;
11647 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11648 		    sizeof(msg_info.task), M_WAITOK);
11649 	}
11650 
11651 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
11652 	if (io->taskio.task_action == CTL_TASK_TARGET_RESET)
11653 		ua_type = CTL_UA_TARG_RESET;
11654 	else
11655 		ua_type = CTL_UA_BUS_RESET;
11656 	mtx_lock(&softc->ctl_lock);
11657 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
11658 		if (port != NULL &&
11659 		    ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
11660 			continue;
11661 		ctl_do_lun_reset(lun, initidx, ua_type);
11662 	}
11663 	mtx_unlock(&softc->ctl_lock);
11664 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11665 	return (0);
11666 }
11667 
11668 /*
11669  * The LUN should always be set.  The I/O is optional, and is used to
11670  * distinguish between I/Os sent by this initiator, and by other
11671  * initiators.  We set unit attention for initiators other than this one.
11672  * SAM-3 is vague on this point.  It does say that a unit attention should
11673  * be established for other initiators when a LUN is reset (see section
11674  * 5.7.3), but it doesn't specifically say that the unit attention should
11675  * be established for this particular initiator when a LUN is reset.  Here
11676  * is the relevant text, from SAM-3 rev 8:
11677  *
11678  * 5.7.2 When a SCSI initiator port aborts its own tasks
11679  *
11680  * When a SCSI initiator port causes its own task(s) to be aborted, no
11681  * notification that the task(s) have been aborted shall be returned to
11682  * the SCSI initiator port other than the completion response for the
11683  * command or task management function action that caused the task(s) to
11684  * be aborted and notification(s) associated with related effects of the
11685  * action (e.g., a reset unit attention condition).
11686  *
11687  * XXX KDM for now, we're setting unit attention for all initiators.
11688  */
11689 static void
11690 ctl_do_lun_reset(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua_type)
11691 {
11692 	struct ctl_io_hdr *xioh;
11693 	int i;
11694 
11695 	mtx_lock(&lun->lun_lock);
11696 	/* Abort tasks. */
11697 	LIST_FOREACH(xioh, &lun->ooa_queue, ooa_links) {
11698 		xioh->flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
11699 		ctl_try_unblock_io(lun, (union ctl_io *)xioh, FALSE);
11700 	}
11701 	/* Clear CA. */
11702 	for (i = 0; i < ctl_max_ports; i++) {
11703 		free(lun->pending_sense[i], M_CTL);
11704 		lun->pending_sense[i] = NULL;
11705 	}
11706 	/* Clear reservation. */
11707 	lun->flags &= ~CTL_LUN_RESERVED;
11708 	/* Clear prevent media removal. */
11709 	if (lun->prevent) {
11710 		for (i = 0; i < CTL_MAX_INITIATORS; i++)
11711 			ctl_clear_mask(lun->prevent, i);
11712 		lun->prevent_count = 0;
11713 	}
11714 	/* Clear TPC status */
11715 	ctl_tpc_lun_clear(lun, -1);
11716 	/* Establish UA. */
11717 #if 0
11718 	ctl_est_ua_all(lun, initidx, ua_type);
11719 #else
11720 	ctl_est_ua_all(lun, -1, ua_type);
11721 #endif
11722 	mtx_unlock(&lun->lun_lock);
11723 }
11724 
11725 static int
11726 ctl_lun_reset(union ctl_io *io)
11727 {
11728 	struct ctl_softc *softc = CTL_SOFTC(io);
11729 	struct ctl_lun *lun;
11730 	uint32_t targ_lun, initidx;
11731 
11732 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11733 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
11734 	mtx_lock(&softc->ctl_lock);
11735 	if (targ_lun >= ctl_max_luns ||
11736 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11737 		mtx_unlock(&softc->ctl_lock);
11738 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11739 		return (1);
11740 	}
11741 	ctl_do_lun_reset(lun, initidx, CTL_UA_LUN_RESET);
11742 	mtx_unlock(&softc->ctl_lock);
11743 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11744 
11745 	if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0) {
11746 		union ctl_ha_msg msg_info;
11747 
11748 		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11749 		msg_info.hdr.nexus = io->io_hdr.nexus;
11750 		msg_info.task.task_action = CTL_TASK_LUN_RESET;
11751 		msg_info.hdr.original_sc = NULL;
11752 		msg_info.hdr.serializing_sc = NULL;
11753 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11754 		    sizeof(msg_info.task), M_WAITOK);
11755 	}
11756 	return (0);
11757 }
11758 
11759 static void
11760 ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
11761     int other_sc)
11762 {
11763 	struct ctl_io_hdr *xioh;
11764 
11765 	mtx_assert(&lun->lun_lock, MA_OWNED);
11766 
11767 	/*
11768 	 * Run through the OOA queue and attempt to find the given I/O.
11769 	 * The target port, initiator ID, tag type and tag number have to
11770 	 * match the values that we got from the initiator.  If we have an
11771 	 * untagged command to abort, simply abort the first untagged command
11772 	 * we come to.  We only allow one untagged command at a time of course.
11773 	 */
11774 	LIST_FOREACH(xioh, &lun->ooa_queue, ooa_links) {
11775 		union ctl_io *xio = (union ctl_io *)xioh;
11776 		if ((targ_port == UINT32_MAX ||
11777 		     targ_port == xioh->nexus.targ_port) &&
11778 		    (init_id == UINT32_MAX ||
11779 		     init_id == xioh->nexus.initid)) {
11780 			if (targ_port != xioh->nexus.targ_port ||
11781 			    init_id != xioh->nexus.initid)
11782 				xioh->flags |= CTL_FLAG_ABORT_STATUS;
11783 			xioh->flags |= CTL_FLAG_ABORT;
11784 			if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11785 				union ctl_ha_msg msg_info;
11786 
11787 				msg_info.hdr.nexus = xioh->nexus;
11788 				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
11789 				msg_info.task.tag_num = xio->scsiio.tag_num;
11790 				msg_info.task.tag_type = xio->scsiio.tag_type;
11791 				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11792 				msg_info.hdr.original_sc = NULL;
11793 				msg_info.hdr.serializing_sc = NULL;
11794 				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11795 				    sizeof(msg_info.task), M_NOWAIT);
11796 			}
11797 			ctl_try_unblock_io(lun, xio, FALSE);
11798 		}
11799 	}
11800 }
11801 
11802 static int
11803 ctl_abort_task_set(union ctl_io *io)
11804 {
11805 	struct ctl_softc *softc = CTL_SOFTC(io);
11806 	struct ctl_lun *lun;
11807 	uint32_t targ_lun;
11808 
11809 	/*
11810 	 * Look up the LUN.
11811 	 */
11812 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11813 	mtx_lock(&softc->ctl_lock);
11814 	if (targ_lun >= ctl_max_luns ||
11815 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11816 		mtx_unlock(&softc->ctl_lock);
11817 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11818 		return (1);
11819 	}
11820 
11821 	mtx_lock(&lun->lun_lock);
11822 	mtx_unlock(&softc->ctl_lock);
11823 	if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
11824 		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
11825 		    io->io_hdr.nexus.initid,
11826 		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11827 	} else { /* CTL_TASK_CLEAR_TASK_SET */
11828 		ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
11829 		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11830 	}
11831 	mtx_unlock(&lun->lun_lock);
11832 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11833 	return (0);
11834 }
11835 
11836 static void
11837 ctl_i_t_nexus_loss(struct ctl_softc *softc, uint32_t initidx,
11838     ctl_ua_type ua_type)
11839 {
11840 	struct ctl_lun *lun;
11841 	struct scsi_sense_data *ps;
11842 	uint32_t p, i;
11843 
11844 	p = initidx / CTL_MAX_INIT_PER_PORT;
11845 	i = initidx % CTL_MAX_INIT_PER_PORT;
11846 	mtx_lock(&softc->ctl_lock);
11847 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
11848 		mtx_lock(&lun->lun_lock);
11849 		/* Abort tasks. */
11850 		ctl_abort_tasks_lun(lun, p, i, 1);
11851 		/* Clear CA. */
11852 		ps = lun->pending_sense[p];
11853 		if (ps != NULL)
11854 			ps[i].error_code = 0;
11855 		/* Clear reservation. */
11856 		if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == initidx))
11857 			lun->flags &= ~CTL_LUN_RESERVED;
11858 		/* Clear prevent media removal. */
11859 		if (lun->prevent && ctl_is_set(lun->prevent, initidx)) {
11860 			ctl_clear_mask(lun->prevent, initidx);
11861 			lun->prevent_count--;
11862 		}
11863 		/* Clear TPC status */
11864 		ctl_tpc_lun_clear(lun, initidx);
11865 		/* Establish UA. */
11866 		ctl_est_ua(lun, initidx, ua_type);
11867 		mtx_unlock(&lun->lun_lock);
11868 	}
11869 	mtx_unlock(&softc->ctl_lock);
11870 }
11871 
11872 static int
11873 ctl_i_t_nexus_reset(union ctl_io *io)
11874 {
11875 	struct ctl_softc *softc = CTL_SOFTC(io);
11876 	uint32_t initidx;
11877 
11878 	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11879 		union ctl_ha_msg msg_info;
11880 
11881 		msg_info.hdr.nexus = io->io_hdr.nexus;
11882 		msg_info.task.task_action = CTL_TASK_I_T_NEXUS_RESET;
11883 		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11884 		msg_info.hdr.original_sc = NULL;
11885 		msg_info.hdr.serializing_sc = NULL;
11886 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11887 		    sizeof(msg_info.task), M_WAITOK);
11888 	}
11889 
11890 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
11891 	ctl_i_t_nexus_loss(softc, initidx, CTL_UA_I_T_NEXUS_LOSS);
11892 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11893 	return (0);
11894 }
11895 
11896 static int
11897 ctl_abort_task(union ctl_io *io)
11898 {
11899 	struct ctl_softc *softc = CTL_SOFTC(io);
11900 	struct ctl_io_hdr *xioh;
11901 	struct ctl_lun *lun;
11902 	uint32_t targ_lun;
11903 
11904 	/*
11905 	 * Look up the LUN.
11906 	 */
11907 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11908 	mtx_lock(&softc->ctl_lock);
11909 	if (targ_lun >= ctl_max_luns ||
11910 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11911 		mtx_unlock(&softc->ctl_lock);
11912 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11913 		return (1);
11914 	}
11915 
11916 	mtx_lock(&lun->lun_lock);
11917 	mtx_unlock(&softc->ctl_lock);
11918 	/*
11919 	 * Run through the OOA queue and attempt to find the given I/O.
11920 	 * The target port, initiator ID, tag type and tag number have to
11921 	 * match the values that we got from the initiator.  If we have an
11922 	 * untagged command to abort, simply abort the first untagged command
11923 	 * we come to.  We only allow one untagged command at a time of course.
11924 	 */
11925 	LIST_FOREACH(xioh, &lun->ooa_queue, ooa_links) {
11926 		union ctl_io *xio = (union ctl_io *)xioh;
11927 		if ((xioh->nexus.targ_port != io->io_hdr.nexus.targ_port)
11928 		 || (xioh->nexus.initid != io->io_hdr.nexus.initid)
11929 		 || (xioh->flags & CTL_FLAG_ABORT))
11930 			continue;
11931 
11932 		/*
11933 		 * If the abort says that the task is untagged, the
11934 		 * task in the queue must be untagged.  Otherwise,
11935 		 * we just check to see whether the tag numbers
11936 		 * match.  This is because the QLogic firmware
11937 		 * doesn't pass back the tag type in an abort
11938 		 * request.
11939 		 */
11940 #if 0
11941 		if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
11942 		  && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
11943 		 || (xio->scsiio.tag_num == io->taskio.tag_num)) {
11944 #else
11945 		/*
11946 		 * XXX KDM we've got problems with FC, because it
11947 		 * doesn't send down a tag type with aborts.  So we
11948 		 * can only really go by the tag number...
11949 		 * This may cause problems with parallel SCSI.
11950 		 * Need to figure that out!!
11951 		 */
11952 		if (xio->scsiio.tag_num == io->taskio.tag_num) {
11953 #endif
11954 			xioh->flags |= CTL_FLAG_ABORT;
11955 			if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0 &&
11956 			    !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11957 				union ctl_ha_msg msg_info;
11958 
11959 				msg_info.hdr.nexus = io->io_hdr.nexus;
11960 				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
11961 				msg_info.task.tag_num = io->taskio.tag_num;
11962 				msg_info.task.tag_type = io->taskio.tag_type;
11963 				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11964 				msg_info.hdr.original_sc = NULL;
11965 				msg_info.hdr.serializing_sc = NULL;
11966 				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11967 				    sizeof(msg_info.task), M_NOWAIT);
11968 			}
11969 			ctl_try_unblock_io(lun, xio, FALSE);
11970 		}
11971 	}
11972 	mtx_unlock(&lun->lun_lock);
11973 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11974 	return (0);
11975 }
11976 
11977 static int
11978 ctl_query_task(union ctl_io *io, int task_set)
11979 {
11980 	struct ctl_softc *softc = CTL_SOFTC(io);
11981 	struct ctl_io_hdr *xioh;
11982 	struct ctl_lun *lun;
11983 	int found = 0;
11984 	uint32_t targ_lun;
11985 
11986 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11987 	mtx_lock(&softc->ctl_lock);
11988 	if (targ_lun >= ctl_max_luns ||
11989 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11990 		mtx_unlock(&softc->ctl_lock);
11991 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11992 		return (1);
11993 	}
11994 	mtx_lock(&lun->lun_lock);
11995 	mtx_unlock(&softc->ctl_lock);
11996 	LIST_FOREACH(xioh, &lun->ooa_queue, ooa_links) {
11997 		union ctl_io *xio = (union ctl_io *)xioh;
11998 		if ((xioh->nexus.targ_port != io->io_hdr.nexus.targ_port)
11999 		 || (xioh->nexus.initid != io->io_hdr.nexus.initid)
12000 		 || (xioh->flags & CTL_FLAG_ABORT))
12001 			continue;
12002 
12003 		if (task_set || xio->scsiio.tag_num == io->taskio.tag_num) {
12004 			found = 1;
12005 			break;
12006 		}
12007 	}
12008 	mtx_unlock(&lun->lun_lock);
12009 	if (found)
12010 		io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12011 	else
12012 		io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12013 	return (0);
12014 }
12015 
12016 static int
12017 ctl_query_async_event(union ctl_io *io)
12018 {
12019 	struct ctl_softc *softc = CTL_SOFTC(io);
12020 	struct ctl_lun *lun;
12021 	ctl_ua_type ua;
12022 	uint32_t targ_lun, initidx;
12023 
12024 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12025 	mtx_lock(&softc->ctl_lock);
12026 	if (targ_lun >= ctl_max_luns ||
12027 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12028 		mtx_unlock(&softc->ctl_lock);
12029 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12030 		return (1);
12031 	}
12032 	mtx_lock(&lun->lun_lock);
12033 	mtx_unlock(&softc->ctl_lock);
12034 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
12035 	ua = ctl_build_qae(lun, initidx, io->taskio.task_resp);
12036 	mtx_unlock(&lun->lun_lock);
12037 	if (ua != CTL_UA_NONE)
12038 		io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12039 	else
12040 		io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12041 	return (0);
12042 }
12043 
12044 static void
12045 ctl_run_task(union ctl_io *io)
12046 {
12047 	int retval = 1;
12048 
12049 	CTL_DEBUG_PRINT(("ctl_run_task\n"));
12050 	KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12051 	    ("ctl_run_task: Unextected io_type %d\n", io->io_hdr.io_type));
12052 	io->taskio.task_status = CTL_TASK_FUNCTION_NOT_SUPPORTED;
12053 	bzero(io->taskio.task_resp, sizeof(io->taskio.task_resp));
12054 	switch (io->taskio.task_action) {
12055 	case CTL_TASK_ABORT_TASK:
12056 		retval = ctl_abort_task(io);
12057 		break;
12058 	case CTL_TASK_ABORT_TASK_SET:
12059 	case CTL_TASK_CLEAR_TASK_SET:
12060 		retval = ctl_abort_task_set(io);
12061 		break;
12062 	case CTL_TASK_CLEAR_ACA:
12063 		break;
12064 	case CTL_TASK_I_T_NEXUS_RESET:
12065 		retval = ctl_i_t_nexus_reset(io);
12066 		break;
12067 	case CTL_TASK_LUN_RESET:
12068 		retval = ctl_lun_reset(io);
12069 		break;
12070 	case CTL_TASK_TARGET_RESET:
12071 	case CTL_TASK_BUS_RESET:
12072 		retval = ctl_target_reset(io);
12073 		break;
12074 	case CTL_TASK_PORT_LOGIN:
12075 		break;
12076 	case CTL_TASK_PORT_LOGOUT:
12077 		break;
12078 	case CTL_TASK_QUERY_TASK:
12079 		retval = ctl_query_task(io, 0);
12080 		break;
12081 	case CTL_TASK_QUERY_TASK_SET:
12082 		retval = ctl_query_task(io, 1);
12083 		break;
12084 	case CTL_TASK_QUERY_ASYNC_EVENT:
12085 		retval = ctl_query_async_event(io);
12086 		break;
12087 	default:
12088 		printf("%s: got unknown task management event %d\n",
12089 		       __func__, io->taskio.task_action);
12090 		break;
12091 	}
12092 	if (retval == 0)
12093 		io->io_hdr.status = CTL_SUCCESS;
12094 	else
12095 		io->io_hdr.status = CTL_ERROR;
12096 	ctl_done(io);
12097 }
12098 
12099 /*
12100  * For HA operation.  Handle commands that come in from the other
12101  * controller.
12102  */
12103 static void
12104 ctl_handle_isc(union ctl_io *io)
12105 {
12106 	struct ctl_softc *softc = CTL_SOFTC(io);
12107 	struct ctl_lun *lun;
12108 	const struct ctl_cmd_entry *entry;
12109 	uint32_t targ_lun;
12110 
12111 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12112 	switch (io->io_hdr.msg_type) {
12113 	case CTL_MSG_SERIALIZE:
12114 		ctl_serialize_other_sc_cmd(&io->scsiio);
12115 		break;
12116 	case CTL_MSG_R2R:		/* Only used in SER_ONLY mode. */
12117 		entry = ctl_get_cmd_entry(&io->scsiio, NULL);
12118 		if (targ_lun >= ctl_max_luns ||
12119 		    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12120 			ctl_done(io);
12121 			break;
12122 		}
12123 		mtx_lock(&lun->lun_lock);
12124 		if (ctl_scsiio_lun_check(lun, entry, &io->scsiio) != 0) {
12125 			mtx_unlock(&lun->lun_lock);
12126 			ctl_done(io);
12127 			break;
12128 		}
12129 		io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12130 		mtx_unlock(&lun->lun_lock);
12131 		ctl_enqueue_rtr(io);
12132 		break;
12133 	case CTL_MSG_FINISH_IO:
12134 		if (softc->ha_mode == CTL_HA_MODE_XFER) {
12135 			ctl_done(io);
12136 			break;
12137 		}
12138 		if (targ_lun >= ctl_max_luns ||
12139 		    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12140 			ctl_free_io(io);
12141 			break;
12142 		}
12143 		mtx_lock(&lun->lun_lock);
12144 		ctl_try_unblock_others(lun, io, TRUE);
12145 		LIST_REMOVE(&io->io_hdr, ooa_links);
12146 		mtx_unlock(&lun->lun_lock);
12147 		ctl_free_io(io);
12148 		break;
12149 	case CTL_MSG_PERS_ACTION:
12150 		ctl_hndl_per_res_out_on_other_sc(io);
12151 		ctl_free_io(io);
12152 		break;
12153 	case CTL_MSG_BAD_JUJU:
12154 		ctl_done(io);
12155 		break;
12156 	case CTL_MSG_DATAMOVE:		/* Only used in XFER mode */
12157 		ctl_datamove_remote(io);
12158 		break;
12159 	case CTL_MSG_DATAMOVE_DONE:	/* Only used in XFER mode */
12160 		ctl_datamove_done(io, false);
12161 		break;
12162 	case CTL_MSG_FAILOVER:
12163 		ctl_failover_lun(io);
12164 		ctl_free_io(io);
12165 		break;
12166 	default:
12167 		printf("%s: Invalid message type %d\n",
12168 		       __func__, io->io_hdr.msg_type);
12169 		ctl_free_io(io);
12170 		break;
12171 	}
12172 
12173 }
12174 
12175 /*
12176  * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12177  * there is no match.
12178  */
12179 static ctl_lun_error_pattern
12180 ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12181 {
12182 	const struct ctl_cmd_entry *entry;
12183 	ctl_lun_error_pattern filtered_pattern, pattern;
12184 
12185 	pattern = desc->error_pattern;
12186 
12187 	/*
12188 	 * XXX KDM we need more data passed into this function to match a
12189 	 * custom pattern, and we actually need to implement custom pattern
12190 	 * matching.
12191 	 */
12192 	if (pattern & CTL_LUN_PAT_CMD)
12193 		return (CTL_LUN_PAT_CMD);
12194 
12195 	if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12196 		return (CTL_LUN_PAT_ANY);
12197 
12198 	entry = ctl_get_cmd_entry(ctsio, NULL);
12199 
12200 	filtered_pattern = entry->pattern & pattern;
12201 
12202 	/*
12203 	 * If the user requested specific flags in the pattern (e.g.
12204 	 * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12205 	 * flags.
12206 	 *
12207 	 * If the user did not specify any flags, it doesn't matter whether
12208 	 * or not the command supports the flags.
12209 	 */
12210 	if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12211 	     (pattern & ~CTL_LUN_PAT_MASK))
12212 		return (CTL_LUN_PAT_NONE);
12213 
12214 	/*
12215 	 * If the user asked for a range check, see if the requested LBA
12216 	 * range overlaps with this command's LBA range.
12217 	 */
12218 	if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12219 		uint64_t lba1;
12220 		uint64_t len1;
12221 		ctl_action action;
12222 		int retval;
12223 
12224 		retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12225 		if (retval != 0)
12226 			return (CTL_LUN_PAT_NONE);
12227 
12228 		action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12229 					      desc->lba_range.len, FALSE);
12230 		/*
12231 		 * A "pass" means that the LBA ranges don't overlap, so
12232 		 * this doesn't match the user's range criteria.
12233 		 */
12234 		if (action == CTL_ACTION_PASS)
12235 			return (CTL_LUN_PAT_NONE);
12236 	}
12237 
12238 	return (filtered_pattern);
12239 }
12240 
12241 static void
12242 ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12243 {
12244 	struct ctl_error_desc *desc, *desc2;
12245 
12246 	mtx_assert(&lun->lun_lock, MA_OWNED);
12247 
12248 	STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12249 		ctl_lun_error_pattern pattern;
12250 		/*
12251 		 * Check to see whether this particular command matches
12252 		 * the pattern in the descriptor.
12253 		 */
12254 		pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12255 		if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12256 			continue;
12257 
12258 		switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12259 		case CTL_LUN_INJ_ABORTED:
12260 			ctl_set_aborted(&io->scsiio);
12261 			break;
12262 		case CTL_LUN_INJ_MEDIUM_ERR:
12263 			ctl_set_medium_error(&io->scsiio,
12264 			    (io->io_hdr.flags & CTL_FLAG_DATA_MASK) !=
12265 			     CTL_FLAG_DATA_OUT);
12266 			break;
12267 		case CTL_LUN_INJ_UA:
12268 			/* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12269 			 * OCCURRED */
12270 			ctl_set_ua(&io->scsiio, 0x29, 0x00);
12271 			break;
12272 		case CTL_LUN_INJ_CUSTOM:
12273 			/*
12274 			 * We're assuming the user knows what he is doing.
12275 			 * Just copy the sense information without doing
12276 			 * checks.
12277 			 */
12278 			bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12279 			      MIN(sizeof(desc->custom_sense),
12280 				  sizeof(io->scsiio.sense_data)));
12281 			io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12282 			io->scsiio.sense_len = SSD_FULL_SIZE;
12283 			io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12284 			break;
12285 		case CTL_LUN_INJ_NONE:
12286 		default:
12287 			/*
12288 			 * If this is an error injection type we don't know
12289 			 * about, clear the continuous flag (if it is set)
12290 			 * so it will get deleted below.
12291 			 */
12292 			desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12293 			break;
12294 		}
12295 		/*
12296 		 * By default, each error injection action is a one-shot
12297 		 */
12298 		if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12299 			continue;
12300 
12301 		STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12302 
12303 		free(desc, M_CTL);
12304 	}
12305 }
12306 
12307 #ifdef CTL_IO_DELAY
12308 static void
12309 ctl_datamove_timer_wakeup(void *arg)
12310 {
12311 	union ctl_io *io;
12312 
12313 	io = (union ctl_io *)arg;
12314 
12315 	ctl_datamove(io);
12316 }
12317 #endif /* CTL_IO_DELAY */
12318 
12319 static void
12320 ctl_datamove_done_process(union ctl_io *io)
12321 {
12322 #ifdef CTL_TIME_IO
12323 	struct bintime cur_bt;
12324 #endif
12325 
12326 	KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
12327 	    ("%s: unexpected I/O type %x", __func__, io->io_hdr.io_type));
12328 
12329 #ifdef CTL_TIME_IO
12330 	getbinuptime(&cur_bt);
12331 	bintime_sub(&cur_bt, &io->io_hdr.dma_start_bt);
12332 	bintime_add(&io->io_hdr.dma_bt, &cur_bt);
12333 #endif
12334 	io->io_hdr.num_dmas++;
12335 
12336 	if ((io->io_hdr.port_status != 0) &&
12337 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
12338 	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
12339 		ctl_set_internal_failure(&io->scsiio, /*sks_valid*/ 1,
12340 		    /*retry_count*/ io->io_hdr.port_status);
12341 	} else if (io->scsiio.kern_data_resid != 0 &&
12342 	    (io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT &&
12343 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
12344 	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
12345 		ctl_set_invalid_field_ciu(&io->scsiio);
12346 	} else if (ctl_debug & CTL_DEBUG_CDB_DATA)
12347 		ctl_data_print(io);
12348 }
12349 
12350 void
12351 ctl_datamove_done(union ctl_io *io, bool samethr)
12352 {
12353 
12354 	ctl_datamove_done_process(io);
12355 	io->scsiio.be_move_done(io, samethr);
12356 }
12357 
12358 void
12359 ctl_datamove(union ctl_io *io)
12360 {
12361 	void (*fe_datamove)(union ctl_io *io);
12362 
12363 	mtx_assert(&((struct ctl_softc *)CTL_SOFTC(io))->ctl_lock, MA_NOTOWNED);
12364 
12365 	CTL_DEBUG_PRINT(("ctl_datamove\n"));
12366 
12367 	/* No data transferred yet.  Frontend must update this when done. */
12368 	io->scsiio.kern_data_resid = io->scsiio.kern_data_len;
12369 
12370 #ifdef CTL_TIME_IO
12371 	getbinuptime(&io->io_hdr.dma_start_bt);
12372 #endif /* CTL_TIME_IO */
12373 
12374 #ifdef CTL_IO_DELAY
12375 	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12376 		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12377 	} else {
12378 		struct ctl_lun *lun;
12379 
12380 		lun = CTL_LUN(io);
12381 		if ((lun != NULL)
12382 		 && (lun->delay_info.datamove_delay > 0)) {
12383 			callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
12384 			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12385 			callout_reset(&io->io_hdr.delay_callout,
12386 				      lun->delay_info.datamove_delay * hz,
12387 				      ctl_datamove_timer_wakeup, io);
12388 			if (lun->delay_info.datamove_type ==
12389 			    CTL_DELAY_TYPE_ONESHOT)
12390 				lun->delay_info.datamove_delay = 0;
12391 			return;
12392 		}
12393 	}
12394 #endif
12395 
12396 	/*
12397 	 * This command has been aborted.  Set the port status, so we fail
12398 	 * the data move.
12399 	 */
12400 	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12401 		printf("ctl_datamove: tag 0x%jx on (%u:%u:%u) aborted\n",
12402 		       io->scsiio.tag_num, io->io_hdr.nexus.initid,
12403 		       io->io_hdr.nexus.targ_port,
12404 		       io->io_hdr.nexus.targ_lun);
12405 		io->io_hdr.port_status = 31337;
12406 		ctl_datamove_done_process(io);
12407 		io->scsiio.be_move_done(io, true);
12408 		return;
12409 	}
12410 
12411 	/* Don't confuse frontend with zero length data move. */
12412 	if (io->scsiio.kern_data_len == 0) {
12413 		ctl_datamove_done_process(io);
12414 		io->scsiio.be_move_done(io, true);
12415 		return;
12416 	}
12417 
12418 	fe_datamove = CTL_PORT(io)->fe_datamove;
12419 	fe_datamove(io);
12420 }
12421 
12422 static void
12423 ctl_send_datamove_done(union ctl_io *io, int have_lock)
12424 {
12425 	union ctl_ha_msg msg;
12426 #ifdef CTL_TIME_IO
12427 	struct bintime cur_bt;
12428 #endif
12429 
12430 	memset(&msg, 0, sizeof(msg));
12431 	msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12432 	msg.hdr.original_sc = io;
12433 	msg.hdr.serializing_sc = io->io_hdr.remote_io;
12434 	msg.hdr.nexus = io->io_hdr.nexus;
12435 	msg.hdr.status = io->io_hdr.status;
12436 	msg.scsi.kern_data_resid = io->scsiio.kern_data_resid;
12437 	msg.scsi.tag_num = io->scsiio.tag_num;
12438 	msg.scsi.tag_type = io->scsiio.tag_type;
12439 	msg.scsi.scsi_status = io->scsiio.scsi_status;
12440 	memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12441 	       io->scsiio.sense_len);
12442 	msg.scsi.sense_len = io->scsiio.sense_len;
12443 	msg.scsi.port_status = io->io_hdr.port_status;
12444 	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12445 	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12446 		ctl_failover_io(io, /*have_lock*/ have_lock);
12447 		return;
12448 	}
12449 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12450 	    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
12451 	    msg.scsi.sense_len, M_WAITOK);
12452 
12453 #ifdef CTL_TIME_IO
12454 	getbinuptime(&cur_bt);
12455 	bintime_sub(&cur_bt, &io->io_hdr.dma_start_bt);
12456 	bintime_add(&io->io_hdr.dma_bt, &cur_bt);
12457 #endif
12458 	io->io_hdr.num_dmas++;
12459 }
12460 
12461 /*
12462  * The DMA to the remote side is done, now we need to tell the other side
12463  * we're done so it can continue with its data movement.
12464  */
12465 static void
12466 ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12467 {
12468 	union ctl_io *io;
12469 	uint32_t i;
12470 
12471 	io = rq->context;
12472 
12473 	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12474 		printf("%s: ISC DMA write failed with error %d", __func__,
12475 		       rq->ret);
12476 		ctl_set_internal_failure(&io->scsiio,
12477 					 /*sks_valid*/ 1,
12478 					 /*retry_count*/ rq->ret);
12479 	}
12480 
12481 	ctl_dt_req_free(rq);
12482 
12483 	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12484 		free(CTL_LSGLT(io)[i].addr, M_CTL);
12485 	free(CTL_RSGL(io), M_CTL);
12486 	CTL_RSGL(io) = NULL;
12487 	CTL_LSGL(io) = NULL;
12488 
12489 	/*
12490 	 * The data is in local and remote memory, so now we need to send
12491 	 * status (good or back) back to the other side.
12492 	 */
12493 	ctl_send_datamove_done(io, /*have_lock*/ 0);
12494 }
12495 
12496 /*
12497  * We've moved the data from the host/controller into local memory.  Now we
12498  * need to push it over to the remote controller's memory.
12499  */
12500 static int
12501 ctl_datamove_remote_dm_write_cb(union ctl_io *io, bool samethr)
12502 {
12503 	int retval;
12504 
12505 	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
12506 					  ctl_datamove_remote_write_cb);
12507 	return (retval);
12508 }
12509 
12510 static void
12511 ctl_datamove_remote_write(union ctl_io *io)
12512 {
12513 	int retval;
12514 	void (*fe_datamove)(union ctl_io *io);
12515 
12516 	/*
12517 	 * - Get the data from the host/HBA into local memory.
12518 	 * - DMA memory from the local controller to the remote controller.
12519 	 * - Send status back to the remote controller.
12520 	 */
12521 
12522 	retval = ctl_datamove_remote_sgl_setup(io);
12523 	if (retval != 0)
12524 		return;
12525 
12526 	/* Switch the pointer over so the FETD knows what to do */
12527 	io->scsiio.kern_data_ptr = (uint8_t *)CTL_LSGL(io);
12528 
12529 	/*
12530 	 * Use a custom move done callback, since we need to send completion
12531 	 * back to the other controller, not to the backend on this side.
12532 	 */
12533 	io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
12534 
12535 	fe_datamove = CTL_PORT(io)->fe_datamove;
12536 	fe_datamove(io);
12537 }
12538 
12539 static int
12540 ctl_datamove_remote_dm_read_cb(union ctl_io *io, bool samethr)
12541 {
12542 	uint32_t i;
12543 
12544 	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12545 		free(CTL_LSGLT(io)[i].addr, M_CTL);
12546 	free(CTL_RSGL(io), M_CTL);
12547 	CTL_RSGL(io) = NULL;
12548 	CTL_LSGL(io) = NULL;
12549 
12550 	/*
12551 	 * The read is done, now we need to send status (good or bad) back
12552 	 * to the other side.
12553 	 */
12554 	ctl_send_datamove_done(io, /*have_lock*/ 0);
12555 
12556 	return (0);
12557 }
12558 
12559 static void
12560 ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
12561 {
12562 	union ctl_io *io;
12563 	void (*fe_datamove)(union ctl_io *io);
12564 
12565 	io = rq->context;
12566 
12567 	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12568 		printf("%s: ISC DMA read failed with error %d\n", __func__,
12569 		       rq->ret);
12570 		ctl_set_internal_failure(&io->scsiio,
12571 					 /*sks_valid*/ 1,
12572 					 /*retry_count*/ rq->ret);
12573 	}
12574 
12575 	ctl_dt_req_free(rq);
12576 
12577 	/* Switch the pointer over so the FETD knows what to do */
12578 	io->scsiio.kern_data_ptr = (uint8_t *)CTL_LSGL(io);
12579 
12580 	/*
12581 	 * Use a custom move done callback, since we need to send completion
12582 	 * back to the other controller, not to the backend on this side.
12583 	 */
12584 	io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
12585 
12586 	/* XXX KDM add checks like the ones in ctl_datamove? */
12587 
12588 	fe_datamove = CTL_PORT(io)->fe_datamove;
12589 	fe_datamove(io);
12590 }
12591 
12592 static int
12593 ctl_datamove_remote_sgl_setup(union ctl_io *io)
12594 {
12595 	struct ctl_sg_entry *local_sglist;
12596 	uint32_t len_to_go;
12597 	int retval;
12598 	int i;
12599 
12600 	retval = 0;
12601 	local_sglist = CTL_LSGL(io);
12602 	len_to_go = io->scsiio.kern_data_len;
12603 
12604 	/*
12605 	 * The difficult thing here is that the size of the various
12606 	 * S/G segments may be different than the size from the
12607 	 * remote controller.  That'll make it harder when DMAing
12608 	 * the data back to the other side.
12609 	 */
12610 	for (i = 0; len_to_go > 0; i++) {
12611 		local_sglist[i].len = MIN(len_to_go, CTL_HA_DATAMOVE_SEGMENT);
12612 		local_sglist[i].addr =
12613 		    malloc(local_sglist[i].len, M_CTL, M_WAITOK);
12614 
12615 		len_to_go -= local_sglist[i].len;
12616 	}
12617 	/*
12618 	 * Reset the number of S/G entries accordingly.  The original
12619 	 * number of S/G entries is available in rem_sg_entries.
12620 	 */
12621 	io->scsiio.kern_sg_entries = i;
12622 
12623 	return (retval);
12624 }
12625 
12626 static int
12627 ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
12628 			 ctl_ha_dt_cb callback)
12629 {
12630 	struct ctl_ha_dt_req *rq;
12631 	struct ctl_sg_entry *remote_sglist, *local_sglist;
12632 	uint32_t local_used, remote_used, total_used;
12633 	int i, j, isc_ret;
12634 
12635 	rq = ctl_dt_req_alloc();
12636 
12637 	/*
12638 	 * If we failed to allocate the request, and if the DMA didn't fail
12639 	 * anyway, set busy status.  This is just a resource allocation
12640 	 * failure.
12641 	 */
12642 	if ((rq == NULL)
12643 	 && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12644 	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS))
12645 		ctl_set_busy(&io->scsiio);
12646 
12647 	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12648 	    (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) {
12649 		if (rq != NULL)
12650 			ctl_dt_req_free(rq);
12651 
12652 		/*
12653 		 * The data move failed.  We need to return status back
12654 		 * to the other controller.  No point in trying to DMA
12655 		 * data to the remote controller.
12656 		 */
12657 
12658 		ctl_send_datamove_done(io, /*have_lock*/ 0);
12659 
12660 		return (1);
12661 	}
12662 
12663 	local_sglist = CTL_LSGL(io);
12664 	remote_sglist = CTL_RSGL(io);
12665 	local_used = 0;
12666 	remote_used = 0;
12667 	total_used = 0;
12668 
12669 	/*
12670 	 * Pull/push the data over the wire from/to the other controller.
12671 	 * This takes into account the possibility that the local and
12672 	 * remote sglists may not be identical in terms of the size of
12673 	 * the elements and the number of elements.
12674 	 *
12675 	 * One fundamental assumption here is that the length allocated for
12676 	 * both the local and remote sglists is identical.  Otherwise, we've
12677 	 * essentially got a coding error of some sort.
12678 	 */
12679 	isc_ret = CTL_HA_STATUS_SUCCESS;
12680 	for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
12681 		uint32_t cur_len;
12682 		uint8_t *tmp_ptr;
12683 
12684 		rq->command = command;
12685 		rq->context = io;
12686 
12687 		/*
12688 		 * Both pointers should be aligned.  But it is possible
12689 		 * that the allocation length is not.  They should both
12690 		 * also have enough slack left over at the end, though,
12691 		 * to round up to the next 8 byte boundary.
12692 		 */
12693 		cur_len = MIN(local_sglist[i].len - local_used,
12694 			      remote_sglist[j].len - remote_used);
12695 		rq->size = cur_len;
12696 
12697 		tmp_ptr = (uint8_t *)local_sglist[i].addr;
12698 		tmp_ptr += local_used;
12699 
12700 #if 0
12701 		/* Use physical addresses when talking to ISC hardware */
12702 		if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
12703 			/* XXX KDM use busdma */
12704 			rq->local = vtophys(tmp_ptr);
12705 		} else
12706 			rq->local = tmp_ptr;
12707 #else
12708 		KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
12709 		    ("HA does not support BUS_ADDR"));
12710 		rq->local = tmp_ptr;
12711 #endif
12712 
12713 		tmp_ptr = (uint8_t *)remote_sglist[j].addr;
12714 		tmp_ptr += remote_used;
12715 		rq->remote = tmp_ptr;
12716 
12717 		rq->callback = NULL;
12718 
12719 		local_used += cur_len;
12720 		if (local_used >= local_sglist[i].len) {
12721 			i++;
12722 			local_used = 0;
12723 		}
12724 
12725 		remote_used += cur_len;
12726 		if (remote_used >= remote_sglist[j].len) {
12727 			j++;
12728 			remote_used = 0;
12729 		}
12730 		total_used += cur_len;
12731 
12732 		if (total_used >= io->scsiio.kern_data_len)
12733 			rq->callback = callback;
12734 
12735 		isc_ret = ctl_dt_single(rq);
12736 		if (isc_ret > CTL_HA_STATUS_SUCCESS)
12737 			break;
12738 	}
12739 	if (isc_ret != CTL_HA_STATUS_WAIT) {
12740 		rq->ret = isc_ret;
12741 		callback(rq);
12742 	}
12743 
12744 	return (0);
12745 }
12746 
12747 static void
12748 ctl_datamove_remote_read(union ctl_io *io)
12749 {
12750 	int retval;
12751 	uint32_t i;
12752 
12753 	/*
12754 	 * This will send an error to the other controller in the case of a
12755 	 * failure.
12756 	 */
12757 	retval = ctl_datamove_remote_sgl_setup(io);
12758 	if (retval != 0)
12759 		return;
12760 
12761 	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
12762 					  ctl_datamove_remote_read_cb);
12763 	if (retval != 0) {
12764 		/*
12765 		 * Make sure we free memory if there was an error..  The
12766 		 * ctl_datamove_remote_xfer() function will send the
12767 		 * datamove done message, or call the callback with an
12768 		 * error if there is a problem.
12769 		 */
12770 		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12771 			free(CTL_LSGLT(io)[i].addr, M_CTL);
12772 		free(CTL_RSGL(io), M_CTL);
12773 		CTL_RSGL(io) = NULL;
12774 		CTL_LSGL(io) = NULL;
12775 	}
12776 }
12777 
12778 /*
12779  * Process a datamove request from the other controller.  This is used for
12780  * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
12781  * first.  Once that is complete, the data gets DMAed into the remote
12782  * controller's memory.  For reads, we DMA from the remote controller's
12783  * memory into our memory first, and then move it out to the FETD.
12784  */
12785 static void
12786 ctl_datamove_remote(union ctl_io *io)
12787 {
12788 
12789 	mtx_assert(&((struct ctl_softc *)CTL_SOFTC(io))->ctl_lock, MA_NOTOWNED);
12790 
12791 	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12792 		ctl_failover_io(io, /*have_lock*/ 0);
12793 		return;
12794 	}
12795 
12796 	/*
12797 	 * Note that we look for an aborted I/O here, but don't do some of
12798 	 * the other checks that ctl_datamove() normally does.
12799 	 * We don't need to run the datamove delay code, since that should
12800 	 * have been done if need be on the other controller.
12801 	 */
12802 	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12803 		printf("%s: tag 0x%jx on (%u:%u:%u) aborted\n", __func__,
12804 		       io->scsiio.tag_num, io->io_hdr.nexus.initid,
12805 		       io->io_hdr.nexus.targ_port,
12806 		       io->io_hdr.nexus.targ_lun);
12807 		io->io_hdr.port_status = 31338;
12808 		ctl_send_datamove_done(io, /*have_lock*/ 0);
12809 		return;
12810 	}
12811 
12812 	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT)
12813 		ctl_datamove_remote_write(io);
12814 	else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
12815 		ctl_datamove_remote_read(io);
12816 	else {
12817 		io->io_hdr.port_status = 31339;
12818 		ctl_send_datamove_done(io, /*have_lock*/ 0);
12819 	}
12820 }
12821 
12822 static void
12823 ctl_process_done(union ctl_io *io)
12824 {
12825 	struct ctl_softc *softc = CTL_SOFTC(io);
12826 	struct ctl_port *port = CTL_PORT(io);
12827 	struct ctl_lun *lun = CTL_LUN(io);
12828 	void (*fe_done)(union ctl_io *io);
12829 	union ctl_ha_msg msg;
12830 
12831 	CTL_DEBUG_PRINT(("ctl_process_done\n"));
12832 	fe_done = port->fe_done;
12833 
12834 #ifdef CTL_TIME_IO
12835 	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12836 		char str[256];
12837 		char path_str[64];
12838 		struct sbuf sb;
12839 
12840 		ctl_scsi_path_string(io, path_str, sizeof(path_str));
12841 		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12842 
12843 		ctl_io_sbuf(io, &sb);
12844 		sbuf_cat(&sb, path_str);
12845 		sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
12846 			    (intmax_t)time_uptime - io->io_hdr.start_time);
12847 		sbuf_finish(&sb);
12848 		printf("%s", sbuf_data(&sb));
12849 	}
12850 #endif /* CTL_TIME_IO */
12851 
12852 	switch (io->io_hdr.io_type) {
12853 	case CTL_IO_SCSI:
12854 		break;
12855 	case CTL_IO_TASK:
12856 		if (ctl_debug & CTL_DEBUG_INFO)
12857 			ctl_io_error_print(io, NULL);
12858 		fe_done(io);
12859 		return;
12860 	default:
12861 		panic("%s: Invalid CTL I/O type %d\n",
12862 		    __func__, io->io_hdr.io_type);
12863 	}
12864 
12865 	if (lun == NULL) {
12866 		CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
12867 				 io->io_hdr.nexus.targ_mapped_lun));
12868 		goto bailout;
12869 	}
12870 
12871 	mtx_lock(&lun->lun_lock);
12872 
12873 	/*
12874 	 * Check to see if we have any informational exception and status
12875 	 * of this command can be modified to report it in form of either
12876 	 * RECOVERED ERROR or NO SENSE, depending on MRIE mode page field.
12877 	 */
12878 	if (lun->ie_reported == 0 && lun->ie_asc != 0 &&
12879 	    io->io_hdr.status == CTL_SUCCESS &&
12880 	    (io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0) {
12881 		uint8_t mrie = lun->MODE_IE.mrie;
12882 		uint8_t per = ((lun->MODE_RWER.byte3 & SMS_RWER_PER) ||
12883 		    (lun->MODE_VER.byte3 & SMS_VER_PER));
12884 		if (((mrie == SIEP_MRIE_REC_COND && per) ||
12885 		     mrie == SIEP_MRIE_REC_UNCOND ||
12886 		     mrie == SIEP_MRIE_NO_SENSE) &&
12887 		    (ctl_get_cmd_entry(&io->scsiio, NULL)->flags &
12888 		     CTL_CMD_FLAG_NO_SENSE) == 0) {
12889 			ctl_set_sense(&io->scsiio,
12890 			      /*current_error*/ 1,
12891 			      /*sense_key*/ (mrie == SIEP_MRIE_NO_SENSE) ?
12892 			        SSD_KEY_NO_SENSE : SSD_KEY_RECOVERED_ERROR,
12893 			      /*asc*/ lun->ie_asc,
12894 			      /*ascq*/ lun->ie_ascq,
12895 			      SSD_ELEM_NONE);
12896 			lun->ie_reported = 1;
12897 		}
12898 	} else if (lun->ie_reported < 0)
12899 		lun->ie_reported = 0;
12900 
12901 	/*
12902 	 * Check to see if we have any errors to inject here.  We only
12903 	 * inject errors for commands that don't already have errors set.
12904 	 */
12905 	if (!STAILQ_EMPTY(&lun->error_list) &&
12906 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS) &&
12907 	    ((io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0))
12908 		ctl_inject_error(lun, io);
12909 
12910 	/*
12911 	 * XXX KDM how do we treat commands that aren't completed
12912 	 * successfully?
12913 	 *
12914 	 * XXX KDM should we also track I/O latency?
12915 	 */
12916 	if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
12917 	    io->io_hdr.io_type == CTL_IO_SCSI) {
12918 		int type;
12919 #ifdef CTL_TIME_IO
12920 		struct bintime bt;
12921 
12922 		getbinuptime(&bt);
12923 		bintime_sub(&bt, &io->io_hdr.start_bt);
12924 #endif
12925 		if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
12926 		    CTL_FLAG_DATA_IN)
12927 			type = CTL_STATS_READ;
12928 		else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
12929 		    CTL_FLAG_DATA_OUT)
12930 			type = CTL_STATS_WRITE;
12931 		else
12932 			type = CTL_STATS_NO_IO;
12933 
12934 		lun->stats.bytes[type] += io->scsiio.kern_total_len;
12935 		lun->stats.operations[type] ++;
12936 		lun->stats.dmas[type] += io->io_hdr.num_dmas;
12937 #ifdef CTL_TIME_IO
12938 		bintime_add(&lun->stats.dma_time[type], &io->io_hdr.dma_bt);
12939 		bintime_add(&lun->stats.time[type], &bt);
12940 #endif
12941 
12942 		mtx_lock(&port->port_lock);
12943 		port->stats.bytes[type] += io->scsiio.kern_total_len;
12944 		port->stats.operations[type] ++;
12945 		port->stats.dmas[type] += io->io_hdr.num_dmas;
12946 #ifdef CTL_TIME_IO
12947 		bintime_add(&port->stats.dma_time[type], &io->io_hdr.dma_bt);
12948 		bintime_add(&port->stats.time[type], &bt);
12949 #endif
12950 		mtx_unlock(&port->port_lock);
12951 	}
12952 
12953 	/*
12954 	 * Run through the blocked queue of this I/O and see if anything
12955 	 * can be unblocked, now that this I/O is done and will be removed.
12956 	 * We need to do it before removal to have OOA position to start.
12957 	 */
12958 	ctl_try_unblock_others(lun, io, TRUE);
12959 
12960 	/*
12961 	 * Remove this from the OOA queue.
12962 	 */
12963 	LIST_REMOVE(&io->io_hdr, ooa_links);
12964 #ifdef CTL_TIME_IO
12965 	if (LIST_EMPTY(&lun->ooa_queue))
12966 		lun->last_busy = getsbinuptime();
12967 #endif
12968 
12969 	/*
12970 	 * If the LUN has been invalidated, free it if there is nothing
12971 	 * left on its OOA queue.
12972 	 */
12973 	if ((lun->flags & CTL_LUN_INVALID)
12974 	 && LIST_EMPTY(&lun->ooa_queue)) {
12975 		mtx_unlock(&lun->lun_lock);
12976 		ctl_free_lun(lun);
12977 	} else
12978 		mtx_unlock(&lun->lun_lock);
12979 
12980 bailout:
12981 
12982 	/*
12983 	 * If this command has been aborted, make sure we set the status
12984 	 * properly.  The FETD is responsible for freeing the I/O and doing
12985 	 * whatever it needs to do to clean up its state.
12986 	 */
12987 	if (io->io_hdr.flags & CTL_FLAG_ABORT)
12988 		ctl_set_task_aborted(&io->scsiio);
12989 
12990 	/*
12991 	 * If enabled, print command error status.
12992 	 */
12993 	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS &&
12994 	    (ctl_debug & CTL_DEBUG_INFO) != 0)
12995 		ctl_io_error_print(io, NULL);
12996 
12997 	/*
12998 	 * Tell the FETD or the other shelf controller we're done with this
12999 	 * command.  Note that only SCSI commands get to this point.  Task
13000 	 * management commands are completed above.
13001 	 */
13002 	if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
13003 	    (io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)) {
13004 		memset(&msg, 0, sizeof(msg));
13005 		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13006 		msg.hdr.serializing_sc = io->io_hdr.remote_io;
13007 		msg.hdr.nexus = io->io_hdr.nexus;
13008 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13009 		    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data),
13010 		    M_WAITOK);
13011 	}
13012 
13013 	fe_done(io);
13014 }
13015 
13016 /*
13017  * Front end should call this if it doesn't do autosense.  When the request
13018  * sense comes back in from the initiator, we'll dequeue this and send it.
13019  */
13020 int
13021 ctl_queue_sense(union ctl_io *io)
13022 {
13023 	struct ctl_softc *softc = CTL_SOFTC(io);
13024 	struct ctl_port *port = CTL_PORT(io);
13025 	struct ctl_lun *lun;
13026 	struct scsi_sense_data *ps;
13027 	uint32_t initidx, p, targ_lun;
13028 
13029 	CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13030 
13031 	targ_lun = ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13032 
13033 	/*
13034 	 * LUN lookup will likely move to the ctl_work_thread() once we
13035 	 * have our new queueing infrastructure (that doesn't put things on
13036 	 * a per-LUN queue initially).  That is so that we can handle
13037 	 * things like an INQUIRY to a LUN that we don't have enabled.  We
13038 	 * can't deal with that right now.
13039 	 * If we don't have a LUN for this, just toss the sense information.
13040 	 */
13041 	mtx_lock(&softc->ctl_lock);
13042 	if (targ_lun >= ctl_max_luns ||
13043 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
13044 		mtx_unlock(&softc->ctl_lock);
13045 		goto bailout;
13046 	}
13047 	mtx_lock(&lun->lun_lock);
13048 	mtx_unlock(&softc->ctl_lock);
13049 
13050 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
13051 	p = initidx / CTL_MAX_INIT_PER_PORT;
13052 	if (lun->pending_sense[p] == NULL) {
13053 		lun->pending_sense[p] = malloc(sizeof(*ps) * CTL_MAX_INIT_PER_PORT,
13054 		    M_CTL, M_NOWAIT | M_ZERO);
13055 	}
13056 	if ((ps = lun->pending_sense[p]) != NULL) {
13057 		ps += initidx % CTL_MAX_INIT_PER_PORT;
13058 		memset(ps, 0, sizeof(*ps));
13059 		memcpy(ps, &io->scsiio.sense_data, io->scsiio.sense_len);
13060 	}
13061 	mtx_unlock(&lun->lun_lock);
13062 
13063 bailout:
13064 	ctl_free_io(io);
13065 	return (CTL_RETVAL_COMPLETE);
13066 }
13067 
13068 /*
13069  * Primary command inlet from frontend ports.  All SCSI and task I/O
13070  * requests must go through this function.
13071  */
13072 int
13073 ctl_queue(union ctl_io *io)
13074 {
13075 	struct ctl_port *port = CTL_PORT(io);
13076 
13077 	CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13078 
13079 #ifdef CTL_TIME_IO
13080 	io->io_hdr.start_time = time_uptime;
13081 	getbinuptime(&io->io_hdr.start_bt);
13082 #endif /* CTL_TIME_IO */
13083 
13084 	/* Map FE-specific LUN ID into global one. */
13085 	io->io_hdr.nexus.targ_mapped_lun =
13086 	    ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13087 
13088 	switch (io->io_hdr.io_type) {
13089 	case CTL_IO_SCSI:
13090 	case CTL_IO_TASK:
13091 		if (ctl_debug & CTL_DEBUG_CDB)
13092 			ctl_io_print(io);
13093 		ctl_enqueue_incoming(io);
13094 		break;
13095 	default:
13096 		printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13097 		return (EINVAL);
13098 	}
13099 
13100 	return (CTL_RETVAL_COMPLETE);
13101 }
13102 
13103 int
13104 ctl_run(union ctl_io *io)
13105 {
13106 	struct ctl_port *port = CTL_PORT(io);
13107 
13108 	CTL_DEBUG_PRINT(("ctl_run cdb[0]=%02X\n", io->scsiio.cdb[0]));
13109 
13110 #ifdef CTL_TIME_IO
13111 	io->io_hdr.start_time = time_uptime;
13112 	getbinuptime(&io->io_hdr.start_bt);
13113 #endif /* CTL_TIME_IO */
13114 
13115 	/* Map FE-specific LUN ID into global one. */
13116 	io->io_hdr.nexus.targ_mapped_lun =
13117 	    ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13118 
13119 	switch (io->io_hdr.io_type) {
13120 	case CTL_IO_SCSI:
13121 		if (ctl_debug & CTL_DEBUG_CDB)
13122 			ctl_io_print(io);
13123 		ctl_scsiio_precheck(&io->scsiio);
13124 		break;
13125 	case CTL_IO_TASK:
13126 		if (ctl_debug & CTL_DEBUG_CDB)
13127 			ctl_io_print(io);
13128 		ctl_run_task(io);
13129 		break;
13130 	default:
13131 		printf("ctl_run: unknown I/O type %d\n", io->io_hdr.io_type);
13132 		return (EINVAL);
13133 	}
13134 
13135 	return (CTL_RETVAL_COMPLETE);
13136 }
13137 
13138 #ifdef CTL_IO_DELAY
13139 static void
13140 ctl_done_timer_wakeup(void *arg)
13141 {
13142 	union ctl_io *io;
13143 
13144 	io = (union ctl_io *)arg;
13145 	ctl_done(io);
13146 }
13147 #endif /* CTL_IO_DELAY */
13148 
13149 void
13150 ctl_serseq_done(union ctl_io *io)
13151 {
13152 	struct ctl_lun *lun = CTL_LUN(io);
13153 
13154 	/* This is racy, but should not be a problem. */
13155 	if (!TAILQ_EMPTY(&io->io_hdr.blocked_queue)) {
13156 		mtx_lock(&lun->lun_lock);
13157 		io->io_hdr.flags |= CTL_FLAG_SERSEQ_DONE;
13158 		ctl_try_unblock_others(lun, io, FALSE);
13159 		mtx_unlock(&lun->lun_lock);
13160 	} else
13161 		io->io_hdr.flags |= CTL_FLAG_SERSEQ_DONE;
13162 }
13163 
13164 void
13165 ctl_done(union ctl_io *io)
13166 {
13167 
13168 	/*
13169 	 * Enable this to catch duplicate completion issues.
13170 	 */
13171 #if 0
13172 	if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13173 		printf("%s: type %d msg %d cdb %x iptl: "
13174 		       "%u:%u:%u tag 0x%04x "
13175 		       "flag %#x status %x\n",
13176 			__func__,
13177 			io->io_hdr.io_type,
13178 			io->io_hdr.msg_type,
13179 			io->scsiio.cdb[0],
13180 			io->io_hdr.nexus.initid,
13181 			io->io_hdr.nexus.targ_port,
13182 			io->io_hdr.nexus.targ_lun,
13183 			(io->io_hdr.io_type ==
13184 			CTL_IO_TASK) ?
13185 			io->taskio.tag_num :
13186 			io->scsiio.tag_num,
13187 		        io->io_hdr.flags,
13188 			io->io_hdr.status);
13189 	} else
13190 		io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13191 #endif
13192 
13193 	/*
13194 	 * This is an internal copy of an I/O, and should not go through
13195 	 * the normal done processing logic.
13196 	 */
13197 	if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13198 		return;
13199 
13200 #ifdef CTL_IO_DELAY
13201 	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13202 		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13203 	} else {
13204 		struct ctl_lun *lun = CTL_LUN(io);
13205 
13206 		if ((lun != NULL)
13207 		 && (lun->delay_info.done_delay > 0)) {
13208 			callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
13209 			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
13210 			callout_reset(&io->io_hdr.delay_callout,
13211 				      lun->delay_info.done_delay * hz,
13212 				      ctl_done_timer_wakeup, io);
13213 			if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
13214 				lun->delay_info.done_delay = 0;
13215 			return;
13216 		}
13217 	}
13218 #endif /* CTL_IO_DELAY */
13219 
13220 	ctl_enqueue_done(io);
13221 }
13222 
13223 static void
13224 ctl_work_thread(void *arg)
13225 {
13226 	struct ctl_thread *thr = (struct ctl_thread *)arg;
13227 	struct ctl_softc *softc = thr->ctl_softc;
13228 	union ctl_io *io;
13229 	int retval;
13230 
13231 	CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
13232 	thread_lock(curthread);
13233 	sched_prio(curthread, PUSER - 1);
13234 	thread_unlock(curthread);
13235 
13236 	while (!softc->shutdown) {
13237 		/*
13238 		 * We handle the queues in this order:
13239 		 * - ISC
13240 		 * - done queue (to free up resources, unblock other commands)
13241 		 * - incoming queue
13242 		 * - RtR queue
13243 		 *
13244 		 * If those queues are empty, we break out of the loop and
13245 		 * go to sleep.
13246 		 */
13247 		mtx_lock(&thr->queue_lock);
13248 		io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
13249 		if (io != NULL) {
13250 			STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
13251 			mtx_unlock(&thr->queue_lock);
13252 			ctl_handle_isc(io);
13253 			continue;
13254 		}
13255 		io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
13256 		if (io != NULL) {
13257 			STAILQ_REMOVE_HEAD(&thr->done_queue, links);
13258 			/* clear any blocked commands, call fe_done */
13259 			mtx_unlock(&thr->queue_lock);
13260 			ctl_process_done(io);
13261 			continue;
13262 		}
13263 		io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
13264 		if (io != NULL) {
13265 			STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
13266 			mtx_unlock(&thr->queue_lock);
13267 			if (io->io_hdr.io_type == CTL_IO_TASK)
13268 				ctl_run_task(io);
13269 			else
13270 				ctl_scsiio_precheck(&io->scsiio);
13271 			continue;
13272 		}
13273 		io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
13274 		if (io != NULL) {
13275 			STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
13276 			mtx_unlock(&thr->queue_lock);
13277 			retval = ctl_scsiio(&io->scsiio);
13278 			if (retval != CTL_RETVAL_COMPLETE)
13279 				CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
13280 			continue;
13281 		}
13282 
13283 		/* Sleep until we have something to do. */
13284 		mtx_sleep(thr, &thr->queue_lock, PDROP, "-", 0);
13285 	}
13286 	thr->thread = NULL;
13287 	kthread_exit();
13288 }
13289 
13290 static void
13291 ctl_thresh_thread(void *arg)
13292 {
13293 	struct ctl_softc *softc = (struct ctl_softc *)arg;
13294 	struct ctl_lun *lun;
13295 	struct ctl_logical_block_provisioning_page *page;
13296 	const char *attr;
13297 	union ctl_ha_msg msg;
13298 	uint64_t thres, val;
13299 	int i, e, set;
13300 
13301 	CTL_DEBUG_PRINT(("ctl_thresh_thread starting\n"));
13302 	thread_lock(curthread);
13303 	sched_prio(curthread, PUSER - 1);
13304 	thread_unlock(curthread);
13305 
13306 	while (!softc->shutdown) {
13307 		mtx_lock(&softc->ctl_lock);
13308 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
13309 			if ((lun->flags & CTL_LUN_DISABLED) ||
13310 			    (lun->flags & CTL_LUN_NO_MEDIA) ||
13311 			    lun->backend->lun_attr == NULL)
13312 				continue;
13313 			if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
13314 			    softc->ha_mode == CTL_HA_MODE_XFER)
13315 				continue;
13316 			if ((lun->MODE_RWER.byte8 & SMS_RWER_LBPERE) == 0)
13317 				continue;
13318 			e = 0;
13319 			page = &lun->MODE_LBP;
13320 			for (i = 0; i < CTL_NUM_LBP_THRESH; i++) {
13321 				if ((page->descr[i].flags & SLBPPD_ENABLED) == 0)
13322 					continue;
13323 				thres = scsi_4btoul(page->descr[i].count);
13324 				thres <<= CTL_LBP_EXPONENT;
13325 				switch (page->descr[i].resource) {
13326 				case 0x01:
13327 					attr = "blocksavail";
13328 					break;
13329 				case 0x02:
13330 					attr = "blocksused";
13331 					break;
13332 				case 0xf1:
13333 					attr = "poolblocksavail";
13334 					break;
13335 				case 0xf2:
13336 					attr = "poolblocksused";
13337 					break;
13338 				default:
13339 					continue;
13340 				}
13341 				mtx_unlock(&softc->ctl_lock); // XXX
13342 				val = lun->backend->lun_attr(lun->be_lun, attr);
13343 				mtx_lock(&softc->ctl_lock);
13344 				if (val == UINT64_MAX)
13345 					continue;
13346 				if ((page->descr[i].flags & SLBPPD_ARMING_MASK)
13347 				    == SLBPPD_ARMING_INC)
13348 					e = (val >= thres);
13349 				else
13350 					e = (val <= thres);
13351 				if (e)
13352 					break;
13353 			}
13354 			mtx_lock(&lun->lun_lock);
13355 			if (e) {
13356 				scsi_u64to8b((uint8_t *)&page->descr[i] -
13357 				    (uint8_t *)page, lun->ua_tpt_info);
13358 				if (lun->lasttpt == 0 ||
13359 				    time_uptime - lun->lasttpt >= CTL_LBP_UA_PERIOD) {
13360 					lun->lasttpt = time_uptime;
13361 					ctl_est_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13362 					set = 1;
13363 				} else
13364 					set = 0;
13365 			} else {
13366 				lun->lasttpt = 0;
13367 				ctl_clr_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13368 				set = -1;
13369 			}
13370 			mtx_unlock(&lun->lun_lock);
13371 			if (set != 0 &&
13372 			    lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
13373 				/* Send msg to other side. */
13374 				bzero(&msg.ua, sizeof(msg.ua));
13375 				msg.hdr.msg_type = CTL_MSG_UA;
13376 				msg.hdr.nexus.initid = -1;
13377 				msg.hdr.nexus.targ_port = -1;
13378 				msg.hdr.nexus.targ_lun = lun->lun;
13379 				msg.hdr.nexus.targ_mapped_lun = lun->lun;
13380 				msg.ua.ua_all = 1;
13381 				msg.ua.ua_set = (set > 0);
13382 				msg.ua.ua_type = CTL_UA_THIN_PROV_THRES;
13383 				memcpy(msg.ua.ua_info, lun->ua_tpt_info, 8);
13384 				mtx_unlock(&softc->ctl_lock); // XXX
13385 				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13386 				    sizeof(msg.ua), M_WAITOK);
13387 				mtx_lock(&softc->ctl_lock);
13388 			}
13389 		}
13390 		mtx_sleep(&softc->thresh_thread, &softc->ctl_lock,
13391 		    PDROP, "-", CTL_LBP_PERIOD * hz);
13392 	}
13393 	softc->thresh_thread = NULL;
13394 	kthread_exit();
13395 }
13396 
13397 static void
13398 ctl_enqueue_incoming(union ctl_io *io)
13399 {
13400 	struct ctl_softc *softc = CTL_SOFTC(io);
13401 	struct ctl_thread *thr;
13402 	u_int idx;
13403 
13404 	idx = (io->io_hdr.nexus.targ_port * 127 +
13405 	       io->io_hdr.nexus.initid) % worker_threads;
13406 	thr = &softc->threads[idx];
13407 	mtx_lock(&thr->queue_lock);
13408 	STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
13409 	mtx_unlock(&thr->queue_lock);
13410 	wakeup(thr);
13411 }
13412 
13413 static void
13414 ctl_enqueue_rtr(union ctl_io *io)
13415 {
13416 	struct ctl_softc *softc = CTL_SOFTC(io);
13417 	struct ctl_thread *thr;
13418 
13419 	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13420 	mtx_lock(&thr->queue_lock);
13421 	STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
13422 	mtx_unlock(&thr->queue_lock);
13423 	wakeup(thr);
13424 }
13425 
13426 static void
13427 ctl_enqueue_done(union ctl_io *io)
13428 {
13429 	struct ctl_softc *softc = CTL_SOFTC(io);
13430 	struct ctl_thread *thr;
13431 
13432 	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13433 	mtx_lock(&thr->queue_lock);
13434 	STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
13435 	mtx_unlock(&thr->queue_lock);
13436 	wakeup(thr);
13437 }
13438 
13439 static void
13440 ctl_enqueue_isc(union ctl_io *io)
13441 {
13442 	struct ctl_softc *softc = CTL_SOFTC(io);
13443 	struct ctl_thread *thr;
13444 
13445 	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13446 	mtx_lock(&thr->queue_lock);
13447 	STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
13448 	mtx_unlock(&thr->queue_lock);
13449 	wakeup(thr);
13450 }
13451 
13452 /*
13453  *  vim: ts=8
13454  */
13455