xref: /freebsd/sys/cam/ctl/ctl.c (revision 7899f917b1c0ea178f1d2be0cfb452086d079d23)
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_nvme_all.h>
87 #include <cam/ctl/ctl_scsi_all.h>
88 #include <cam/ctl/ctl_error.h>
89 
90 struct ctl_softc *control_softc = NULL;
91 
92 /*
93  * Template mode pages.
94  */
95 
96 /*
97  * Note that these are default values only.  The actual values will be
98  * filled in when the user does a mode sense.
99  */
100 const static struct scsi_da_rw_recovery_page rw_er_page_default = {
101 	/*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
102 	/*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
103 	/*byte3*/SMS_RWER_AWRE|SMS_RWER_ARRE,
104 	/*read_retry_count*/0,
105 	/*correction_span*/0,
106 	/*head_offset_count*/0,
107 	/*data_strobe_offset_cnt*/0,
108 	/*byte8*/SMS_RWER_LBPERE,
109 	/*write_retry_count*/0,
110 	/*reserved2*/0,
111 	/*recovery_time_limit*/{0, 0},
112 };
113 
114 const static struct scsi_da_rw_recovery_page rw_er_page_changeable = {
115 	/*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
116 	/*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
117 	/*byte3*/SMS_RWER_PER,
118 	/*read_retry_count*/0,
119 	/*correction_span*/0,
120 	/*head_offset_count*/0,
121 	/*data_strobe_offset_cnt*/0,
122 	/*byte8*/SMS_RWER_LBPERE,
123 	/*write_retry_count*/0,
124 	/*reserved2*/0,
125 	/*recovery_time_limit*/{0, 0},
126 };
127 
128 const static struct scsi_da_verify_recovery_page verify_er_page_default = {
129 	/*page_code*/SMS_VERIFY_ERROR_RECOVERY_PAGE,
130 	/*page_length*/sizeof(struct scsi_da_verify_recovery_page) - 2,
131 	/*byte3*/0,
132 	/*read_retry_count*/0,
133 	/*reserved*/{ 0, 0, 0, 0, 0, 0 },
134 	/*recovery_time_limit*/{0, 0},
135 };
136 
137 const static struct scsi_da_verify_recovery_page verify_er_page_changeable = {
138 	/*page_code*/SMS_VERIFY_ERROR_RECOVERY_PAGE,
139 	/*page_length*/sizeof(struct scsi_da_verify_recovery_page) - 2,
140 	/*byte3*/SMS_VER_PER,
141 	/*read_retry_count*/0,
142 	/*reserved*/{ 0, 0, 0, 0, 0, 0 },
143 	/*recovery_time_limit*/{0, 0},
144 };
145 
146 const static struct scsi_caching_page caching_page_default = {
147 	/*page_code*/SMS_CACHING_PAGE,
148 	/*page_length*/sizeof(struct scsi_caching_page) - 2,
149 	/*flags1*/ SCP_DISC | SCP_WCE,
150 	/*ret_priority*/ 0,
151 	/*disable_pf_transfer_len*/ {0xff, 0xff},
152 	/*min_prefetch*/ {0, 0},
153 	/*max_prefetch*/ {0xff, 0xff},
154 	/*max_pf_ceiling*/ {0xff, 0xff},
155 	/*flags2*/ 0,
156 	/*cache_segments*/ 0,
157 	/*cache_seg_size*/ {0, 0},
158 	/*reserved*/ 0,
159 	/*non_cache_seg_size*/ {0, 0, 0}
160 };
161 
162 const static struct scsi_caching_page caching_page_changeable = {
163 	/*page_code*/SMS_CACHING_PAGE,
164 	/*page_length*/sizeof(struct scsi_caching_page) - 2,
165 	/*flags1*/ SCP_WCE | SCP_RCD,
166 	/*ret_priority*/ 0,
167 	/*disable_pf_transfer_len*/ {0, 0},
168 	/*min_prefetch*/ {0, 0},
169 	/*max_prefetch*/ {0, 0},
170 	/*max_pf_ceiling*/ {0, 0},
171 	/*flags2*/ 0,
172 	/*cache_segments*/ 0,
173 	/*cache_seg_size*/ {0, 0},
174 	/*reserved*/ 0,
175 	/*non_cache_seg_size*/ {0, 0, 0}
176 };
177 
178 const static struct scsi_control_page control_page_default = {
179 	/*page_code*/SMS_CONTROL_MODE_PAGE,
180 	/*page_length*/sizeof(struct scsi_control_page) - 2,
181 	/*rlec*/0,
182 	/*queue_flags*/SCP_QUEUE_ALG_RESTRICTED,
183 	/*eca_and_aen*/0,
184 	/*flags4*/SCP_TAS,
185 	/*aen_holdoff_period*/{0, 0},
186 	/*busy_timeout_period*/{0, 0},
187 	/*extended_selftest_completion_time*/{0, 0}
188 };
189 
190 const static struct scsi_control_page control_page_changeable = {
191 	/*page_code*/SMS_CONTROL_MODE_PAGE,
192 	/*page_length*/sizeof(struct scsi_control_page) - 2,
193 	/*rlec*/SCP_DSENSE,
194 	/*queue_flags*/SCP_QUEUE_ALG_MASK | SCP_NUAR,
195 	/*eca_and_aen*/SCP_SWP,
196 	/*flags4*/0,
197 	/*aen_holdoff_period*/{0, 0},
198 	/*busy_timeout_period*/{0, 0},
199 	/*extended_selftest_completion_time*/{0, 0}
200 };
201 
202 #define CTL_CEM_LEN	(sizeof(struct scsi_control_ext_page) - 4)
203 
204 const static struct scsi_control_ext_page control_ext_page_default = {
205 	/*page_code*/SMS_CONTROL_MODE_PAGE | SMPH_SPF,
206 	/*subpage_code*/0x01,
207 	/*page_length*/{CTL_CEM_LEN >> 8, CTL_CEM_LEN},
208 	/*flags*/0,
209 	/*prio*/0,
210 	/*max_sense*/0
211 };
212 
213 const static struct scsi_control_ext_page control_ext_page_changeable = {
214 	/*page_code*/SMS_CONTROL_MODE_PAGE | SMPH_SPF,
215 	/*subpage_code*/0x01,
216 	/*page_length*/{CTL_CEM_LEN >> 8, CTL_CEM_LEN},
217 	/*flags*/0,
218 	/*prio*/0,
219 	/*max_sense*/0xff
220 };
221 
222 const static struct scsi_info_exceptions_page ie_page_default = {
223 	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
224 	/*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
225 	/*info_flags*/SIEP_FLAGS_EWASC,
226 	/*mrie*/SIEP_MRIE_NO,
227 	/*interval_timer*/{0, 0, 0, 0},
228 	/*report_count*/{0, 0, 0, 1}
229 };
230 
231 const static struct scsi_info_exceptions_page ie_page_changeable = {
232 	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
233 	/*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
234 	/*info_flags*/SIEP_FLAGS_EWASC | SIEP_FLAGS_DEXCPT | SIEP_FLAGS_TEST |
235 	    SIEP_FLAGS_LOGERR,
236 	/*mrie*/0x0f,
237 	/*interval_timer*/{0xff, 0xff, 0xff, 0xff},
238 	/*report_count*/{0xff, 0xff, 0xff, 0xff}
239 };
240 
241 #define CTL_LBPM_LEN	(sizeof(struct ctl_logical_block_provisioning_page) - 4)
242 
243 const static struct ctl_logical_block_provisioning_page lbp_page_default = {{
244 	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
245 	/*subpage_code*/0x02,
246 	/*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
247 	/*flags*/0,
248 	/*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
249 	/*descr*/{}},
250 	{{/*flags*/0,
251 	  /*resource*/0x01,
252 	  /*reserved*/{0, 0},
253 	  /*count*/{0, 0, 0, 0}},
254 	 {/*flags*/0,
255 	  /*resource*/0x02,
256 	  /*reserved*/{0, 0},
257 	  /*count*/{0, 0, 0, 0}},
258 	 {/*flags*/0,
259 	  /*resource*/0xf1,
260 	  /*reserved*/{0, 0},
261 	  /*count*/{0, 0, 0, 0}},
262 	 {/*flags*/0,
263 	  /*resource*/0xf2,
264 	  /*reserved*/{0, 0},
265 	  /*count*/{0, 0, 0, 0}}
266 	}
267 };
268 
269 const static struct ctl_logical_block_provisioning_page lbp_page_changeable = {{
270 	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
271 	/*subpage_code*/0x02,
272 	/*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
273 	/*flags*/SLBPP_SITUA,
274 	/*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
275 	/*descr*/{}},
276 	{{/*flags*/0,
277 	  /*resource*/0,
278 	  /*reserved*/{0, 0},
279 	  /*count*/{0, 0, 0, 0}},
280 	 {/*flags*/0,
281 	  /*resource*/0,
282 	  /*reserved*/{0, 0},
283 	  /*count*/{0, 0, 0, 0}},
284 	 {/*flags*/0,
285 	  /*resource*/0,
286 	  /*reserved*/{0, 0},
287 	  /*count*/{0, 0, 0, 0}},
288 	 {/*flags*/0,
289 	  /*resource*/0,
290 	  /*reserved*/{0, 0},
291 	  /*count*/{0, 0, 0, 0}}
292 	}
293 };
294 
295 const static struct scsi_cddvd_capabilities_page cddvd_page_default = {
296 	/*page_code*/SMS_CDDVD_CAPS_PAGE,
297 	/*page_length*/sizeof(struct scsi_cddvd_capabilities_page) - 2,
298 	/*caps1*/0x3f,
299 	/*caps2*/0x00,
300 	/*caps3*/0xf0,
301 	/*caps4*/0x00,
302 	/*caps5*/0x29,
303 	/*caps6*/0x00,
304 	/*obsolete*/{0, 0},
305 	/*nvol_levels*/{0, 0},
306 	/*buffer_size*/{8, 0},
307 	/*obsolete2*/{0, 0},
308 	/*reserved*/0,
309 	/*digital*/0,
310 	/*obsolete3*/0,
311 	/*copy_management*/0,
312 	/*reserved2*/0,
313 	/*rotation_control*/0,
314 	/*cur_write_speed*/0,
315 	/*num_speed_descr*/0,
316 };
317 
318 const static struct scsi_cddvd_capabilities_page cddvd_page_changeable = {
319 	/*page_code*/SMS_CDDVD_CAPS_PAGE,
320 	/*page_length*/sizeof(struct scsi_cddvd_capabilities_page) - 2,
321 	/*caps1*/0,
322 	/*caps2*/0,
323 	/*caps3*/0,
324 	/*caps4*/0,
325 	/*caps5*/0,
326 	/*caps6*/0,
327 	/*obsolete*/{0, 0},
328 	/*nvol_levels*/{0, 0},
329 	/*buffer_size*/{0, 0},
330 	/*obsolete2*/{0, 0},
331 	/*reserved*/0,
332 	/*digital*/0,
333 	/*obsolete3*/0,
334 	/*copy_management*/0,
335 	/*reserved2*/0,
336 	/*rotation_control*/0,
337 	/*cur_write_speed*/0,
338 	/*num_speed_descr*/0,
339 };
340 
341 SYSCTL_NODE(_kern_cam, OID_AUTO, ctl, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
342     "CAM Target Layer");
343 static int worker_threads = -1;
344 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, worker_threads, CTLFLAG_RDTUN,
345     &worker_threads, 1, "Number of worker threads");
346 static int ctl_debug = CTL_DEBUG_NONE;
347 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, debug, CTLFLAG_RWTUN,
348     &ctl_debug, 0, "Enabled debug flags");
349 static int ctl_lun_map_size = 1024;
350 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, lun_map_size, CTLFLAG_RWTUN,
351     &ctl_lun_map_size, 0, "Size of per-port LUN map (max LUN + 1)");
352 #ifdef  CTL_TIME_IO
353 static int ctl_time_io_secs = CTL_TIME_IO_DEFAULT_SECS;
354 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, time_io_secs, CTLFLAG_RWTUN,
355     &ctl_time_io_secs, 0, "Log requests taking more seconds");
356 #endif
357 
358 /*
359  * Maximum number of LUNs we support.  MUST be a power of 2.
360  */
361 #define	CTL_DEFAULT_MAX_LUNS	1024
362 static int ctl_max_luns = CTL_DEFAULT_MAX_LUNS;
363 TUNABLE_INT("kern.cam.ctl.max_luns", &ctl_max_luns);
364 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, max_luns, CTLFLAG_RDTUN,
365     &ctl_max_luns, CTL_DEFAULT_MAX_LUNS, "Maximum number of LUNs");
366 
367 /*
368  * Maximum number of ports registered at one time.
369  */
370 #define	CTL_DEFAULT_MAX_PORTS		1024
371 static int ctl_max_ports = CTL_DEFAULT_MAX_PORTS;
372 TUNABLE_INT("kern.cam.ctl.max_ports", &ctl_max_ports);
373 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, max_ports, CTLFLAG_RDTUN,
374     &ctl_max_ports, CTL_DEFAULT_MAX_LUNS, "Maximum number of ports");
375 
376 /*
377  * Maximum number of initiators we support.
378  */
379 #define	CTL_MAX_INITIATORS	(CTL_MAX_INIT_PER_PORT * ctl_max_ports)
380 
381 /*
382  * Supported pages (0x00), Serial number (0x80), Device ID (0x83),
383  * Extended INQUIRY Data (0x86), Mode Page Policy (0x87),
384  * SCSI Ports (0x88), Third-party Copy (0x8F), SCSI Feature Sets (0x92),
385  * Block limits (0xB0), Block Device Characteristics (0xB1) and
386  * Logical Block Provisioning (0xB2)
387  */
388 #define SCSI_EVPD_NUM_SUPPORTED_PAGES	11
389 
390 static void ctl_isc_event_handler(ctl_ha_channel chanel, ctl_ha_event event,
391 				  int param);
392 static void ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest);
393 static void ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest);
394 static int ctl_init(void);
395 static int ctl_shutdown(void);
396 static int ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td);
397 static int ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td);
398 static void ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio);
399 static void ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
400 			      struct ctl_ooa *ooa_hdr,
401 			      struct ctl_ooa_entry *kern_entries);
402 static int ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
403 		     struct thread *td);
404 static int ctl_enable_lun(struct ctl_lun *lun);
405 static int ctl_disable_lun(struct ctl_lun *lun);
406 static int ctl_free_lun(struct ctl_lun *lun);
407 
408 static int ctl_do_mode_select(union ctl_io *io);
409 static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
410 			   uint64_t res_key, uint64_t sa_res_key,
411 			   uint8_t type, uint32_t residx,
412 			   struct ctl_scsiio *ctsio,
413 			   struct scsi_per_res_out *cdb,
414 			   struct scsi_per_res_out_parms* param);
415 static void ctl_pro_preempt_other(struct ctl_lun *lun,
416 				  union ctl_ha_msg *msg);
417 static void ctl_hndl_per_res_out_on_other_sc(union ctl_io *io);
418 static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
419 static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
420 static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
421 static int ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len);
422 static int ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len);
423 static int ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio,
424 					 int alloc_len);
425 static int ctl_inquiry_evpd_sfs(struct ctl_scsiio *ctsio, int alloc_len);
426 static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
427 					 int alloc_len);
428 static int ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len);
429 static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
430 static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
431 static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
432 static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len);
433 static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2,
434     bool seq);
435 static ctl_action ctl_seq_check(union ctl_io *io1, union ctl_io *io2);
436 static ctl_action ctl_check_for_blockage(struct ctl_lun *lun,
437     union ctl_io *pending_io, const uint8_t *serialize_row,
438     union ctl_io *ooa_io);
439 static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
440 				union ctl_io **starting_io);
441 static void ctl_try_unblock_io(struct ctl_lun *lun, union ctl_io *io,
442     bool skip);
443 static void ctl_try_unblock_others(struct ctl_lun *lun, union ctl_io *io,
444     bool skip);
445 static int ctl_scsiio_lun_check(struct ctl_lun *lun,
446 				const struct ctl_cmd_entry *entry,
447 				struct ctl_scsiio *ctsio);
448 static void ctl_failover_lun(union ctl_io *io);
449 static void ctl_scsiio_precheck(struct ctl_scsiio *ctsio);
450 static int ctl_scsiio(struct ctl_scsiio *ctsio);
451 static void ctl_nvmeio_precheck(struct ctl_nvmeio *ctnio);
452 static int ctl_nvmeio(struct ctl_nvmeio *ctnio);
453 
454 static int ctl_target_reset(union ctl_io *io);
455 static void ctl_do_lun_reset(struct ctl_lun *lun, uint32_t initidx,
456 			 ctl_ua_type ua_type);
457 static int ctl_lun_reset(union ctl_io *io);
458 static int ctl_abort_task(union ctl_io *io);
459 static int ctl_abort_task_set(union ctl_io *io);
460 static int ctl_query_task(union ctl_io *io, int task_set);
461 static void ctl_i_t_nexus_loss(struct ctl_softc *softc, uint32_t initidx,
462 			      ctl_ua_type ua_type);
463 static int ctl_i_t_nexus_reset(union ctl_io *io);
464 static int ctl_query_async_event(union ctl_io *io);
465 static void ctl_run_task(union ctl_io *io);
466 #ifdef CTL_IO_DELAY
467 static void ctl_datamove_timer_wakeup(void *arg);
468 static void ctl_done_timer_wakeup(void *arg);
469 #endif /* CTL_IO_DELAY */
470 
471 static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
472 static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
473 static int ctl_datamove_remote_dm_write_cb(union ctl_io *io, bool samethr);
474 static void ctl_datamove_remote_write(union ctl_io *io);
475 static int ctl_datamove_remote_dm_read_cb(union ctl_io *io, bool samethr);
476 static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
477 static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
478 static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
479 				    ctl_ha_dt_cb callback);
480 static void ctl_datamove_remote_read(union ctl_io *io);
481 static void ctl_datamove_remote(union ctl_io *io);
482 static void ctl_process_done(union ctl_io *io);
483 static void ctl_thresh_thread(void *arg);
484 static void ctl_work_thread(void *arg);
485 static void ctl_enqueue_incoming(union ctl_io *io);
486 static void ctl_enqueue_rtr(union ctl_io *io);
487 static void ctl_enqueue_done(union ctl_io *io);
488 static void ctl_enqueue_isc(union ctl_io *io);
489 static const struct ctl_cmd_entry *
490     ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa);
491 static const struct ctl_cmd_entry *
492     ctl_validate_command(struct ctl_scsiio *ctsio);
493 static int ctl_cmd_applicable(uint8_t lun_type,
494     const struct ctl_cmd_entry *entry);
495 static int ctl_ha_init(void);
496 static int ctl_ha_shutdown(void);
497 
498 static uint64_t ctl_get_prkey(struct ctl_lun *lun, uint32_t residx);
499 static void ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx);
500 static void ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx);
501 static void ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key);
502 
503 /*
504  * Load the serialization table.  This isn't very pretty, but is probably
505  * the easiest way to do it.
506  */
507 #include "ctl_ser_table.c"
508 
509 /*
510  * We only need to define open, close and ioctl routines for this driver.
511  */
512 static struct cdevsw ctl_cdevsw = {
513 	.d_version =	D_VERSION,
514 	.d_flags =	0,
515 	.d_open =	ctl_open,
516 	.d_close =	ctl_close,
517 	.d_ioctl =	ctl_ioctl,
518 	.d_name =	"ctl",
519 };
520 
521 MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
522 
523 static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
524 
525 static moduledata_t ctl_moduledata = {
526 	"ctl",
527 	ctl_module_event_handler,
528 	NULL
529 };
530 
531 DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
532 MODULE_VERSION(ctl, 1);
533 
534 static void
535 ctl_be_move_done(union ctl_io *io, bool samethr)
536 {
537 	switch (io->io_hdr.io_type) {
538 	case CTL_IO_SCSI:
539 		io->scsiio.be_move_done(io, samethr);
540 		break;
541 	case CTL_IO_NVME:
542 	case CTL_IO_NVME_ADMIN:
543 		io->nvmeio.be_move_done(io, samethr);
544 		break;
545 	default:
546 		__assert_unreachable();
547 	}
548 }
549 
550 static void
551 ctl_continue_io(union ctl_io *io)
552 {
553 	switch (io->io_hdr.io_type) {
554 	case CTL_IO_SCSI:
555 		io->scsiio.io_cont(io);
556 		break;
557 	case CTL_IO_NVME:
558 	case CTL_IO_NVME_ADMIN:
559 		io->nvmeio.io_cont(io);
560 		break;
561 	default:
562 		__assert_unreachable();
563 	}
564 }
565 
566 static struct ctl_frontend ha_frontend =
567 {
568 	.name = "ha",
569 	.init = ctl_ha_init,
570 	.shutdown = ctl_ha_shutdown,
571 };
572 
573 static int
574 ctl_ha_init(void)
575 {
576 	struct ctl_softc *softc = control_softc;
577 
578 	if (ctl_pool_create(softc, "othersc", CTL_POOL_ENTRIES_OTHER_SC,
579 	                    &softc->othersc_pool) != 0)
580 		return (ENOMEM);
581 	if (ctl_ha_msg_init(softc) != CTL_HA_STATUS_SUCCESS) {
582 		ctl_pool_free(softc->othersc_pool);
583 		return (EIO);
584 	}
585 	if (ctl_ha_msg_register(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
586 	    != CTL_HA_STATUS_SUCCESS) {
587 		ctl_ha_msg_destroy(softc);
588 		ctl_pool_free(softc->othersc_pool);
589 		return (EIO);
590 	}
591 	return (0);
592 };
593 
594 static int
595 ctl_ha_shutdown(void)
596 {
597 	struct ctl_softc *softc = control_softc;
598 	struct ctl_port *port;
599 
600 	ctl_ha_msg_shutdown(softc);
601 	if (ctl_ha_msg_deregister(CTL_HA_CHAN_CTL) != CTL_HA_STATUS_SUCCESS)
602 		return (EIO);
603 	if (ctl_ha_msg_destroy(softc) != CTL_HA_STATUS_SUCCESS)
604 		return (EIO);
605 	ctl_pool_free(softc->othersc_pool);
606 	while ((port = STAILQ_FIRST(&ha_frontend.port_list)) != NULL) {
607 		ctl_port_deregister(port);
608 		free(port->port_name, M_CTL);
609 		free(port, M_CTL);
610 	}
611 	return (0);
612 };
613 
614 static void
615 ctl_ha_datamove(union ctl_io *io)
616 {
617 	struct ctl_lun *lun = CTL_LUN(io);
618 	struct ctl_sg_entry *sgl;
619 	union ctl_ha_msg msg;
620 	uint32_t sg_entries_sent;
621 	int do_sg_copy, i, j;
622 
623 	CTL_IO_ASSERT(io, SCSI);
624 
625 	memset(&msg.dt, 0, sizeof(msg.dt));
626 	msg.hdr.msg_type = CTL_MSG_DATAMOVE;
627 	msg.hdr.original_sc = io->io_hdr.remote_io;
628 	msg.hdr.serializing_sc = io;
629 	msg.hdr.nexus = io->io_hdr.nexus;
630 	msg.hdr.status = io->io_hdr.status;
631 	msg.dt.flags = io->io_hdr.flags;
632 
633 	/*
634 	 * We convert everything into a S/G list here.  We can't
635 	 * pass by reference, only by value between controllers.
636 	 * So we can't pass a pointer to the S/G list, only as many
637 	 * S/G entries as we can fit in here.  If it's possible for
638 	 * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
639 	 * then we need to break this up into multiple transfers.
640 	 */
641 	if (ctl_kern_sg_entries(io) == 0) {
642 		msg.dt.kern_sg_entries = 1;
643 #if 0
644 		if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
645 			msg.dt.sg_list[0].addr = ctl_kern_data_ptr(io);
646 		} else {
647 			/* XXX KDM use busdma here! */
648 			msg.dt.sg_list[0].addr =
649 			    (void *)vtophys(ctl_kern_data_ptr(io));
650 		}
651 #else
652 		KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
653 		    ("HA does not support BUS_ADDR"));
654 		msg.dt.sg_list[0].addr = ctl_kern_data_ptr(io);
655 #endif
656 		msg.dt.sg_list[0].len = ctl_kern_data_len(io);
657 		do_sg_copy = 0;
658 	} else {
659 		msg.dt.kern_sg_entries = ctl_kern_sg_entries(io);
660 		do_sg_copy = 1;
661 	}
662 
663 	msg.dt.kern_data_len = ctl_kern_data_len(io);
664 	msg.dt.kern_total_len = ctl_kern_total_len(io);
665 	msg.dt.kern_data_resid = ctl_kern_data_resid(io);
666 	msg.dt.kern_rel_offset = ctl_kern_rel_offset(io);
667 	msg.dt.sg_sequence = 0;
668 
669 	/*
670 	 * Loop until we've sent all of the S/G entries.  On the
671 	 * other end, we'll recompose these S/G entries into one
672 	 * contiguous list before processing.
673 	 */
674 	for (sg_entries_sent = 0; sg_entries_sent < msg.dt.kern_sg_entries;
675 	    msg.dt.sg_sequence++) {
676 		msg.dt.cur_sg_entries = MIN((sizeof(msg.dt.sg_list) /
677 		    sizeof(msg.dt.sg_list[0])),
678 		    msg.dt.kern_sg_entries - sg_entries_sent);
679 		if (do_sg_copy != 0) {
680 			sgl = (struct ctl_sg_entry *)ctl_kern_data_ptr(io);
681 			for (i = sg_entries_sent, j = 0;
682 			     i < msg.dt.cur_sg_entries; i++, j++) {
683 #if 0
684 				if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
685 					msg.dt.sg_list[j].addr = sgl[i].addr;
686 				} else {
687 					/* XXX KDM use busdma here! */
688 					msg.dt.sg_list[j].addr =
689 					    (void *)vtophys(sgl[i].addr);
690 				}
691 #else
692 				KASSERT((io->io_hdr.flags &
693 				    CTL_FLAG_BUS_ADDR) == 0,
694 				    ("HA does not support BUS_ADDR"));
695 				msg.dt.sg_list[j].addr = sgl[i].addr;
696 #endif
697 				msg.dt.sg_list[j].len = sgl[i].len;
698 			}
699 		}
700 
701 		sg_entries_sent += msg.dt.cur_sg_entries;
702 		msg.dt.sg_last = (sg_entries_sent >= msg.dt.kern_sg_entries);
703 		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
704 		    sizeof(msg.dt) - sizeof(msg.dt.sg_list) +
705 		    sizeof(struct ctl_sg_entry) * msg.dt.cur_sg_entries,
706 		    M_WAITOK) > CTL_HA_STATUS_SUCCESS) {
707 			io->io_hdr.port_status = 31341;
708 			ctl_datamove_done(io, true);
709 			return;
710 		}
711 		msg.dt.sent_sg_entries = sg_entries_sent;
712 	}
713 
714 	/*
715 	 * Officially handover the request from us to peer.
716 	 * If failover has just happened, then we must return error.
717 	 * If failover happen just after, then it is not our problem.
718 	 */
719 	if (lun)
720 		mtx_lock(&lun->lun_lock);
721 	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
722 		if (lun)
723 			mtx_unlock(&lun->lun_lock);
724 		io->io_hdr.port_status = 31342;
725 		ctl_datamove_done(io, true);
726 		return;
727 	}
728 	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
729 	io->io_hdr.flags |= CTL_FLAG_DMA_INPROG;
730 	if (lun)
731 		mtx_unlock(&lun->lun_lock);
732 }
733 
734 static void
735 ctl_ha_done(union ctl_io *io)
736 {
737 	union ctl_ha_msg msg;
738 
739 	if (io->io_hdr.io_type == CTL_IO_SCSI) {
740 		memset(&msg, 0, sizeof(msg));
741 		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
742 		msg.hdr.original_sc = io->io_hdr.remote_io;
743 		msg.hdr.nexus = io->io_hdr.nexus;
744 		msg.hdr.status = io->io_hdr.status;
745 		msg.scsi.scsi_status = io->scsiio.scsi_status;
746 		msg.scsi.tag_num = io->scsiio.tag_num;
747 		msg.scsi.tag_type = io->scsiio.tag_type;
748 		msg.scsi.sense_len = io->scsiio.sense_len;
749 		memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
750 		    io->scsiio.sense_len);
751 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
752 		    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
753 		    msg.scsi.sense_len, M_WAITOK);
754 	}
755 	ctl_free_io(io);
756 }
757 
758 static void
759 ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
760 			    union ctl_ha_msg *msg_info)
761 {
762 	struct ctl_scsiio *ctsio;
763 
764 	if (msg_info->hdr.original_sc == NULL) {
765 		printf("%s: original_sc == NULL!\n", __func__);
766 		/* XXX KDM now what? */
767 		return;
768 	}
769 
770 	ctsio = &msg_info->hdr.original_sc->scsiio;
771 	ctsio->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
772 	ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
773 	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
774 	ctsio->io_hdr.status = msg_info->hdr.status;
775 	ctsio->scsi_status = msg_info->scsi.scsi_status;
776 	ctsio->sense_len = msg_info->scsi.sense_len;
777 	memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
778 	       msg_info->scsi.sense_len);
779 	ctl_enqueue_isc((union ctl_io *)ctsio);
780 }
781 
782 static void
783 ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
784 				union ctl_ha_msg *msg_info)
785 {
786 	struct ctl_scsiio *ctsio;
787 
788 	if (msg_info->hdr.serializing_sc == NULL) {
789 		printf("%s: serializing_sc == NULL!\n", __func__);
790 		/* XXX KDM now what? */
791 		return;
792 	}
793 
794 	ctsio = &msg_info->hdr.serializing_sc->scsiio;
795 	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
796 	ctl_enqueue_isc((union ctl_io *)ctsio);
797 }
798 
799 void
800 ctl_isc_announce_lun(struct ctl_lun *lun)
801 {
802 	struct ctl_softc *softc = lun->ctl_softc;
803 	union ctl_ha_msg *msg;
804 	struct ctl_ha_msg_lun_pr_key pr_key;
805 	int i, k;
806 
807 	if (softc->ha_link != CTL_HA_LINK_ONLINE)
808 		return;
809 	mtx_lock(&lun->lun_lock);
810 	i = sizeof(msg->lun);
811 	if (lun->lun_devid)
812 		i += lun->lun_devid->len;
813 	i += sizeof(pr_key) * lun->pr_key_count;
814 alloc:
815 	mtx_unlock(&lun->lun_lock);
816 	msg = malloc(i, M_CTL, M_WAITOK);
817 	mtx_lock(&lun->lun_lock);
818 	k = sizeof(msg->lun);
819 	if (lun->lun_devid)
820 		k += lun->lun_devid->len;
821 	k += sizeof(pr_key) * lun->pr_key_count;
822 	if (i < k) {
823 		free(msg, M_CTL);
824 		i = k;
825 		goto alloc;
826 	}
827 	bzero(&msg->lun, sizeof(msg->lun));
828 	msg->hdr.msg_type = CTL_MSG_LUN_SYNC;
829 	msg->hdr.nexus.targ_lun = lun->lun;
830 	msg->hdr.nexus.targ_mapped_lun = lun->lun;
831 	msg->lun.flags = lun->flags;
832 	msg->lun.pr_generation = lun->pr_generation;
833 	msg->lun.pr_res_idx = lun->pr_res_idx;
834 	msg->lun.pr_res_type = lun->pr_res_type;
835 	msg->lun.pr_key_count = lun->pr_key_count;
836 	i = 0;
837 	if (lun->lun_devid) {
838 		msg->lun.lun_devid_len = lun->lun_devid->len;
839 		memcpy(&msg->lun.data[i], lun->lun_devid->data,
840 		    msg->lun.lun_devid_len);
841 		i += msg->lun.lun_devid_len;
842 	}
843 	for (k = 0; k < CTL_MAX_INITIATORS; k++) {
844 		if ((pr_key.pr_key = ctl_get_prkey(lun, k)) == 0)
845 			continue;
846 		pr_key.pr_iid = k;
847 		memcpy(&msg->lun.data[i], &pr_key, sizeof(pr_key));
848 		i += sizeof(pr_key);
849 	}
850 	mtx_unlock(&lun->lun_lock);
851 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->lun, sizeof(msg->lun) + i,
852 	    M_WAITOK);
853 	free(msg, M_CTL);
854 
855 	if (lun->flags & CTL_LUN_PRIMARY_SC) {
856 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
857 			ctl_isc_announce_mode(lun, -1,
858 			    lun->mode_pages.index[i].page_code & SMPH_PC_MASK,
859 			    lun->mode_pages.index[i].subpage);
860 		}
861 	}
862 }
863 
864 void
865 ctl_isc_announce_port(struct ctl_port *port)
866 {
867 	struct ctl_softc *softc = port->ctl_softc;
868 	union ctl_ha_msg *msg;
869 	int i;
870 
871 	if (port->targ_port < softc->port_min ||
872 	    port->targ_port >= softc->port_max ||
873 	    softc->ha_link != CTL_HA_LINK_ONLINE)
874 		return;
875 	i = sizeof(msg->port) + strlen(port->port_name) + 1;
876 	if (port->lun_map)
877 		i += port->lun_map_size * sizeof(uint32_t);
878 	if (port->port_devid)
879 		i += port->port_devid->len;
880 	if (port->target_devid)
881 		i += port->target_devid->len;
882 	if (port->init_devid)
883 		i += port->init_devid->len;
884 	msg = malloc(i, M_CTL, M_WAITOK);
885 	bzero(&msg->port, sizeof(msg->port));
886 	msg->hdr.msg_type = CTL_MSG_PORT_SYNC;
887 	msg->hdr.nexus.targ_port = port->targ_port;
888 	msg->port.port_type = port->port_type;
889 	msg->port.physical_port = port->physical_port;
890 	msg->port.virtual_port = port->virtual_port;
891 	msg->port.status = port->status;
892 	i = 0;
893 	msg->port.name_len = sprintf(&msg->port.data[i],
894 	    "%d:%s", softc->ha_id, port->port_name) + 1;
895 	i += msg->port.name_len;
896 	if (port->lun_map) {
897 		msg->port.lun_map_len = port->lun_map_size * sizeof(uint32_t);
898 		memcpy(&msg->port.data[i], port->lun_map,
899 		    msg->port.lun_map_len);
900 		i += msg->port.lun_map_len;
901 	}
902 	if (port->port_devid) {
903 		msg->port.port_devid_len = port->port_devid->len;
904 		memcpy(&msg->port.data[i], port->port_devid->data,
905 		    msg->port.port_devid_len);
906 		i += msg->port.port_devid_len;
907 	}
908 	if (port->target_devid) {
909 		msg->port.target_devid_len = port->target_devid->len;
910 		memcpy(&msg->port.data[i], port->target_devid->data,
911 		    msg->port.target_devid_len);
912 		i += msg->port.target_devid_len;
913 	}
914 	if (port->init_devid) {
915 		msg->port.init_devid_len = port->init_devid->len;
916 		memcpy(&msg->port.data[i], port->init_devid->data,
917 		    msg->port.init_devid_len);
918 		i += msg->port.init_devid_len;
919 	}
920 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->port, sizeof(msg->port) + i,
921 	    M_WAITOK);
922 	free(msg, M_CTL);
923 }
924 
925 void
926 ctl_isc_announce_iid(struct ctl_port *port, int iid)
927 {
928 	struct ctl_softc *softc = port->ctl_softc;
929 	union ctl_ha_msg *msg;
930 	int i, l;
931 
932 	if (port->targ_port < softc->port_min ||
933 	    port->targ_port >= softc->port_max ||
934 	    softc->ha_link != CTL_HA_LINK_ONLINE)
935 		return;
936 	mtx_lock(&softc->ctl_lock);
937 	i = sizeof(msg->iid);
938 	l = 0;
939 	if (port->wwpn_iid[iid].name)
940 		l = strlen(port->wwpn_iid[iid].name) + 1;
941 	i += l;
942 	msg = malloc(i, M_CTL, M_NOWAIT);
943 	if (msg == NULL) {
944 		mtx_unlock(&softc->ctl_lock);
945 		return;
946 	}
947 	bzero(&msg->iid, sizeof(msg->iid));
948 	msg->hdr.msg_type = CTL_MSG_IID_SYNC;
949 	msg->hdr.nexus.targ_port = port->targ_port;
950 	msg->hdr.nexus.initid = iid;
951 	msg->iid.in_use = port->wwpn_iid[iid].in_use;
952 	msg->iid.name_len = l;
953 	msg->iid.wwpn = port->wwpn_iid[iid].wwpn;
954 	if (port->wwpn_iid[iid].name)
955 		strlcpy(msg->iid.data, port->wwpn_iid[iid].name, l);
956 	mtx_unlock(&softc->ctl_lock);
957 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->iid, i, M_NOWAIT);
958 	free(msg, M_CTL);
959 }
960 
961 void
962 ctl_isc_announce_mode(struct ctl_lun *lun, uint32_t initidx,
963     uint8_t page, uint8_t subpage)
964 {
965 	struct ctl_softc *softc = lun->ctl_softc;
966 	union ctl_ha_msg *msg;
967 	u_int i, l;
968 
969 	if (softc->ha_link != CTL_HA_LINK_ONLINE)
970 		return;
971 	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
972 		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) ==
973 		    page && lun->mode_pages.index[i].subpage == subpage)
974 			break;
975 	}
976 	if (i == CTL_NUM_MODE_PAGES)
977 		return;
978 
979 	/* Don't try to replicate pages not present on this device. */
980 	if (lun->mode_pages.index[i].page_data == NULL)
981 		return;
982 
983 	l = sizeof(msg->mode) + lun->mode_pages.index[i].page_len;
984 	msg = malloc(l, M_CTL, M_WAITOK | M_ZERO);
985 	msg->hdr.msg_type = CTL_MSG_MODE_SYNC;
986 	msg->hdr.nexus.targ_port = initidx / CTL_MAX_INIT_PER_PORT;
987 	msg->hdr.nexus.initid = initidx % CTL_MAX_INIT_PER_PORT;
988 	msg->hdr.nexus.targ_lun = lun->lun;
989 	msg->hdr.nexus.targ_mapped_lun = lun->lun;
990 	msg->mode.page_code = page;
991 	msg->mode.subpage = subpage;
992 	msg->mode.page_len = lun->mode_pages.index[i].page_len;
993 	memcpy(msg->mode.data, lun->mode_pages.index[i].page_data,
994 	    msg->mode.page_len);
995 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->mode, l, M_WAITOK);
996 	free(msg, M_CTL);
997 }
998 
999 static void
1000 ctl_isc_ha_link_up(struct ctl_softc *softc)
1001 {
1002 	struct ctl_port *port;
1003 	struct ctl_lun *lun;
1004 	union ctl_ha_msg msg;
1005 	int i;
1006 
1007 	/* Announce this node parameters to peer for validation. */
1008 	msg.login.msg_type = CTL_MSG_LOGIN;
1009 	msg.login.version = CTL_HA_VERSION;
1010 	msg.login.ha_mode = softc->ha_mode;
1011 	msg.login.ha_id = softc->ha_id;
1012 	msg.login.max_luns = ctl_max_luns;
1013 	msg.login.max_ports = ctl_max_ports;
1014 	msg.login.max_init_per_port = CTL_MAX_INIT_PER_PORT;
1015 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg.login, sizeof(msg.login),
1016 	    M_WAITOK);
1017 
1018 	STAILQ_FOREACH(port, &softc->port_list, links) {
1019 		ctl_isc_announce_port(port);
1020 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1021 			if (port->wwpn_iid[i].in_use)
1022 				ctl_isc_announce_iid(port, i);
1023 		}
1024 	}
1025 	STAILQ_FOREACH(lun, &softc->lun_list, links)
1026 		ctl_isc_announce_lun(lun);
1027 }
1028 
1029 static void
1030 ctl_isc_ha_link_down(struct ctl_softc *softc)
1031 {
1032 	struct ctl_port *port;
1033 	struct ctl_lun *lun;
1034 	union ctl_io *io;
1035 	int i;
1036 
1037 	mtx_lock(&softc->ctl_lock);
1038 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
1039 		mtx_lock(&lun->lun_lock);
1040 		if (lun->flags & CTL_LUN_PEER_SC_PRIMARY) {
1041 			lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
1042 			ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
1043 		}
1044 		mtx_unlock(&lun->lun_lock);
1045 
1046 		mtx_unlock(&softc->ctl_lock);
1047 		io = ctl_alloc_io(softc->othersc_pool);
1048 		mtx_lock(&softc->ctl_lock);
1049 		ctl_zero_io(io);
1050 		io->io_hdr.msg_type = CTL_MSG_FAILOVER;
1051 		io->io_hdr.nexus.targ_mapped_lun = lun->lun;
1052 		ctl_enqueue_isc(io);
1053 	}
1054 
1055 	STAILQ_FOREACH(port, &softc->port_list, links) {
1056 		if (port->targ_port >= softc->port_min &&
1057 		    port->targ_port < softc->port_max)
1058 			continue;
1059 		port->status &= ~CTL_PORT_STATUS_ONLINE;
1060 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1061 			port->wwpn_iid[i].in_use = 0;
1062 			free(port->wwpn_iid[i].name, M_CTL);
1063 			port->wwpn_iid[i].name = NULL;
1064 		}
1065 	}
1066 	mtx_unlock(&softc->ctl_lock);
1067 }
1068 
1069 static void
1070 ctl_isc_ua(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1071 {
1072 	struct ctl_lun *lun;
1073 	uint32_t iid;
1074 
1075 	if (len < sizeof(msg->ua)) {
1076 		printf("%s: Received truncated message %d < %zu\n",
1077 		    __func__, len, sizeof(msg->ua));
1078 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1079 		return;
1080 	}
1081 
1082 	mtx_lock(&softc->ctl_lock);
1083 	if (msg->hdr.nexus.targ_mapped_lun >= ctl_max_luns ||
1084 	    (lun = softc->ctl_luns[msg->hdr.nexus.targ_mapped_lun]) == NULL) {
1085 		mtx_unlock(&softc->ctl_lock);
1086 		return;
1087 	}
1088 	mtx_lock(&lun->lun_lock);
1089 	mtx_unlock(&softc->ctl_lock);
1090 	if (msg->ua.ua_type == CTL_UA_THIN_PROV_THRES && msg->ua.ua_set)
1091 		memcpy(lun->ua_tpt_info, msg->ua.ua_info, 8);
1092 	iid = ctl_get_initindex(&msg->hdr.nexus);
1093 	if (msg->ua.ua_all) {
1094 		if (msg->ua.ua_set)
1095 			ctl_est_ua_all(lun, iid, msg->ua.ua_type);
1096 		else
1097 			ctl_clr_ua_all(lun, iid, msg->ua.ua_type);
1098 	} else {
1099 		if (msg->ua.ua_set)
1100 			ctl_est_ua(lun, iid, msg->ua.ua_type);
1101 		else
1102 			ctl_clr_ua(lun, iid, msg->ua.ua_type);
1103 	}
1104 	mtx_unlock(&lun->lun_lock);
1105 }
1106 
1107 static void
1108 ctl_isc_lun_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1109 {
1110 	struct ctl_lun *lun;
1111 	struct ctl_ha_msg_lun_pr_key pr_key;
1112 	int i, k;
1113 	ctl_lun_flags oflags;
1114 	uint32_t targ_lun;
1115 
1116 	if (len < offsetof(struct ctl_ha_msg_lun, data[0])) {
1117 		printf("%s: Received truncated message %d < %zu\n",
1118 		    __func__, len, offsetof(struct ctl_ha_msg_lun, data[0]));
1119 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1120 		return;
1121 	}
1122 	i = msg->lun.lun_devid_len + msg->lun.pr_key_count * sizeof(pr_key);
1123 	if (len < offsetof(struct ctl_ha_msg_lun, data[i])) {
1124 		printf("%s: Received truncated message data %d < %zu\n",
1125 		    __func__, len, offsetof(struct ctl_ha_msg_lun, data[i]));
1126 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1127 		return;
1128 	}
1129 
1130 	targ_lun = msg->hdr.nexus.targ_mapped_lun;
1131 	mtx_lock(&softc->ctl_lock);
1132 	if (targ_lun >= ctl_max_luns ||
1133 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
1134 		mtx_unlock(&softc->ctl_lock);
1135 		return;
1136 	}
1137 	mtx_lock(&lun->lun_lock);
1138 	mtx_unlock(&softc->ctl_lock);
1139 	if (lun->flags & CTL_LUN_DISABLED) {
1140 		mtx_unlock(&lun->lun_lock);
1141 		return;
1142 	}
1143 	i = (lun->lun_devid != NULL) ? lun->lun_devid->len : 0;
1144 	if (msg->lun.lun_devid_len != i || (i > 0 &&
1145 	    memcmp(&msg->lun.data[0], lun->lun_devid->data, i) != 0)) {
1146 		mtx_unlock(&lun->lun_lock);
1147 		printf("%s: Received conflicting HA LUN %d\n",
1148 		    __func__, targ_lun);
1149 		return;
1150 	} else {
1151 		/* Record whether peer is primary. */
1152 		oflags = lun->flags;
1153 		if ((msg->lun.flags & CTL_LUN_PRIMARY_SC) &&
1154 		    (msg->lun.flags & CTL_LUN_DISABLED) == 0)
1155 			lun->flags |= CTL_LUN_PEER_SC_PRIMARY;
1156 		else
1157 			lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
1158 		if (oflags != lun->flags)
1159 			ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
1160 
1161 		/* If peer is primary and we are not -- use data */
1162 		if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
1163 		    (lun->flags & CTL_LUN_PEER_SC_PRIMARY)) {
1164 			lun->pr_generation = msg->lun.pr_generation;
1165 			lun->pr_res_idx = msg->lun.pr_res_idx;
1166 			lun->pr_res_type = msg->lun.pr_res_type;
1167 			lun->pr_key_count = msg->lun.pr_key_count;
1168 			for (k = 0; k < CTL_MAX_INITIATORS; k++)
1169 				ctl_clr_prkey(lun, k);
1170 			for (k = 0; k < msg->lun.pr_key_count; k++) {
1171 				memcpy(&pr_key, &msg->lun.data[i],
1172 				    sizeof(pr_key));
1173 				ctl_alloc_prkey(lun, pr_key.pr_iid);
1174 				ctl_set_prkey(lun, pr_key.pr_iid,
1175 				    pr_key.pr_key);
1176 				i += sizeof(pr_key);
1177 			}
1178 		}
1179 
1180 		mtx_unlock(&lun->lun_lock);
1181 		CTL_DEBUG_PRINT(("%s: Known LUN %d, peer is %s\n",
1182 		    __func__, targ_lun,
1183 		    (msg->lun.flags & CTL_LUN_PRIMARY_SC) ?
1184 		    "primary" : "secondary"));
1185 
1186 		/* If we are primary but peer doesn't know -- notify */
1187 		if ((lun->flags & CTL_LUN_PRIMARY_SC) &&
1188 		    (msg->lun.flags & CTL_LUN_PEER_SC_PRIMARY) == 0)
1189 			ctl_isc_announce_lun(lun);
1190 	}
1191 }
1192 
1193 static void
1194 ctl_isc_port_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1195 {
1196 	struct ctl_port *port;
1197 	struct ctl_lun *lun;
1198 	int i, new;
1199 
1200 	if (len < offsetof(struct ctl_ha_msg_port, data[0])) {
1201 		printf("%s: Received truncated message %d < %zu\n",
1202 		    __func__, len, offsetof(struct ctl_ha_msg_port, data[0]));
1203 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1204 		return;
1205 	}
1206 	i = msg->port.name_len + msg->port.lun_map_len +
1207 	    msg->port.port_devid_len + msg->port.target_devid_len +
1208 	    msg->port.init_devid_len;
1209 	if (len < offsetof(struct ctl_ha_msg_port, data[i])) {
1210 		printf("%s: Received truncated message data %d < %zu\n",
1211 		    __func__, len, offsetof(struct ctl_ha_msg_port, data[i]));
1212 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1213 		return;
1214 	}
1215 
1216 	port = softc->ctl_ports[msg->hdr.nexus.targ_port];
1217 	if (port == NULL) {
1218 		CTL_DEBUG_PRINT(("%s: New port %d\n", __func__,
1219 		    msg->hdr.nexus.targ_port));
1220 		new = 1;
1221 		port = malloc(sizeof(*port), M_CTL, M_WAITOK | M_ZERO);
1222 		port->frontend = &ha_frontend;
1223 		port->targ_port = msg->hdr.nexus.targ_port;
1224 		port->fe_datamove = ctl_ha_datamove;
1225 		port->fe_done = ctl_ha_done;
1226 	} else if (port->frontend == &ha_frontend) {
1227 		CTL_DEBUG_PRINT(("%s: Updated port %d\n", __func__,
1228 		    msg->hdr.nexus.targ_port));
1229 		new = 0;
1230 	} else {
1231 		printf("%s: Received conflicting HA port %d\n",
1232 		    __func__, msg->hdr.nexus.targ_port);
1233 		return;
1234 	}
1235 	port->port_type = msg->port.port_type;
1236 	port->physical_port = msg->port.physical_port;
1237 	port->virtual_port = msg->port.virtual_port;
1238 	port->status = msg->port.status;
1239 	i = 0;
1240 	free(port->port_name, M_CTL);
1241 	port->port_name = strndup(&msg->port.data[i], msg->port.name_len,
1242 	    M_CTL);
1243 	i += msg->port.name_len;
1244 	if (msg->port.lun_map_len != 0) {
1245 		if (port->lun_map == NULL ||
1246 		    port->lun_map_size * sizeof(uint32_t) <
1247 		    msg->port.lun_map_len) {
1248 			port->lun_map_size = 0;
1249 			free(port->lun_map, M_CTL);
1250 			port->lun_map = malloc(msg->port.lun_map_len,
1251 			    M_CTL, M_WAITOK);
1252 		}
1253 		memcpy(port->lun_map, &msg->port.data[i], msg->port.lun_map_len);
1254 		port->lun_map_size = msg->port.lun_map_len / sizeof(uint32_t);
1255 		i += msg->port.lun_map_len;
1256 	} else {
1257 		port->lun_map_size = 0;
1258 		free(port->lun_map, M_CTL);
1259 		port->lun_map = NULL;
1260 	}
1261 	if (msg->port.port_devid_len != 0) {
1262 		if (port->port_devid == NULL ||
1263 		    port->port_devid->len < msg->port.port_devid_len) {
1264 			free(port->port_devid, M_CTL);
1265 			port->port_devid = malloc(sizeof(struct ctl_devid) +
1266 			    msg->port.port_devid_len, M_CTL, M_WAITOK);
1267 		}
1268 		memcpy(port->port_devid->data, &msg->port.data[i],
1269 		    msg->port.port_devid_len);
1270 		port->port_devid->len = msg->port.port_devid_len;
1271 		i += msg->port.port_devid_len;
1272 	} else {
1273 		free(port->port_devid, M_CTL);
1274 		port->port_devid = NULL;
1275 	}
1276 	if (msg->port.target_devid_len != 0) {
1277 		if (port->target_devid == NULL ||
1278 		    port->target_devid->len < msg->port.target_devid_len) {
1279 			free(port->target_devid, M_CTL);
1280 			port->target_devid = malloc(sizeof(struct ctl_devid) +
1281 			    msg->port.target_devid_len, M_CTL, M_WAITOK);
1282 		}
1283 		memcpy(port->target_devid->data, &msg->port.data[i],
1284 		    msg->port.target_devid_len);
1285 		port->target_devid->len = msg->port.target_devid_len;
1286 		i += msg->port.target_devid_len;
1287 	} else {
1288 		free(port->target_devid, M_CTL);
1289 		port->target_devid = NULL;
1290 	}
1291 	if (msg->port.init_devid_len != 0) {
1292 		if (port->init_devid == NULL ||
1293 		    port->init_devid->len < msg->port.init_devid_len) {
1294 			free(port->init_devid, M_CTL);
1295 			port->init_devid = malloc(sizeof(struct ctl_devid) +
1296 			    msg->port.init_devid_len, M_CTL, M_WAITOK);
1297 		}
1298 		memcpy(port->init_devid->data, &msg->port.data[i],
1299 		    msg->port.init_devid_len);
1300 		port->init_devid->len = msg->port.init_devid_len;
1301 		i += msg->port.init_devid_len;
1302 	} else {
1303 		free(port->init_devid, M_CTL);
1304 		port->init_devid = NULL;
1305 	}
1306 	if (new) {
1307 		if (ctl_port_register(port) != 0) {
1308 			printf("%s: ctl_port_register() failed with error\n",
1309 			    __func__);
1310 		}
1311 	}
1312 	mtx_lock(&softc->ctl_lock);
1313 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
1314 		if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
1315 			continue;
1316 		mtx_lock(&lun->lun_lock);
1317 		ctl_est_ua_all(lun, -1, CTL_UA_INQ_CHANGE);
1318 		mtx_unlock(&lun->lun_lock);
1319 	}
1320 	mtx_unlock(&softc->ctl_lock);
1321 }
1322 
1323 static void
1324 ctl_isc_iid_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1325 {
1326 	struct ctl_port *port;
1327 	int i, iid;
1328 
1329 	if (len < offsetof(struct ctl_ha_msg_iid, data[0])) {
1330 		printf("%s: Received truncated message %d < %zu\n",
1331 		    __func__, len, offsetof(struct ctl_ha_msg_iid, data[0]));
1332 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1333 		return;
1334 	}
1335 	i = msg->iid.name_len;
1336 	if (len < offsetof(struct ctl_ha_msg_iid, data[i])) {
1337 		printf("%s: Received truncated message data %d < %zu\n",
1338 		    __func__, len, offsetof(struct ctl_ha_msg_iid, data[i]));
1339 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1340 		return;
1341 	}
1342 
1343 	port = softc->ctl_ports[msg->hdr.nexus.targ_port];
1344 	if (port == NULL) {
1345 		printf("%s: Received IID for unknown port %d\n",
1346 		    __func__, msg->hdr.nexus.targ_port);
1347 		return;
1348 	}
1349 	iid = msg->hdr.nexus.initid;
1350 	if (port->wwpn_iid[iid].in_use != 0 &&
1351 	    msg->iid.in_use == 0)
1352 		ctl_i_t_nexus_loss(softc, iid, CTL_UA_POWERON);
1353 	port->wwpn_iid[iid].in_use = msg->iid.in_use;
1354 	port->wwpn_iid[iid].wwpn = msg->iid.wwpn;
1355 	free(port->wwpn_iid[iid].name, M_CTL);
1356 	if (msg->iid.name_len) {
1357 		port->wwpn_iid[iid].name = strndup(&msg->iid.data[0],
1358 		    msg->iid.name_len, M_CTL);
1359 	} else
1360 		port->wwpn_iid[iid].name = NULL;
1361 }
1362 
1363 static void
1364 ctl_isc_login(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1365 {
1366 
1367 	if (len < sizeof(msg->login)) {
1368 		printf("%s: Received truncated message %d < %zu\n",
1369 		    __func__, len, sizeof(msg->login));
1370 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1371 		return;
1372 	}
1373 
1374 	if (msg->login.version != CTL_HA_VERSION) {
1375 		printf("CTL HA peers have different versions %d != %d\n",
1376 		    msg->login.version, CTL_HA_VERSION);
1377 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1378 		return;
1379 	}
1380 	if (msg->login.ha_mode != softc->ha_mode) {
1381 		printf("CTL HA peers have different ha_mode %d != %d\n",
1382 		    msg->login.ha_mode, softc->ha_mode);
1383 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1384 		return;
1385 	}
1386 	if (msg->login.ha_id == softc->ha_id) {
1387 		printf("CTL HA peers have same ha_id %d\n", msg->login.ha_id);
1388 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1389 		return;
1390 	}
1391 	if (msg->login.max_luns != ctl_max_luns ||
1392 	    msg->login.max_ports != ctl_max_ports ||
1393 	    msg->login.max_init_per_port != CTL_MAX_INIT_PER_PORT) {
1394 		printf("CTL HA peers have different limits\n");
1395 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1396 		return;
1397 	}
1398 }
1399 
1400 static void
1401 ctl_isc_mode_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1402 {
1403 	struct ctl_lun *lun;
1404 	u_int i;
1405 	uint32_t initidx, targ_lun;
1406 
1407 	if (len < offsetof(struct ctl_ha_msg_mode, data[0])) {
1408 		printf("%s: Received truncated message %d < %zu\n",
1409 		    __func__, len, offsetof(struct ctl_ha_msg_mode, data[0]));
1410 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1411 		return;
1412 	}
1413 	i = msg->mode.page_len;
1414 	if (len < offsetof(struct ctl_ha_msg_mode, data[i])) {
1415 		printf("%s: Received truncated message data %d < %zu\n",
1416 		    __func__, len, offsetof(struct ctl_ha_msg_mode, data[i]));
1417 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1418 		return;
1419 	}
1420 
1421 	targ_lun = msg->hdr.nexus.targ_mapped_lun;
1422 	mtx_lock(&softc->ctl_lock);
1423 	if (targ_lun >= ctl_max_luns ||
1424 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
1425 		mtx_unlock(&softc->ctl_lock);
1426 		return;
1427 	}
1428 	mtx_lock(&lun->lun_lock);
1429 	mtx_unlock(&softc->ctl_lock);
1430 	if (lun->flags & CTL_LUN_DISABLED) {
1431 		mtx_unlock(&lun->lun_lock);
1432 		return;
1433 	}
1434 	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
1435 		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) ==
1436 		    msg->mode.page_code &&
1437 		    lun->mode_pages.index[i].subpage == msg->mode.subpage)
1438 			break;
1439 	}
1440 	if (i == CTL_NUM_MODE_PAGES) {
1441 		mtx_unlock(&lun->lun_lock);
1442 		return;
1443 	}
1444 	memcpy(lun->mode_pages.index[i].page_data, msg->mode.data,
1445 	    min(lun->mode_pages.index[i].page_len, msg->mode.page_len));
1446 	initidx = ctl_get_initindex(&msg->hdr.nexus);
1447 	if (initidx != -1)
1448 		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
1449 	mtx_unlock(&lun->lun_lock);
1450 }
1451 
1452 /*
1453  * ISC (Inter Shelf Communication) event handler.  Events from the HA
1454  * subsystem come in here.
1455  */
1456 static void
1457 ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
1458 {
1459 	struct ctl_softc *softc = control_softc;
1460 	union ctl_io *io;
1461 	struct ctl_prio *presio;
1462 	ctl_ha_status isc_status;
1463 
1464 	CTL_DEBUG_PRINT(("CTL: Isc Msg event %d\n", event));
1465 	if (event == CTL_HA_EVT_MSG_RECV) {
1466 		union ctl_ha_msg *msg, msgbuf;
1467 
1468 		if (param > sizeof(msgbuf))
1469 			msg = malloc(param, M_CTL, M_WAITOK);
1470 		else
1471 			msg = &msgbuf;
1472 		isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, msg, param,
1473 		    M_WAITOK);
1474 		if (isc_status != CTL_HA_STATUS_SUCCESS) {
1475 			printf("%s: Error receiving message: %d\n",
1476 			    __func__, isc_status);
1477 			if (msg != &msgbuf)
1478 				free(msg, M_CTL);
1479 			return;
1480 		}
1481 
1482 		CTL_DEBUG_PRINT(("CTL: msg_type %d len %d\n",
1483 		    msg->hdr.msg_type, param));
1484 		switch (msg->hdr.msg_type) {
1485 		case CTL_MSG_SERIALIZE:
1486 			io = ctl_alloc_io(softc->othersc_pool);
1487 			ctl_zero_io(io);
1488 			// populate ctsio from msg
1489 			io->io_hdr.io_type = CTL_IO_SCSI;
1490 			io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
1491 			io->io_hdr.remote_io = msg->hdr.original_sc;
1492 			io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
1493 					    CTL_FLAG_IO_ACTIVE;
1494 			/*
1495 			 * If we're in serialization-only mode, we don't
1496 			 * want to go through full done processing.  Thus
1497 			 * the COPY flag.
1498 			 *
1499 			 * XXX KDM add another flag that is more specific.
1500 			 */
1501 			if (softc->ha_mode != CTL_HA_MODE_XFER)
1502 				io->io_hdr.flags |= CTL_FLAG_INT_COPY;
1503 			io->io_hdr.nexus = msg->hdr.nexus;
1504 			io->scsiio.priority = msg->scsi.priority;
1505 			io->scsiio.tag_num = msg->scsi.tag_num;
1506 			io->scsiio.tag_type = msg->scsi.tag_type;
1507 #ifdef CTL_TIME_IO
1508 			io->io_hdr.start_time = time_uptime;
1509 			getbinuptime(&io->io_hdr.start_bt);
1510 #endif /* CTL_TIME_IO */
1511 			io->scsiio.cdb_len = msg->scsi.cdb_len;
1512 			memcpy(io->scsiio.cdb, msg->scsi.cdb,
1513 			       CTL_MAX_CDBLEN);
1514 			if (softc->ha_mode == CTL_HA_MODE_XFER) {
1515 				const struct ctl_cmd_entry *entry;
1516 
1517 				entry = ctl_get_cmd_entry(&io->scsiio, NULL);
1518 				io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
1519 				io->io_hdr.flags |=
1520 					entry->flags & CTL_FLAG_DATA_MASK;
1521 			}
1522 			ctl_enqueue_isc(io);
1523 			break;
1524 
1525 		/* Performed on the Originating SC, XFER mode only */
1526 		case CTL_MSG_DATAMOVE: {
1527 			struct ctl_sg_entry *sgl;
1528 			int i, j;
1529 
1530 			io = msg->hdr.original_sc;
1531 			if (io == NULL) {
1532 				printf("%s: original_sc == NULL!\n", __func__);
1533 				/* XXX KDM do something here */
1534 				break;
1535 			}
1536 			CTL_IO_ASSERT(io, SCSI);
1537 
1538 			io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
1539 			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1540 			/*
1541 			 * Keep track of this, we need to send it back over
1542 			 * when the datamove is complete.
1543 			 */
1544 			io->io_hdr.remote_io = msg->hdr.serializing_sc;
1545 			if (msg->hdr.status == CTL_SUCCESS)
1546 				io->io_hdr.status = msg->hdr.status;
1547 
1548 			if (msg->dt.sg_sequence == 0) {
1549 #ifdef CTL_TIME_IO
1550 				getbinuptime(&io->io_hdr.dma_start_bt);
1551 #endif
1552 				i = msg->dt.kern_sg_entries +
1553 				    msg->dt.kern_data_len /
1554 				    CTL_HA_DATAMOVE_SEGMENT + 1;
1555 				sgl = malloc(sizeof(*sgl) * i, M_CTL,
1556 				    M_WAITOK | M_ZERO);
1557 				CTL_RSGL(io) = sgl;
1558 				CTL_LSGL(io) = &sgl[msg->dt.kern_sg_entries];
1559 
1560 				io->scsiio.kern_data_ptr = (uint8_t *)sgl;
1561 
1562 				io->scsiio.kern_sg_entries =
1563 					msg->dt.kern_sg_entries;
1564 				io->scsiio.rem_sg_entries =
1565 					msg->dt.kern_sg_entries;
1566 				io->scsiio.kern_data_len =
1567 					msg->dt.kern_data_len;
1568 				io->scsiio.kern_total_len =
1569 					msg->dt.kern_total_len;
1570 				io->scsiio.kern_data_resid =
1571 					msg->dt.kern_data_resid;
1572 				io->scsiio.kern_rel_offset =
1573 					msg->dt.kern_rel_offset;
1574 				io->io_hdr.flags &= ~CTL_FLAG_BUS_ADDR;
1575 				io->io_hdr.flags |= msg->dt.flags &
1576 				    CTL_FLAG_BUS_ADDR;
1577 			} else
1578 				sgl = (struct ctl_sg_entry *)
1579 					io->scsiio.kern_data_ptr;
1580 
1581 			for (i = msg->dt.sent_sg_entries, j = 0;
1582 			     i < (msg->dt.sent_sg_entries +
1583 			     msg->dt.cur_sg_entries); i++, j++) {
1584 				sgl[i].addr = msg->dt.sg_list[j].addr;
1585 				sgl[i].len = msg->dt.sg_list[j].len;
1586 			}
1587 
1588 			/*
1589 			 * If this is the last piece of the I/O, we've got
1590 			 * the full S/G list.  Queue processing in the thread.
1591 			 * Otherwise wait for the next piece.
1592 			 */
1593 			if (msg->dt.sg_last != 0)
1594 				ctl_enqueue_isc(io);
1595 			break;
1596 		}
1597 		/* Performed on the Serializing (primary) SC, XFER mode only */
1598 		case CTL_MSG_DATAMOVE_DONE: {
1599 			if (msg->hdr.serializing_sc == NULL) {
1600 				printf("%s: serializing_sc == NULL!\n",
1601 				       __func__);
1602 				/* XXX KDM now what? */
1603 				break;
1604 			}
1605 			/*
1606 			 * We grab the sense information here in case
1607 			 * there was a failure, so we can return status
1608 			 * back to the initiator.
1609 			 */
1610 			io = msg->hdr.serializing_sc;
1611 			CTL_IO_ASSERT(io, SCSI);
1612 
1613 			io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
1614 			io->io_hdr.flags &= ~CTL_FLAG_DMA_INPROG;
1615 			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1616 			io->io_hdr.port_status = msg->scsi.port_status;
1617 			io->scsiio.kern_data_resid = msg->scsi.kern_data_resid;
1618 			if (msg->hdr.status != CTL_STATUS_NONE) {
1619 				io->io_hdr.status = msg->hdr.status;
1620 				io->scsiio.scsi_status = msg->scsi.scsi_status;
1621 				io->scsiio.sense_len = msg->scsi.sense_len;
1622 				memcpy(&io->scsiio.sense_data,
1623 				    &msg->scsi.sense_data,
1624 				    msg->scsi.sense_len);
1625 				if (msg->hdr.status == CTL_SUCCESS)
1626 					io->io_hdr.flags |= CTL_FLAG_STATUS_SENT;
1627 			}
1628 			ctl_enqueue_isc(io);
1629 			break;
1630 		}
1631 
1632 		/* Preformed on Originating SC, SER_ONLY mode */
1633 		case CTL_MSG_R2R:
1634 			io = msg->hdr.original_sc;
1635 			if (io == NULL) {
1636 				printf("%s: original_sc == NULL!\n",
1637 				    __func__);
1638 				break;
1639 			}
1640 			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1641 			io->io_hdr.msg_type = CTL_MSG_R2R;
1642 			io->io_hdr.remote_io = msg->hdr.serializing_sc;
1643 			ctl_enqueue_isc(io);
1644 			break;
1645 
1646 		/*
1647 		 * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
1648 		 * mode.
1649 		 * Performed on the Originating (i.e. secondary) SC in XFER
1650 		 * mode
1651 		 */
1652 		case CTL_MSG_FINISH_IO:
1653 			if (softc->ha_mode == CTL_HA_MODE_XFER)
1654 				ctl_isc_handler_finish_xfer(softc, msg);
1655 			else
1656 				ctl_isc_handler_finish_ser_only(softc, msg);
1657 			break;
1658 
1659 		/* Preformed on Originating SC */
1660 		case CTL_MSG_BAD_JUJU:
1661 			io = msg->hdr.original_sc;
1662 			if (io == NULL) {
1663 				printf("%s: Bad JUJU!, original_sc is NULL!\n",
1664 				       __func__);
1665 				break;
1666 			}
1667 			ctl_copy_sense_data(msg, io);
1668 			/*
1669 			 * IO should have already been cleaned up on other
1670 			 * SC so clear this flag so we won't send a message
1671 			 * back to finish the IO there.
1672 			 */
1673 			io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
1674 			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1675 
1676 			/* io = msg->hdr.serializing_sc; */
1677 			io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
1678 			ctl_enqueue_isc(io);
1679 			break;
1680 
1681 		/* Handle resets sent from the other side */
1682 		case CTL_MSG_MANAGE_TASKS: {
1683 			struct ctl_taskio *taskio;
1684 			taskio = (struct ctl_taskio *)ctl_alloc_io(
1685 			    softc->othersc_pool);
1686 			ctl_zero_io((union ctl_io *)taskio);
1687 			taskio->io_hdr.io_type = CTL_IO_TASK;
1688 			taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1689 			taskio->io_hdr.nexus = msg->hdr.nexus;
1690 			taskio->task_action = msg->task.task_action;
1691 			taskio->tag_num = msg->task.tag_num;
1692 			taskio->tag_type = msg->task.tag_type;
1693 #ifdef CTL_TIME_IO
1694 			taskio->io_hdr.start_time = time_uptime;
1695 			getbinuptime(&taskio->io_hdr.start_bt);
1696 #endif /* CTL_TIME_IO */
1697 			ctl_run_task((union ctl_io *)taskio);
1698 			break;
1699 		}
1700 		/* Persistent Reserve action which needs attention */
1701 		case CTL_MSG_PERS_ACTION:
1702 			presio = (struct ctl_prio *)ctl_alloc_io(
1703 			    softc->othersc_pool);
1704 			ctl_zero_io((union ctl_io *)presio);
1705 			presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
1706 			presio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1707 			presio->io_hdr.nexus = msg->hdr.nexus;
1708 			presio->pr_msg = msg->pr;
1709 			ctl_enqueue_isc((union ctl_io *)presio);
1710 			break;
1711 		case CTL_MSG_UA:
1712 			ctl_isc_ua(softc, msg, param);
1713 			break;
1714 		case CTL_MSG_PORT_SYNC:
1715 			ctl_isc_port_sync(softc, msg, param);
1716 			break;
1717 		case CTL_MSG_LUN_SYNC:
1718 			ctl_isc_lun_sync(softc, msg, param);
1719 			break;
1720 		case CTL_MSG_IID_SYNC:
1721 			ctl_isc_iid_sync(softc, msg, param);
1722 			break;
1723 		case CTL_MSG_LOGIN:
1724 			ctl_isc_login(softc, msg, param);
1725 			break;
1726 		case CTL_MSG_MODE_SYNC:
1727 			ctl_isc_mode_sync(softc, msg, param);
1728 			break;
1729 		default:
1730 			printf("Received HA message of unknown type %d\n",
1731 			    msg->hdr.msg_type);
1732 			ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1733 			break;
1734 		}
1735 		if (msg != &msgbuf)
1736 			free(msg, M_CTL);
1737 	} else if (event == CTL_HA_EVT_LINK_CHANGE) {
1738 		printf("CTL: HA link status changed from %d to %d\n",
1739 		    softc->ha_link, param);
1740 		if (param == softc->ha_link)
1741 			return;
1742 		if (softc->ha_link == CTL_HA_LINK_ONLINE) {
1743 			softc->ha_link = param;
1744 			ctl_isc_ha_link_down(softc);
1745 		} else {
1746 			softc->ha_link = param;
1747 			if (softc->ha_link == CTL_HA_LINK_ONLINE)
1748 				ctl_isc_ha_link_up(softc);
1749 		}
1750 		return;
1751 	} else {
1752 		printf("ctl_isc_event_handler: Unknown event %d\n", event);
1753 		return;
1754 	}
1755 }
1756 
1757 static void
1758 ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
1759 {
1760 
1761 	memcpy(&dest->scsiio.sense_data, &src->scsi.sense_data,
1762 	    src->scsi.sense_len);
1763 	dest->scsiio.scsi_status = src->scsi.scsi_status;
1764 	dest->scsiio.sense_len = src->scsi.sense_len;
1765 	dest->io_hdr.status = src->hdr.status;
1766 }
1767 
1768 static void
1769 ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest)
1770 {
1771 
1772 	memcpy(&dest->scsi.sense_data, &src->scsiio.sense_data,
1773 	    src->scsiio.sense_len);
1774 	dest->scsi.scsi_status = src->scsiio.scsi_status;
1775 	dest->scsi.sense_len = src->scsiio.sense_len;
1776 	dest->hdr.status = src->io_hdr.status;
1777 }
1778 
1779 void
1780 ctl_est_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_est_ua_port(struct ctl_lun *lun, int port, uint32_t except, ctl_ua_type ua)
1796 {
1797 	int i;
1798 
1799 	mtx_assert(&lun->lun_lock, MA_OWNED);
1800 	if (lun->pending_ua[port] == NULL)
1801 		return;
1802 	for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1803 		if (port * CTL_MAX_INIT_PER_PORT + i == except)
1804 			continue;
1805 		lun->pending_ua[port][i] |= ua;
1806 	}
1807 }
1808 
1809 void
1810 ctl_est_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1811 {
1812 	struct ctl_softc *softc = lun->ctl_softc;
1813 	int i;
1814 
1815 	mtx_assert(&lun->lun_lock, MA_OWNED);
1816 	for (i = softc->port_min; i < softc->port_max; i++)
1817 		ctl_est_ua_port(lun, i, except, ua);
1818 }
1819 
1820 void
1821 ctl_clr_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1822 {
1823 	struct ctl_softc *softc = lun->ctl_softc;
1824 	ctl_ua_type *pu;
1825 
1826 	if (initidx < softc->init_min || initidx >= softc->init_max)
1827 		return;
1828 	mtx_assert(&lun->lun_lock, MA_OWNED);
1829 	pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1830 	if (pu == NULL)
1831 		return;
1832 	pu[initidx % CTL_MAX_INIT_PER_PORT] &= ~ua;
1833 }
1834 
1835 void
1836 ctl_clr_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1837 {
1838 	struct ctl_softc *softc = lun->ctl_softc;
1839 	int i, j;
1840 
1841 	mtx_assert(&lun->lun_lock, MA_OWNED);
1842 	for (i = softc->port_min; i < softc->port_max; i++) {
1843 		if (lun->pending_ua[i] == NULL)
1844 			continue;
1845 		for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
1846 			if (i * CTL_MAX_INIT_PER_PORT + j == except)
1847 				continue;
1848 			lun->pending_ua[i][j] &= ~ua;
1849 		}
1850 	}
1851 }
1852 
1853 void
1854 ctl_clr_ua_allluns(struct ctl_softc *ctl_softc, uint32_t initidx,
1855     ctl_ua_type ua_type)
1856 {
1857 	struct ctl_lun *lun;
1858 
1859 	mtx_assert(&ctl_softc->ctl_lock, MA_OWNED);
1860 	STAILQ_FOREACH(lun, &ctl_softc->lun_list, links) {
1861 		mtx_lock(&lun->lun_lock);
1862 		ctl_clr_ua(lun, initidx, ua_type);
1863 		mtx_unlock(&lun->lun_lock);
1864 	}
1865 }
1866 
1867 static int
1868 ctl_ha_role_sysctl(SYSCTL_HANDLER_ARGS)
1869 {
1870 	struct ctl_softc *softc = (struct ctl_softc *)arg1;
1871 	struct ctl_lun *lun;
1872 	struct ctl_lun_req ireq;
1873 	int error, value;
1874 
1875 	value = (softc->flags & CTL_FLAG_ACTIVE_SHELF) ? 0 : 1;
1876 	error = sysctl_handle_int(oidp, &value, 0, req);
1877 	if ((error != 0) || (req->newptr == NULL))
1878 		return (error);
1879 
1880 	mtx_lock(&softc->ctl_lock);
1881 	if (value == 0)
1882 		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1883 	else
1884 		softc->flags &= ~CTL_FLAG_ACTIVE_SHELF;
1885 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
1886 		mtx_unlock(&softc->ctl_lock);
1887 		bzero(&ireq, sizeof(ireq));
1888 		ireq.reqtype = CTL_LUNREQ_MODIFY;
1889 		ireq.reqdata.modify.lun_id = lun->lun;
1890 		lun->backend->ioctl(NULL, CTL_LUN_REQ, (caddr_t)&ireq, 0,
1891 		    curthread);
1892 		if (ireq.status != CTL_LUN_OK) {
1893 			printf("%s: CTL_LUNREQ_MODIFY returned %d '%s'\n",
1894 			    __func__, ireq.status, ireq.error_str);
1895 		}
1896 		mtx_lock(&softc->ctl_lock);
1897 	}
1898 	mtx_unlock(&softc->ctl_lock);
1899 	return (0);
1900 }
1901 
1902 static int
1903 ctl_init(void)
1904 {
1905 	struct make_dev_args args;
1906 	struct ctl_softc *softc;
1907 	int i, error;
1908 
1909 	softc = control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
1910 			       M_WAITOK | M_ZERO);
1911 
1912 	make_dev_args_init(&args);
1913 	args.mda_devsw = &ctl_cdevsw;
1914 	args.mda_uid = UID_ROOT;
1915 	args.mda_gid = GID_OPERATOR;
1916 	args.mda_mode = 0600;
1917 	args.mda_si_drv1 = softc;
1918 	args.mda_si_drv2 = NULL;
1919 	error = make_dev_s(&args, &softc->dev, "cam/ctl");
1920 	if (error != 0) {
1921 		free(softc, M_DEVBUF);
1922 		control_softc = NULL;
1923 		return (error);
1924 	}
1925 
1926 	sysctl_ctx_init(&softc->sysctl_ctx);
1927 	softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
1928 		SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
1929 		CTLFLAG_RD | CTLFLAG_MPSAFE, 0, "CAM Target Layer");
1930 
1931 	if (softc->sysctl_tree == NULL) {
1932 		printf("%s: unable to allocate sysctl tree\n", __func__);
1933 		destroy_dev(softc->dev);
1934 		free(softc, M_DEVBUF);
1935 		control_softc = NULL;
1936 		return (ENOMEM);
1937 	}
1938 
1939 	mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
1940 	softc->io_zone = uma_zcreate("CTL IO", sizeof(union ctl_io),
1941 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1942 	softc->flags = 0;
1943 
1944 	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1945 	    OID_AUTO, "ha_mode", CTLFLAG_RDTUN, (int *)&softc->ha_mode, 0,
1946 	    "HA mode (0 - act/stby, 1 - serialize only, 2 - xfer)");
1947 
1948 	if (ctl_max_luns <= 0 || powerof2(ctl_max_luns) == 0) {
1949 		printf("Bad value %d for kern.cam.ctl.max_luns, must be a power of two, using %d\n",
1950 		    ctl_max_luns, CTL_DEFAULT_MAX_LUNS);
1951 		ctl_max_luns = CTL_DEFAULT_MAX_LUNS;
1952 	}
1953 	softc->ctl_luns = malloc(sizeof(struct ctl_lun *) * ctl_max_luns,
1954 	    M_DEVBUF, M_WAITOK | M_ZERO);
1955 	softc->ctl_lun_mask = malloc(sizeof(uint32_t) *
1956 	    ((ctl_max_luns + 31) / 32), M_DEVBUF, M_WAITOK | M_ZERO);
1957 	if (ctl_max_ports <= 0 || powerof2(ctl_max_ports) == 0) {
1958 		printf("Bad value %d for kern.cam.ctl.max_ports, must be a power of two, using %d\n",
1959 		    ctl_max_ports, CTL_DEFAULT_MAX_PORTS);
1960 		ctl_max_ports = CTL_DEFAULT_MAX_PORTS;
1961 	}
1962 	softc->ctl_port_mask = malloc(sizeof(uint32_t) *
1963 	  ((ctl_max_ports + 31) / 32), M_DEVBUF, M_WAITOK | M_ZERO);
1964 	softc->ctl_ports = malloc(sizeof(struct ctl_port *) * ctl_max_ports,
1965 	     M_DEVBUF, M_WAITOK | M_ZERO);
1966 
1967 	/*
1968 	 * In Copan's HA scheme, the "master" and "slave" roles are
1969 	 * figured out through the slot the controller is in.  Although it
1970 	 * is an active/active system, someone has to be in charge.
1971 	 */
1972 	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1973 	    OID_AUTO, "ha_id", CTLFLAG_RDTUN, &softc->ha_id, 0,
1974 	    "HA head ID (0 - no HA)");
1975 	if (softc->ha_id == 0 || softc->ha_id > NUM_HA_SHELVES) {
1976 		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1977 		softc->is_single = 1;
1978 		softc->port_cnt = ctl_max_ports;
1979 		softc->port_min = 0;
1980 	} else {
1981 		softc->port_cnt = ctl_max_ports / NUM_HA_SHELVES;
1982 		softc->port_min = (softc->ha_id - 1) * softc->port_cnt;
1983 	}
1984 	softc->port_max = softc->port_min + softc->port_cnt;
1985 	softc->init_min = softc->port_min * CTL_MAX_INIT_PER_PORT;
1986 	softc->init_max = softc->port_max * CTL_MAX_INIT_PER_PORT;
1987 
1988 	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1989 	    OID_AUTO, "ha_link", CTLFLAG_RD, (int *)&softc->ha_link, 0,
1990 	    "HA link state (0 - offline, 1 - unknown, 2 - online)");
1991 
1992 	STAILQ_INIT(&softc->lun_list);
1993 	STAILQ_INIT(&softc->fe_list);
1994 	STAILQ_INIT(&softc->port_list);
1995 	STAILQ_INIT(&softc->be_list);
1996 	ctl_tpc_init(softc);
1997 
1998 	if (worker_threads <= 0)
1999 		worker_threads = max(1, mp_ncpus / 4);
2000 	if (worker_threads > CTL_MAX_THREADS)
2001 		worker_threads = CTL_MAX_THREADS;
2002 
2003 	for (i = 0; i < worker_threads; i++) {
2004 		struct ctl_thread *thr = &softc->threads[i];
2005 
2006 		mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
2007 		thr->ctl_softc = softc;
2008 		STAILQ_INIT(&thr->incoming_queue);
2009 		STAILQ_INIT(&thr->rtr_queue);
2010 		STAILQ_INIT(&thr->done_queue);
2011 		STAILQ_INIT(&thr->isc_queue);
2012 
2013 		error = kproc_kthread_add(ctl_work_thread, thr,
2014 		    &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
2015 		if (error != 0) {
2016 			printf("error creating CTL work thread!\n");
2017 			return (error);
2018 		}
2019 	}
2020 	error = kproc_kthread_add(ctl_thresh_thread, softc,
2021 	    &softc->ctl_proc, &softc->thresh_thread, 0, 0, "ctl", "thresh");
2022 	if (error != 0) {
2023 		printf("error creating CTL threshold thread!\n");
2024 		return (error);
2025 	}
2026 
2027 	SYSCTL_ADD_PROC(&softc->sysctl_ctx,SYSCTL_CHILDREN(softc->sysctl_tree),
2028 	    OID_AUTO, "ha_role",
2029 	    CTLTYPE_INT | CTLFLAG_RWTUN | CTLFLAG_MPSAFE,
2030 	    softc, 0, ctl_ha_role_sysctl, "I", "HA role for this head");
2031 
2032 	if (softc->is_single == 0) {
2033 		if (ctl_frontend_register(&ha_frontend) != 0)
2034 			softc->is_single = 1;
2035 	}
2036 	return (0);
2037 }
2038 
2039 static int
2040 ctl_shutdown(void)
2041 {
2042 	struct ctl_softc *softc = control_softc;
2043 	int i;
2044 
2045 	if (softc->is_single == 0)
2046 		ctl_frontend_deregister(&ha_frontend);
2047 
2048 	destroy_dev(softc->dev);
2049 
2050 	/* Shutdown CTL threads. */
2051 	softc->shutdown = 1;
2052 	for (i = 0; i < worker_threads; i++) {
2053 		struct ctl_thread *thr = &softc->threads[i];
2054 		while (thr->thread != NULL) {
2055 			wakeup(thr);
2056 			if (thr->thread != NULL)
2057 				pause("CTL thr shutdown", 1);
2058 		}
2059 		mtx_destroy(&thr->queue_lock);
2060 	}
2061 	while (softc->thresh_thread != NULL) {
2062 		wakeup(softc->thresh_thread);
2063 		if (softc->thresh_thread != NULL)
2064 			pause("CTL thr shutdown", 1);
2065 	}
2066 
2067 	ctl_tpc_shutdown(softc);
2068 	uma_zdestroy(softc->io_zone);
2069 	mtx_destroy(&softc->ctl_lock);
2070 
2071 	free(softc->ctl_luns, M_DEVBUF);
2072 	free(softc->ctl_lun_mask, M_DEVBUF);
2073 	free(softc->ctl_port_mask, M_DEVBUF);
2074 	free(softc->ctl_ports, M_DEVBUF);
2075 
2076 	sysctl_ctx_free(&softc->sysctl_ctx);
2077 
2078 	free(softc, M_DEVBUF);
2079 	control_softc = NULL;
2080 	return (0);
2081 }
2082 
2083 static int
2084 ctl_module_event_handler(module_t mod, int what, void *arg)
2085 {
2086 
2087 	switch (what) {
2088 	case MOD_LOAD:
2089 		return (ctl_init());
2090 	case MOD_UNLOAD:
2091 		return (ctl_shutdown());
2092 	default:
2093 		return (EOPNOTSUPP);
2094 	}
2095 }
2096 
2097 /*
2098  * XXX KDM should we do some access checks here?  Bump a reference count to
2099  * prevent a CTL module from being unloaded while someone has it open?
2100  */
2101 static int
2102 ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
2103 {
2104 	return (0);
2105 }
2106 
2107 static int
2108 ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
2109 {
2110 	return (0);
2111 }
2112 
2113 /*
2114  * Remove an initiator by port number and initiator ID.
2115  * Returns 0 for success, -1 for failure.
2116  */
2117 int
2118 ctl_remove_initiator(struct ctl_port *port, int iid)
2119 {
2120 	struct ctl_softc *softc = port->ctl_softc;
2121 	int last;
2122 
2123 	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
2124 
2125 	if (iid > CTL_MAX_INIT_PER_PORT) {
2126 		printf("%s: initiator ID %u > maximun %u!\n",
2127 		       __func__, iid, CTL_MAX_INIT_PER_PORT);
2128 		return (-1);
2129 	}
2130 
2131 	mtx_lock(&softc->ctl_lock);
2132 	last = (--port->wwpn_iid[iid].in_use == 0);
2133 	port->wwpn_iid[iid].last_use = time_uptime;
2134 	mtx_unlock(&softc->ctl_lock);
2135 	if (last)
2136 		ctl_i_t_nexus_loss(softc, iid, CTL_UA_POWERON);
2137 	ctl_isc_announce_iid(port, iid);
2138 
2139 	return (0);
2140 }
2141 
2142 /*
2143  * Add an initiator to the initiator map.
2144  * Returns iid for success, < 0 for failure.
2145  */
2146 int
2147 ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
2148 {
2149 	struct ctl_softc *softc = port->ctl_softc;
2150 	time_t best_time;
2151 	int i, best;
2152 
2153 	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
2154 
2155 	if (iid >= CTL_MAX_INIT_PER_PORT) {
2156 		printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
2157 		       __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
2158 		free(name, M_CTL);
2159 		return (-1);
2160 	}
2161 
2162 	mtx_lock(&softc->ctl_lock);
2163 
2164 	if (iid < 0 && (wwpn != 0 || name != NULL)) {
2165 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2166 			if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
2167 				iid = i;
2168 				break;
2169 			}
2170 			if (name != NULL && port->wwpn_iid[i].name != NULL &&
2171 			    strcmp(name, port->wwpn_iid[i].name) == 0) {
2172 				iid = i;
2173 				break;
2174 			}
2175 		}
2176 	}
2177 
2178 	if (iid < 0) {
2179 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2180 			if (port->wwpn_iid[i].in_use == 0 &&
2181 			    port->wwpn_iid[i].wwpn == 0 &&
2182 			    port->wwpn_iid[i].name == NULL) {
2183 				iid = i;
2184 				break;
2185 			}
2186 		}
2187 	}
2188 
2189 	if (iid < 0) {
2190 		best = -1;
2191 		best_time = INT32_MAX;
2192 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2193 			if (port->wwpn_iid[i].in_use == 0) {
2194 				if (port->wwpn_iid[i].last_use < best_time) {
2195 					best = i;
2196 					best_time = port->wwpn_iid[i].last_use;
2197 				}
2198 			}
2199 		}
2200 		iid = best;
2201 	}
2202 
2203 	if (iid < 0) {
2204 		mtx_unlock(&softc->ctl_lock);
2205 		free(name, M_CTL);
2206 		return (-2);
2207 	}
2208 
2209 	if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
2210 		/*
2211 		 * This is not an error yet.
2212 		 */
2213 		if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
2214 #if 0
2215 			printf("%s: port %d iid %u WWPN %#jx arrived"
2216 			    " again\n", __func__, port->targ_port,
2217 			    iid, (uintmax_t)wwpn);
2218 #endif
2219 			goto take;
2220 		}
2221 		if (name != NULL && port->wwpn_iid[iid].name != NULL &&
2222 		    strcmp(name, port->wwpn_iid[iid].name) == 0) {
2223 #if 0
2224 			printf("%s: port %d iid %u name '%s' arrived"
2225 			    " again\n", __func__, port->targ_port,
2226 			    iid, name);
2227 #endif
2228 			goto take;
2229 		}
2230 
2231 		/*
2232 		 * This is an error, but what do we do about it?  The
2233 		 * driver is telling us we have a new WWPN for this
2234 		 * initiator ID, so we pretty much need to use it.
2235 		 */
2236 		printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
2237 		    " but WWPN %#jx '%s' is still at that address\n",
2238 		    __func__, port->targ_port, iid, wwpn, name,
2239 		    (uintmax_t)port->wwpn_iid[iid].wwpn,
2240 		    port->wwpn_iid[iid].name);
2241 	}
2242 take:
2243 	free(port->wwpn_iid[iid].name, M_CTL);
2244 	port->wwpn_iid[iid].name = name;
2245 	port->wwpn_iid[iid].wwpn = wwpn;
2246 	port->wwpn_iid[iid].in_use++;
2247 	mtx_unlock(&softc->ctl_lock);
2248 	ctl_isc_announce_iid(port, iid);
2249 
2250 	return (iid);
2251 }
2252 
2253 static int
2254 ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
2255 {
2256 	int len;
2257 
2258 	switch (port->port_type) {
2259 	case CTL_PORT_FC:
2260 	{
2261 		struct scsi_transportid_fcp *id =
2262 		    (struct scsi_transportid_fcp *)buf;
2263 		if (port->wwpn_iid[iid].wwpn == 0)
2264 			return (0);
2265 		memset(id, 0, sizeof(*id));
2266 		id->format_protocol = SCSI_PROTO_FC;
2267 		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
2268 		return (sizeof(*id));
2269 	}
2270 	case CTL_PORT_ISCSI:
2271 	{
2272 		struct scsi_transportid_iscsi_port *id =
2273 		    (struct scsi_transportid_iscsi_port *)buf;
2274 		if (port->wwpn_iid[iid].name == NULL)
2275 			return (0);
2276 		memset(id, 0, 256);
2277 		id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
2278 		    SCSI_PROTO_ISCSI;
2279 		len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
2280 		len = roundup2(min(len, 252), 4);
2281 		scsi_ulto2b(len, id->additional_length);
2282 		return (sizeof(*id) + len);
2283 	}
2284 	case CTL_PORT_SAS:
2285 	{
2286 		struct scsi_transportid_sas *id =
2287 		    (struct scsi_transportid_sas *)buf;
2288 		if (port->wwpn_iid[iid].wwpn == 0)
2289 			return (0);
2290 		memset(id, 0, sizeof(*id));
2291 		id->format_protocol = SCSI_PROTO_SAS;
2292 		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
2293 		return (sizeof(*id));
2294 	}
2295 	default:
2296 	{
2297 		struct scsi_transportid_spi *id =
2298 		    (struct scsi_transportid_spi *)buf;
2299 		memset(id, 0, sizeof(*id));
2300 		id->format_protocol = SCSI_PROTO_SPI;
2301 		scsi_ulto2b(iid, id->scsi_addr);
2302 		scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
2303 		return (sizeof(*id));
2304 	}
2305 	}
2306 }
2307 
2308 /*
2309  * Serialize a command that went down the "wrong" side, and so was sent to
2310  * this controller for execution.  The logic is a little different than the
2311  * standard case in ctl_scsiio_precheck().  Errors in this case need to get
2312  * sent back to the other side, but in the success case, we execute the
2313  * command on this side (XFER mode) or tell the other side to execute it
2314  * (SER_ONLY mode).
2315  */
2316 static void
2317 ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
2318 {
2319 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
2320 	struct ctl_port *port = CTL_PORT(ctsio);
2321 	union ctl_ha_msg msg_info;
2322 	struct ctl_lun *lun;
2323 	const struct ctl_cmd_entry *entry;
2324 	union ctl_io *bio;
2325 	uint32_t targ_lun;
2326 
2327 	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
2328 
2329 	/* Make sure that we know about this port. */
2330 	if (port == NULL || (port->status & CTL_PORT_STATUS_ONLINE) == 0) {
2331 		ctl_set_internal_failure(ctsio, /*sks_valid*/ 0,
2332 					 /*retry_count*/ 1);
2333 		goto badjuju;
2334 	}
2335 
2336 	/* Make sure that we know about this LUN. */
2337 	mtx_lock(&softc->ctl_lock);
2338 	if (targ_lun >= ctl_max_luns ||
2339 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
2340 		mtx_unlock(&softc->ctl_lock);
2341 
2342 		/*
2343 		 * The other node would not send this request to us unless
2344 		 * received announce that we are primary node for this LUN.
2345 		 * If this LUN does not exist now, it is probably result of
2346 		 * a race, so respond to initiator in the most opaque way.
2347 		 */
2348 		ctl_set_busy(ctsio);
2349 		goto badjuju;
2350 	}
2351 	mtx_lock(&lun->lun_lock);
2352 	mtx_unlock(&softc->ctl_lock);
2353 
2354 	/*
2355 	 * If the LUN is invalid, pretend that it doesn't exist.
2356 	 * It will go away as soon as all pending I/Os completed.
2357 	 */
2358 	if (lun->flags & CTL_LUN_DISABLED) {
2359 		mtx_unlock(&lun->lun_lock);
2360 		ctl_set_busy(ctsio);
2361 		goto badjuju;
2362 	}
2363 
2364 	entry = ctl_get_cmd_entry(ctsio, NULL);
2365 	ctsio->seridx = entry->seridx;
2366 	if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
2367 		mtx_unlock(&lun->lun_lock);
2368 		goto badjuju;
2369 	}
2370 
2371 	CTL_LUN(ctsio) = lun;
2372 	CTL_BACKEND_LUN(ctsio) = lun->be_lun;
2373 
2374 	/*
2375 	 * Every I/O goes into the OOA queue for a
2376 	 * particular LUN, and stays there until completion.
2377 	 */
2378 #ifdef CTL_TIME_IO
2379 	if (LIST_EMPTY(&lun->ooa_queue))
2380 		lun->idle_time += getsbinuptime() - lun->last_busy;
2381 #endif
2382 	LIST_INSERT_HEAD(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2383 
2384 	bio = (union ctl_io *)LIST_NEXT(&ctsio->io_hdr, ooa_links);
2385 	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio, &bio)) {
2386 	case CTL_ACTION_PASS:
2387 	case CTL_ACTION_SKIP:
2388 		if (softc->ha_mode == CTL_HA_MODE_XFER) {
2389 			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
2390 			ctl_enqueue_rtr((union ctl_io *)ctsio);
2391 			mtx_unlock(&lun->lun_lock);
2392 		} else {
2393 			ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
2394 			mtx_unlock(&lun->lun_lock);
2395 
2396 			/* send msg back to other side */
2397 			msg_info.hdr.original_sc = ctsio->io_hdr.remote_io;
2398 			msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
2399 			msg_info.hdr.msg_type = CTL_MSG_R2R;
2400 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2401 			    sizeof(msg_info.hdr), M_WAITOK);
2402 		}
2403 		break;
2404 	case CTL_ACTION_BLOCK:
2405 		ctsio->io_hdr.blocker = bio;
2406 		TAILQ_INSERT_TAIL(&bio->io_hdr.blocked_queue, &ctsio->io_hdr,
2407 				  blocked_links);
2408 		mtx_unlock(&lun->lun_lock);
2409 		break;
2410 	case CTL_ACTION_OVERLAP:
2411 		LIST_REMOVE(&ctsio->io_hdr, ooa_links);
2412 		mtx_unlock(&lun->lun_lock);
2413 		ctl_set_overlapped_cmd(ctsio);
2414 		goto badjuju;
2415 	case CTL_ACTION_OVERLAP_TAG:
2416 		LIST_REMOVE(&ctsio->io_hdr, ooa_links);
2417 		mtx_unlock(&lun->lun_lock);
2418 		ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
2419 badjuju:
2420 		ctl_copy_sense_data_back((union ctl_io *)ctsio, &msg_info);
2421 		msg_info.hdr.original_sc = ctsio->io_hdr.remote_io;
2422 		msg_info.hdr.serializing_sc = NULL;
2423 		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
2424 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2425 		    sizeof(msg_info.scsi), M_WAITOK);
2426 		ctl_free_io((union ctl_io *)ctsio);
2427 		break;
2428 	default:
2429 		__assert_unreachable();
2430 	}
2431 }
2432 
2433 /*
2434  * Returns 0 for success, errno for failure.
2435  */
2436 static void
2437 ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2438 		   struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2439 {
2440 	struct ctl_io_hdr *ioh;
2441 
2442 	mtx_lock(&lun->lun_lock);
2443 	ioh = LIST_FIRST(&lun->ooa_queue);
2444 	if (ioh == NULL) {
2445 		mtx_unlock(&lun->lun_lock);
2446 		return;
2447 	}
2448 	while (LIST_NEXT(ioh, ooa_links) != NULL)
2449 		ioh = LIST_NEXT(ioh, ooa_links);
2450 	for ( ; ioh; ioh = LIST_PREV(ioh, &lun->ooa_queue, ctl_io_hdr, ooa_links)) {
2451 		union ctl_io *io = (union ctl_io *)ioh;
2452 		struct ctl_ooa_entry *entry;
2453 
2454 		CTL_IO_ASSERT(io, SCSI);
2455 
2456 		/*
2457 		 * If we've got more than we can fit, just count the
2458 		 * remaining entries.
2459 		 */
2460 		if (*cur_fill_num >= ooa_hdr->alloc_num) {
2461 			(*cur_fill_num)++;
2462 			continue;
2463 		}
2464 
2465 		entry = &kern_entries[*cur_fill_num];
2466 
2467 		entry->tag_num = io->scsiio.tag_num;
2468 		entry->tag_type = io->scsiio.tag_type;
2469 		entry->lun_num = lun->lun;
2470 #ifdef CTL_TIME_IO
2471 		entry->start_bt = io->io_hdr.start_bt;
2472 #endif
2473 		bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2474 		entry->cdb_len = io->scsiio.cdb_len;
2475 		if (io->io_hdr.blocker != NULL)
2476 			entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2477 
2478 		if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2479 			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2480 
2481 		if (io->io_hdr.flags & CTL_FLAG_ABORT)
2482 			entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2483 
2484 		if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2485 			entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2486 
2487 		if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2488 			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2489 
2490 		if (io->io_hdr.flags & CTL_FLAG_STATUS_QUEUED)
2491 			entry->cmd_flags |= CTL_OOACMD_FLAG_STATUS_QUEUED;
2492 
2493 		if (io->io_hdr.flags & CTL_FLAG_STATUS_SENT)
2494 			entry->cmd_flags |= CTL_OOACMD_FLAG_STATUS_SENT;
2495 		(*cur_fill_num)++;
2496 	}
2497 	mtx_unlock(&lun->lun_lock);
2498 }
2499 
2500 /*
2501  * Escape characters that are illegal or not recommended in XML.
2502  */
2503 int
2504 ctl_sbuf_printf_esc(struct sbuf *sb, char *str, int size)
2505 {
2506 	char *end = str + size;
2507 	int retval;
2508 
2509 	retval = 0;
2510 
2511 	for (; *str && str < end; str++) {
2512 		switch (*str) {
2513 		case '&':
2514 			retval = sbuf_cat(sb, "&amp;");
2515 			break;
2516 		case '>':
2517 			retval = sbuf_cat(sb, "&gt;");
2518 			break;
2519 		case '<':
2520 			retval = sbuf_cat(sb, "&lt;");
2521 			break;
2522 		default:
2523 			retval = sbuf_putc(sb, *str);
2524 			break;
2525 		}
2526 
2527 		if (retval != 0)
2528 			break;
2529 	}
2530 
2531 	return (retval);
2532 }
2533 
2534 static void
2535 ctl_id_sbuf(struct ctl_devid *id, struct sbuf *sb)
2536 {
2537 	struct scsi_vpd_id_descriptor *desc;
2538 	int i;
2539 
2540 	if (id == NULL || id->len < 4)
2541 		return;
2542 	desc = (struct scsi_vpd_id_descriptor *)id->data;
2543 	switch (desc->id_type & SVPD_ID_TYPE_MASK) {
2544 	case SVPD_ID_TYPE_T10:
2545 		sbuf_cat(sb, "t10.");
2546 		break;
2547 	case SVPD_ID_TYPE_EUI64:
2548 		sbuf_cat(sb, "eui.");
2549 		break;
2550 	case SVPD_ID_TYPE_NAA:
2551 		sbuf_cat(sb, "naa.");
2552 		break;
2553 	case SVPD_ID_TYPE_SCSI_NAME:
2554 		break;
2555 	}
2556 	switch (desc->proto_codeset & SVPD_ID_CODESET_MASK) {
2557 	case SVPD_ID_CODESET_BINARY:
2558 		for (i = 0; i < desc->length; i++)
2559 			sbuf_printf(sb, "%02x", desc->identifier[i]);
2560 		break;
2561 	case SVPD_ID_CODESET_ASCII:
2562 		sbuf_printf(sb, "%.*s", (int)desc->length,
2563 		    (char *)desc->identifier);
2564 		break;
2565 	case SVPD_ID_CODESET_UTF8:
2566 		sbuf_cat(sb, (char *)desc->identifier);
2567 		break;
2568 	}
2569 }
2570 
2571 static int
2572 ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2573 	  struct thread *td)
2574 {
2575 	struct ctl_softc *softc = dev->si_drv1;
2576 	struct ctl_port *port;
2577 	struct ctl_lun *lun;
2578 	int retval;
2579 
2580 	retval = 0;
2581 
2582 	switch (cmd) {
2583 	case CTL_IO:
2584 		retval = ctl_ioctl_io(dev, cmd, addr, flag, td);
2585 		break;
2586 	case CTL_ENABLE_PORT:
2587 	case CTL_DISABLE_PORT:
2588 	case CTL_SET_PORT_WWNS: {
2589 		struct ctl_port *port;
2590 		struct ctl_port_entry *entry;
2591 
2592 		entry = (struct ctl_port_entry *)addr;
2593 
2594 		mtx_lock(&softc->ctl_lock);
2595 		STAILQ_FOREACH(port, &softc->port_list, links) {
2596 			int action, done;
2597 
2598 			if (port->targ_port < softc->port_min ||
2599 			    port->targ_port >= softc->port_max)
2600 				continue;
2601 
2602 			action = 0;
2603 			done = 0;
2604 			if ((entry->port_type == CTL_PORT_NONE)
2605 			 && (entry->targ_port == port->targ_port)) {
2606 				/*
2607 				 * If the user only wants to enable or
2608 				 * disable or set WWNs on a specific port,
2609 				 * do the operation and we're done.
2610 				 */
2611 				action = 1;
2612 				done = 1;
2613 			} else if (entry->port_type & port->port_type) {
2614 				/*
2615 				 * Compare the user's type mask with the
2616 				 * particular frontend type to see if we
2617 				 * have a match.
2618 				 */
2619 				action = 1;
2620 				done = 0;
2621 
2622 				/*
2623 				 * Make sure the user isn't trying to set
2624 				 * WWNs on multiple ports at the same time.
2625 				 */
2626 				if (cmd == CTL_SET_PORT_WWNS) {
2627 					printf("%s: Can't set WWNs on "
2628 					       "multiple ports\n", __func__);
2629 					retval = EINVAL;
2630 					break;
2631 				}
2632 			}
2633 			if (action == 0)
2634 				continue;
2635 
2636 			/*
2637 			 * XXX KDM we have to drop the lock here, because
2638 			 * the online/offline operations can potentially
2639 			 * block.  We need to reference count the frontends
2640 			 * so they can't go away,
2641 			 */
2642 			if (cmd == CTL_ENABLE_PORT) {
2643 				mtx_unlock(&softc->ctl_lock);
2644 				ctl_port_online(port);
2645 				mtx_lock(&softc->ctl_lock);
2646 			} else if (cmd == CTL_DISABLE_PORT) {
2647 				mtx_unlock(&softc->ctl_lock);
2648 				ctl_port_offline(port);
2649 				mtx_lock(&softc->ctl_lock);
2650 			} else if (cmd == CTL_SET_PORT_WWNS) {
2651 				ctl_port_set_wwns(port,
2652 				    (entry->flags & CTL_PORT_WWNN_VALID) ?
2653 				    1 : 0, entry->wwnn,
2654 				    (entry->flags & CTL_PORT_WWPN_VALID) ?
2655 				    1 : 0, entry->wwpn);
2656 			}
2657 			if (done != 0)
2658 				break;
2659 		}
2660 		mtx_unlock(&softc->ctl_lock);
2661 		break;
2662 	}
2663 	case CTL_GET_OOA: {
2664 		struct ctl_ooa *ooa_hdr;
2665 		struct ctl_ooa_entry *entries;
2666 		uint32_t cur_fill_num;
2667 
2668 		ooa_hdr = (struct ctl_ooa *)addr;
2669 
2670 		if ((ooa_hdr->alloc_len == 0)
2671 		 || (ooa_hdr->alloc_num == 0)) {
2672 			printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2673 			       "must be non-zero\n", __func__,
2674 			       ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2675 			retval = EINVAL;
2676 			break;
2677 		}
2678 
2679 		if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2680 		    sizeof(struct ctl_ooa_entry))) {
2681 			printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2682 			       "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2683 			       __func__, ooa_hdr->alloc_len,
2684 			       ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2685 			retval = EINVAL;
2686 			break;
2687 		}
2688 
2689 		entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2690 
2691 		mtx_lock(&softc->ctl_lock);
2692 		if ((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0 &&
2693 		    (ooa_hdr->lun_num >= ctl_max_luns ||
2694 		     softc->ctl_luns[ooa_hdr->lun_num] == NULL)) {
2695 			mtx_unlock(&softc->ctl_lock);
2696 			free(entries, M_CTL);
2697 			printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2698 			       __func__, (uintmax_t)ooa_hdr->lun_num);
2699 			retval = EINVAL;
2700 			break;
2701 		}
2702 
2703 		cur_fill_num = 0;
2704 
2705 		if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2706 			STAILQ_FOREACH(lun, &softc->lun_list, links) {
2707 				ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2708 				    ooa_hdr, entries);
2709 			}
2710 		} else {
2711 			lun = softc->ctl_luns[ooa_hdr->lun_num];
2712 			ctl_ioctl_fill_ooa(lun, &cur_fill_num, ooa_hdr,
2713 			    entries);
2714 		}
2715 		mtx_unlock(&softc->ctl_lock);
2716 
2717 		ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2718 		ooa_hdr->fill_len = ooa_hdr->fill_num *
2719 			sizeof(struct ctl_ooa_entry);
2720 		retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2721 		if (retval != 0) {
2722 			printf("%s: error copying out %d bytes for OOA dump\n",
2723 			       __func__, ooa_hdr->fill_len);
2724 		}
2725 
2726 		getbinuptime(&ooa_hdr->cur_bt);
2727 
2728 		if (cur_fill_num > ooa_hdr->alloc_num) {
2729 			ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2730 			ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2731 		} else {
2732 			ooa_hdr->dropped_num = 0;
2733 			ooa_hdr->status = CTL_OOA_OK;
2734 		}
2735 
2736 		free(entries, M_CTL);
2737 		break;
2738 	}
2739 	case CTL_DELAY_IO: {
2740 		struct ctl_io_delay_info *delay_info;
2741 
2742 		delay_info = (struct ctl_io_delay_info *)addr;
2743 
2744 #ifdef CTL_IO_DELAY
2745 		mtx_lock(&softc->ctl_lock);
2746 		if (delay_info->lun_id >= ctl_max_luns ||
2747 		    (lun = softc->ctl_luns[delay_info->lun_id]) == NULL) {
2748 			mtx_unlock(&softc->ctl_lock);
2749 			delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2750 			break;
2751 		}
2752 		mtx_lock(&lun->lun_lock);
2753 		mtx_unlock(&softc->ctl_lock);
2754 		delay_info->status = CTL_DELAY_STATUS_OK;
2755 		switch (delay_info->delay_type) {
2756 		case CTL_DELAY_TYPE_CONT:
2757 		case CTL_DELAY_TYPE_ONESHOT:
2758 			break;
2759 		default:
2760 			delay_info->status = CTL_DELAY_STATUS_INVALID_TYPE;
2761 			break;
2762 		}
2763 		switch (delay_info->delay_loc) {
2764 		case CTL_DELAY_LOC_DATAMOVE:
2765 			lun->delay_info.datamove_type = delay_info->delay_type;
2766 			lun->delay_info.datamove_delay = delay_info->delay_secs;
2767 			break;
2768 		case CTL_DELAY_LOC_DONE:
2769 			lun->delay_info.done_type = delay_info->delay_type;
2770 			lun->delay_info.done_delay = delay_info->delay_secs;
2771 			break;
2772 		default:
2773 			delay_info->status = CTL_DELAY_STATUS_INVALID_LOC;
2774 			break;
2775 		}
2776 		mtx_unlock(&lun->lun_lock);
2777 #else
2778 		delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2779 #endif /* CTL_IO_DELAY */
2780 		break;
2781 	}
2782 	case CTL_ERROR_INJECT: {
2783 		struct ctl_error_desc *err_desc, *new_err_desc;
2784 
2785 		err_desc = (struct ctl_error_desc *)addr;
2786 
2787 		new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2788 				      M_WAITOK | M_ZERO);
2789 		bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2790 
2791 		mtx_lock(&softc->ctl_lock);
2792 		if (err_desc->lun_id >= ctl_max_luns ||
2793 		    (lun = softc->ctl_luns[err_desc->lun_id]) == NULL) {
2794 			mtx_unlock(&softc->ctl_lock);
2795 			free(new_err_desc, M_CTL);
2796 			printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
2797 			       __func__, (uintmax_t)err_desc->lun_id);
2798 			retval = EINVAL;
2799 			break;
2800 		}
2801 		mtx_lock(&lun->lun_lock);
2802 		mtx_unlock(&softc->ctl_lock);
2803 
2804 		/*
2805 		 * We could do some checking here to verify the validity
2806 		 * of the request, but given the complexity of error
2807 		 * injection requests, the checking logic would be fairly
2808 		 * complex.
2809 		 *
2810 		 * For now, if the request is invalid, it just won't get
2811 		 * executed and might get deleted.
2812 		 */
2813 		STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
2814 
2815 		/*
2816 		 * XXX KDM check to make sure the serial number is unique,
2817 		 * in case we somehow manage to wrap.  That shouldn't
2818 		 * happen for a very long time, but it's the right thing to
2819 		 * do.
2820 		 */
2821 		new_err_desc->serial = lun->error_serial;
2822 		err_desc->serial = lun->error_serial;
2823 		lun->error_serial++;
2824 
2825 		mtx_unlock(&lun->lun_lock);
2826 		break;
2827 	}
2828 	case CTL_ERROR_INJECT_DELETE: {
2829 		struct ctl_error_desc *delete_desc, *desc, *desc2;
2830 		int delete_done;
2831 
2832 		delete_desc = (struct ctl_error_desc *)addr;
2833 		delete_done = 0;
2834 
2835 		mtx_lock(&softc->ctl_lock);
2836 		if (delete_desc->lun_id >= ctl_max_luns ||
2837 		    (lun = softc->ctl_luns[delete_desc->lun_id]) == NULL) {
2838 			mtx_unlock(&softc->ctl_lock);
2839 			printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
2840 			       __func__, (uintmax_t)delete_desc->lun_id);
2841 			retval = EINVAL;
2842 			break;
2843 		}
2844 		mtx_lock(&lun->lun_lock);
2845 		mtx_unlock(&softc->ctl_lock);
2846 		STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
2847 			if (desc->serial != delete_desc->serial)
2848 				continue;
2849 
2850 			STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
2851 				      links);
2852 			free(desc, M_CTL);
2853 			delete_done = 1;
2854 		}
2855 		mtx_unlock(&lun->lun_lock);
2856 		if (delete_done == 0) {
2857 			printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
2858 			       "error serial %ju on LUN %u\n", __func__,
2859 			       delete_desc->serial, delete_desc->lun_id);
2860 			retval = EINVAL;
2861 			break;
2862 		}
2863 		break;
2864 	}
2865 	case CTL_DUMP_STRUCTS: {
2866 		int j, k;
2867 		struct ctl_port *port;
2868 		struct ctl_frontend *fe;
2869 
2870 		mtx_lock(&softc->ctl_lock);
2871 		printf("CTL Persistent Reservation information start:\n");
2872 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
2873 			mtx_lock(&lun->lun_lock);
2874 			if ((lun->flags & CTL_LUN_DISABLED) != 0) {
2875 				mtx_unlock(&lun->lun_lock);
2876 				continue;
2877 			}
2878 
2879 			for (j = 0; j < ctl_max_ports; j++) {
2880 				if (lun->pr_keys[j] == NULL)
2881 					continue;
2882 				for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
2883 					if (lun->pr_keys[j][k] == 0)
2884 						continue;
2885 					printf("  LUN %ju port %d iid %d key "
2886 					       "%#jx\n", lun->lun, j, k,
2887 					       (uintmax_t)lun->pr_keys[j][k]);
2888 				}
2889 			}
2890 			mtx_unlock(&lun->lun_lock);
2891 		}
2892 		printf("CTL Persistent Reservation information end\n");
2893 		printf("CTL Ports:\n");
2894 		STAILQ_FOREACH(port, &softc->port_list, links) {
2895 			printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
2896 			       "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
2897 			       port->frontend->name, port->port_type,
2898 			       port->physical_port, port->virtual_port,
2899 			       (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
2900 			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
2901 				if (port->wwpn_iid[j].in_use == 0 &&
2902 				    port->wwpn_iid[j].wwpn == 0 &&
2903 				    port->wwpn_iid[j].name == NULL)
2904 					continue;
2905 
2906 				printf("    iid %u use %d WWPN %#jx '%s'\n",
2907 				    j, port->wwpn_iid[j].in_use,
2908 				    (uintmax_t)port->wwpn_iid[j].wwpn,
2909 				    port->wwpn_iid[j].name);
2910 			}
2911 		}
2912 		printf("CTL Port information end\n");
2913 		mtx_unlock(&softc->ctl_lock);
2914 		/*
2915 		 * XXX KDM calling this without a lock.  We'd likely want
2916 		 * to drop the lock before calling the frontend's dump
2917 		 * routine anyway.
2918 		 */
2919 		printf("CTL Frontends:\n");
2920 		STAILQ_FOREACH(fe, &softc->fe_list, links) {
2921 			printf("  Frontend '%s'\n", fe->name);
2922 			if (fe->fe_dump != NULL)
2923 				fe->fe_dump();
2924 		}
2925 		printf("CTL Frontend information end\n");
2926 		break;
2927 	}
2928 	case CTL_LUN_REQ: {
2929 		struct ctl_lun_req *lun_req;
2930 		struct ctl_backend_driver *backend;
2931 		void *packed;
2932 		nvlist_t *tmp_args_nvl;
2933 		size_t packed_len;
2934 
2935 		lun_req = (struct ctl_lun_req *)addr;
2936 		tmp_args_nvl = lun_req->args_nvl;
2937 
2938 		backend = ctl_backend_find(lun_req->backend);
2939 		if (backend == NULL) {
2940 			lun_req->status = CTL_LUN_ERROR;
2941 			snprintf(lun_req->error_str,
2942 				 sizeof(lun_req->error_str),
2943 				 "Backend \"%s\" not found.",
2944 				 lun_req->backend);
2945 			break;
2946 		}
2947 
2948 		if (lun_req->args != NULL) {
2949 			if (lun_req->args_len > CTL_MAX_ARGS_LEN) {
2950 				lun_req->status = CTL_LUN_ERROR;
2951 				snprintf(lun_req->error_str, sizeof(lun_req->error_str),
2952 				    "Too big args.");
2953 				break;
2954 			}
2955 			packed = malloc(lun_req->args_len, M_CTL, M_WAITOK);
2956 			if (copyin(lun_req->args, packed, lun_req->args_len) != 0) {
2957 				free(packed, M_CTL);
2958 				lun_req->status = CTL_LUN_ERROR;
2959 				snprintf(lun_req->error_str, sizeof(lun_req->error_str),
2960 				    "Cannot copyin args.");
2961 				break;
2962 			}
2963 			lun_req->args_nvl = nvlist_unpack(packed,
2964 			    lun_req->args_len, 0);
2965 			free(packed, M_CTL);
2966 
2967 			if (lun_req->args_nvl == NULL) {
2968 				lun_req->status = CTL_LUN_ERROR;
2969 				snprintf(lun_req->error_str, sizeof(lun_req->error_str),
2970 				    "Cannot unpack args nvlist.");
2971 				break;
2972 			}
2973 		} else
2974 			lun_req->args_nvl = nvlist_create(0);
2975 
2976 		lun_req->result_nvl = NULL;
2977 		retval = backend->ioctl(dev, cmd, addr, flag, td);
2978 		nvlist_destroy(lun_req->args_nvl);
2979 		lun_req->args_nvl = tmp_args_nvl;
2980 
2981 		if (lun_req->result_nvl != NULL) {
2982 			if (lun_req->result != NULL) {
2983 				packed = nvlist_pack(lun_req->result_nvl,
2984 				    &packed_len);
2985 				if (packed == NULL) {
2986 					lun_req->status = CTL_LUN_ERROR;
2987 					snprintf(lun_req->error_str,
2988 					    sizeof(lun_req->error_str),
2989 					    "Cannot pack result nvlist.");
2990 					break;
2991 				}
2992 
2993 				if (packed_len > lun_req->result_len) {
2994 					lun_req->status = CTL_LUN_ERROR;
2995 					snprintf(lun_req->error_str,
2996 					    sizeof(lun_req->error_str),
2997 					    "Result nvlist too large.");
2998 					free(packed, M_NVLIST);
2999 					break;
3000 				}
3001 
3002 				if (copyout(packed, lun_req->result, packed_len)) {
3003 					lun_req->status = CTL_LUN_ERROR;
3004 					snprintf(lun_req->error_str,
3005 					    sizeof(lun_req->error_str),
3006 					    "Cannot copyout() the result.");
3007 					free(packed, M_NVLIST);
3008 					break;
3009 				}
3010 
3011 				lun_req->result_len = packed_len;
3012 				free(packed, M_NVLIST);
3013 			}
3014 
3015 			nvlist_destroy(lun_req->result_nvl);
3016 		}
3017 		break;
3018 	}
3019 	case CTL_LUN_LIST: {
3020 		struct sbuf *sb;
3021 		struct ctl_lun_list *list;
3022 		const char *name, *value;
3023 		void *cookie;
3024 		int type;
3025 
3026 		list = (struct ctl_lun_list *)addr;
3027 
3028 		/*
3029 		 * Allocate a fixed length sbuf here, based on the length
3030 		 * of the user's buffer.  We could allocate an auto-extending
3031 		 * buffer, and then tell the user how much larger our
3032 		 * amount of data is than his buffer, but that presents
3033 		 * some problems:
3034 		 *
3035 		 * 1.  The sbuf(9) routines use a blocking malloc, and so
3036 		 *     we can't hold a lock while calling them with an
3037 		 *     auto-extending buffer.
3038  		 *
3039 		 * 2.  There is not currently a LUN reference counting
3040 		 *     mechanism, outside of outstanding transactions on
3041 		 *     the LUN's OOA queue.  So a LUN could go away on us
3042 		 *     while we're getting the LUN number, backend-specific
3043 		 *     information, etc.  Thus, given the way things
3044 		 *     currently work, we need to hold the CTL lock while
3045 		 *     grabbing LUN information.
3046 		 *
3047 		 * So, from the user's standpoint, the best thing to do is
3048 		 * allocate what he thinks is a reasonable buffer length,
3049 		 * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
3050 		 * double the buffer length and try again.  (And repeat
3051 		 * that until he succeeds.)
3052 		 */
3053 		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3054 		if (sb == NULL) {
3055 			list->status = CTL_LUN_LIST_ERROR;
3056 			snprintf(list->error_str, sizeof(list->error_str),
3057 				 "Unable to allocate %d bytes for LUN list",
3058 				 list->alloc_len);
3059 			break;
3060 		}
3061 
3062 		sbuf_cat(sb, "<ctllunlist>\n");
3063 
3064 		mtx_lock(&softc->ctl_lock);
3065 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
3066 			mtx_lock(&lun->lun_lock);
3067 			retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3068 					     (uintmax_t)lun->lun);
3069 
3070 			/*
3071 			 * Bail out as soon as we see that we've overfilled
3072 			 * the buffer.
3073 			 */
3074 			if (retval != 0)
3075 				break;
3076 
3077 			retval = sbuf_printf(sb, "\t<backend_type>%s"
3078 					     "</backend_type>\n",
3079 					     (lun->backend == NULL) ?  "none" :
3080 					     lun->backend->name);
3081 
3082 			if (retval != 0)
3083 				break;
3084 
3085 			retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3086 					     lun->be_lun->lun_type);
3087 
3088 			if (retval != 0)
3089 				break;
3090 
3091 			if (lun->backend == NULL) {
3092 				retval = sbuf_cat(sb, "</lun>\n");
3093 				if (retval != 0)
3094 					break;
3095 				continue;
3096 			}
3097 
3098 			retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3099 					     (lun->be_lun->maxlba > 0) ?
3100 					     lun->be_lun->maxlba + 1 : 0);
3101 
3102 			if (retval != 0)
3103 				break;
3104 
3105 			retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3106 					     lun->be_lun->blocksize);
3107 
3108 			if (retval != 0)
3109 				break;
3110 
3111 			retval = sbuf_cat(sb, "\t<serial_number>");
3112 
3113 			if (retval != 0)
3114 				break;
3115 
3116 			retval = ctl_sbuf_printf_esc(sb,
3117 			    lun->be_lun->serial_num,
3118 			    sizeof(lun->be_lun->serial_num));
3119 
3120 			if (retval != 0)
3121 				break;
3122 
3123 			retval = sbuf_cat(sb, "</serial_number>\n");
3124 
3125 			if (retval != 0)
3126 				break;
3127 
3128 			retval = sbuf_cat(sb, "\t<device_id>");
3129 
3130 			if (retval != 0)
3131 				break;
3132 
3133 			retval = ctl_sbuf_printf_esc(sb,
3134 			    lun->be_lun->device_id,
3135 			    sizeof(lun->be_lun->device_id));
3136 
3137 			if (retval != 0)
3138 				break;
3139 
3140 			retval = sbuf_cat(sb, "</device_id>\n");
3141 
3142 			if (retval != 0)
3143 				break;
3144 
3145 			if (lun->backend->lun_info != NULL) {
3146 				retval = lun->backend->lun_info(lun->be_lun, sb);
3147 				if (retval != 0)
3148 					break;
3149 			}
3150 
3151 			cookie = NULL;
3152 			while ((name = nvlist_next(lun->be_lun->options, &type,
3153 			    &cookie)) != NULL) {
3154 				sbuf_printf(sb, "\t<%s>", name);
3155 
3156 				if (type == NV_TYPE_STRING) {
3157 					value = dnvlist_get_string(
3158 					    lun->be_lun->options, name, NULL);
3159 					if (value != NULL)
3160 						sbuf_cat(sb, value);
3161 				}
3162 
3163 				sbuf_printf(sb, "</%s>\n", name);
3164 			}
3165 
3166 			retval = sbuf_cat(sb, "</lun>\n");
3167 
3168 			if (retval != 0)
3169 				break;
3170 			mtx_unlock(&lun->lun_lock);
3171 		}
3172 		if (lun != NULL)
3173 			mtx_unlock(&lun->lun_lock);
3174 		mtx_unlock(&softc->ctl_lock);
3175 
3176 		if ((retval != 0)
3177 		 || ((retval = sbuf_cat(sb, "</ctllunlist>\n")) != 0)) {
3178 			retval = 0;
3179 			sbuf_delete(sb);
3180 			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3181 			snprintf(list->error_str, sizeof(list->error_str),
3182 				 "Out of space, %d bytes is too small",
3183 				 list->alloc_len);
3184 			break;
3185 		}
3186 
3187 		sbuf_finish(sb);
3188 
3189 		retval = copyout(sbuf_data(sb), list->lun_xml,
3190 				 sbuf_len(sb) + 1);
3191 
3192 		list->fill_len = sbuf_len(sb) + 1;
3193 		list->status = CTL_LUN_LIST_OK;
3194 		sbuf_delete(sb);
3195 		break;
3196 	}
3197 	case CTL_ISCSI: {
3198 		struct ctl_iscsi *ci;
3199 		struct ctl_frontend *fe;
3200 
3201 		ci = (struct ctl_iscsi *)addr;
3202 
3203 		fe = ctl_frontend_find("iscsi");
3204 		if (fe == NULL) {
3205 			ci->status = CTL_ISCSI_ERROR;
3206 			snprintf(ci->error_str, sizeof(ci->error_str),
3207 			    "Frontend \"iscsi\" not found.");
3208 			break;
3209 		}
3210 
3211 		retval = fe->ioctl(dev, cmd, addr, flag, td);
3212 		break;
3213 	}
3214 	case CTL_NVMF: {
3215 		struct ctl_nvmf *cn;
3216 		struct ctl_frontend *fe;
3217 
3218 		cn = (struct ctl_nvmf *)addr;
3219 
3220 		fe = ctl_frontend_find("nvmf");
3221 		if (fe == NULL) {
3222 			cn->status = CTL_NVMF_ERROR;
3223 			snprintf(cn->error_str, sizeof(cn->error_str),
3224 			    "Frontend \"nvmf\" not found.");
3225 			break;
3226 		}
3227 
3228 		retval = fe->ioctl(dev, cmd, addr, flag, td);
3229 		break;
3230 	}
3231 	case CTL_PORT_REQ: {
3232 		struct ctl_req *req;
3233 		struct ctl_frontend *fe;
3234 		void *packed;
3235 		nvlist_t *tmp_args_nvl;
3236 		size_t packed_len;
3237 
3238 		req = (struct ctl_req *)addr;
3239 		tmp_args_nvl = req->args_nvl;
3240 
3241 		fe = ctl_frontend_find(req->driver);
3242 		if (fe == NULL) {
3243 			req->status = CTL_LUN_ERROR;
3244 			snprintf(req->error_str, sizeof(req->error_str),
3245 			    "Frontend \"%s\" not found.", req->driver);
3246 			break;
3247 		}
3248 
3249 		if (req->args != NULL) {
3250 			if (req->args_len > CTL_MAX_ARGS_LEN) {
3251 				req->status = CTL_LUN_ERROR;
3252 				snprintf(req->error_str, sizeof(req->error_str),
3253 				    "Too big args.");
3254 				break;
3255 			}
3256 			packed = malloc(req->args_len, M_CTL, M_WAITOK);
3257 			if (copyin(req->args, packed, req->args_len) != 0) {
3258 				free(packed, M_CTL);
3259 				req->status = CTL_LUN_ERROR;
3260 				snprintf(req->error_str, sizeof(req->error_str),
3261 				    "Cannot copyin args.");
3262 				break;
3263 			}
3264 			req->args_nvl = nvlist_unpack(packed,
3265 			    req->args_len, 0);
3266 			free(packed, M_CTL);
3267 
3268 			if (req->args_nvl == NULL) {
3269 				req->status = CTL_LUN_ERROR;
3270 				snprintf(req->error_str, sizeof(req->error_str),
3271 				    "Cannot unpack args nvlist.");
3272 				break;
3273 			}
3274 		} else
3275 			req->args_nvl = nvlist_create(0);
3276 
3277 		req->result_nvl = NULL;
3278 		if (fe->ioctl)
3279 			retval = fe->ioctl(dev, cmd, addr, flag, td);
3280 		else
3281 			retval = ENODEV;
3282 
3283 		nvlist_destroy(req->args_nvl);
3284 		req->args_nvl = tmp_args_nvl;
3285 
3286 		if (req->result_nvl != NULL) {
3287 			if (req->result != NULL) {
3288 				packed = nvlist_pack(req->result_nvl,
3289 				    &packed_len);
3290 				if (packed == NULL) {
3291 					req->status = CTL_LUN_ERROR;
3292 					snprintf(req->error_str,
3293 					    sizeof(req->error_str),
3294 					    "Cannot pack result nvlist.");
3295 					break;
3296 				}
3297 
3298 				if (packed_len > req->result_len) {
3299 					req->status = CTL_LUN_ERROR;
3300 					snprintf(req->error_str,
3301 					    sizeof(req->error_str),
3302 					    "Result nvlist too large.");
3303 					free(packed, M_NVLIST);
3304 					break;
3305 				}
3306 
3307 				if (copyout(packed, req->result, packed_len)) {
3308 					req->status = CTL_LUN_ERROR;
3309 					snprintf(req->error_str,
3310 					    sizeof(req->error_str),
3311 					    "Cannot copyout() the result.");
3312 					free(packed, M_NVLIST);
3313 					break;
3314 				}
3315 
3316 				req->result_len = packed_len;
3317 				free(packed, M_NVLIST);
3318 			}
3319 
3320 			nvlist_destroy(req->result_nvl);
3321 		}
3322 		break;
3323 	}
3324 	case CTL_PORT_LIST: {
3325 		struct sbuf *sb;
3326 		struct ctl_port *port;
3327 		struct ctl_lun_list *list;
3328 		const char *name, *value;
3329 		void *cookie;
3330 		int j, type;
3331 		uint32_t plun;
3332 
3333 		list = (struct ctl_lun_list *)addr;
3334 
3335 		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3336 		if (sb == NULL) {
3337 			list->status = CTL_LUN_LIST_ERROR;
3338 			snprintf(list->error_str, sizeof(list->error_str),
3339 				 "Unable to allocate %d bytes for LUN list",
3340 				 list->alloc_len);
3341 			break;
3342 		}
3343 
3344 		sbuf_cat(sb, "<ctlportlist>\n");
3345 
3346 		mtx_lock(&softc->ctl_lock);
3347 		STAILQ_FOREACH(port, &softc->port_list, links) {
3348 			retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3349 					     (uintmax_t)port->targ_port);
3350 
3351 			/*
3352 			 * Bail out as soon as we see that we've overfilled
3353 			 * the buffer.
3354 			 */
3355 			if (retval != 0)
3356 				break;
3357 
3358 			retval = sbuf_printf(sb, "\t<frontend_type>%s"
3359 			    "</frontend_type>\n", port->frontend->name);
3360 			if (retval != 0)
3361 				break;
3362 
3363 			retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3364 					     port->port_type);
3365 			if (retval != 0)
3366 				break;
3367 
3368 			retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3369 			    (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3370 			if (retval != 0)
3371 				break;
3372 
3373 			retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3374 			    port->port_name);
3375 			if (retval != 0)
3376 				break;
3377 
3378 			retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3379 			    port->physical_port);
3380 			if (retval != 0)
3381 				break;
3382 
3383 			retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3384 			    port->virtual_port);
3385 			if (retval != 0)
3386 				break;
3387 
3388 			if (port->target_devid != NULL) {
3389 				sbuf_cat(sb, "\t<target>");
3390 				ctl_id_sbuf(port->target_devid, sb);
3391 				sbuf_cat(sb, "</target>\n");
3392 			}
3393 
3394 			if (port->port_devid != NULL) {
3395 				sbuf_cat(sb, "\t<port>");
3396 				ctl_id_sbuf(port->port_devid, sb);
3397 				sbuf_cat(sb, "</port>\n");
3398 			}
3399 
3400 			if (port->port_info != NULL) {
3401 				retval = port->port_info(port->onoff_arg, sb);
3402 				if (retval != 0)
3403 					break;
3404 			}
3405 
3406 			cookie = NULL;
3407 			while ((name = nvlist_next(port->options, &type,
3408 			    &cookie)) != NULL) {
3409 				sbuf_printf(sb, "\t<%s>", name);
3410 
3411 				if (type == NV_TYPE_STRING) {
3412 					value = dnvlist_get_string(port->options,
3413 					    name, NULL);
3414 					if (value != NULL)
3415 						sbuf_printf(sb, "%s", value);
3416 				}
3417 
3418 				sbuf_printf(sb, "</%s>\n", name);
3419 			}
3420 
3421 			if (port->lun_map != NULL) {
3422 				sbuf_cat(sb, "\t<lun_map>on</lun_map>\n");
3423 				for (j = 0; j < port->lun_map_size; j++) {
3424 					plun = ctl_lun_map_from_port(port, j);
3425 					if (plun == UINT32_MAX)
3426 						continue;
3427 					sbuf_printf(sb,
3428 					    "\t<lun id=\"%u\">%u</lun>\n",
3429 					    j, plun);
3430 				}
3431 			}
3432 
3433 			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3434 				if (port->wwpn_iid[j].in_use == 0 ||
3435 				    (port->wwpn_iid[j].wwpn == 0 &&
3436 				     port->wwpn_iid[j].name == NULL))
3437 					continue;
3438 
3439 				if (port->wwpn_iid[j].name != NULL)
3440 					retval = sbuf_printf(sb,
3441 					    "\t<initiator id=\"%u\">%s</initiator>\n",
3442 					    j, port->wwpn_iid[j].name);
3443 				else
3444 					retval = sbuf_printf(sb,
3445 					    "\t<initiator id=\"%u\">naa.%08jx</initiator>\n",
3446 					    j, port->wwpn_iid[j].wwpn);
3447 				if (retval != 0)
3448 					break;
3449 			}
3450 			if (retval != 0)
3451 				break;
3452 
3453 			retval = sbuf_cat(sb, "</targ_port>\n");
3454 			if (retval != 0)
3455 				break;
3456 		}
3457 		mtx_unlock(&softc->ctl_lock);
3458 
3459 		if ((retval != 0)
3460 		 || ((retval = sbuf_cat(sb, "</ctlportlist>\n")) != 0)) {
3461 			retval = 0;
3462 			sbuf_delete(sb);
3463 			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3464 			snprintf(list->error_str, sizeof(list->error_str),
3465 				 "Out of space, %d bytes is too small",
3466 				 list->alloc_len);
3467 			break;
3468 		}
3469 
3470 		sbuf_finish(sb);
3471 
3472 		retval = copyout(sbuf_data(sb), list->lun_xml,
3473 				 sbuf_len(sb) + 1);
3474 
3475 		list->fill_len = sbuf_len(sb) + 1;
3476 		list->status = CTL_LUN_LIST_OK;
3477 		sbuf_delete(sb);
3478 		break;
3479 	}
3480 	case CTL_LUN_MAP: {
3481 		struct ctl_lun_map *lm  = (struct ctl_lun_map *)addr;
3482 		struct ctl_port *port;
3483 
3484 		mtx_lock(&softc->ctl_lock);
3485 		if (lm->port < softc->port_min ||
3486 		    lm->port >= softc->port_max ||
3487 		    (port = softc->ctl_ports[lm->port]) == NULL) {
3488 			mtx_unlock(&softc->ctl_lock);
3489 			return (ENXIO);
3490 		}
3491 		if (port->status & CTL_PORT_STATUS_ONLINE) {
3492 			STAILQ_FOREACH(lun, &softc->lun_list, links) {
3493 				if (ctl_lun_map_to_port(port, lun->lun) ==
3494 				    UINT32_MAX)
3495 					continue;
3496 				mtx_lock(&lun->lun_lock);
3497 				ctl_est_ua_port(lun, lm->port, -1,
3498 				    CTL_UA_LUN_CHANGE);
3499 				mtx_unlock(&lun->lun_lock);
3500 			}
3501 		}
3502 		mtx_unlock(&softc->ctl_lock); // XXX: port_enable sleeps
3503 		if (lm->plun != UINT32_MAX) {
3504 			if (lm->lun == UINT32_MAX)
3505 				retval = ctl_lun_map_unset(port, lm->plun);
3506 			else if (lm->lun < ctl_max_luns &&
3507 			    softc->ctl_luns[lm->lun] != NULL)
3508 				retval = ctl_lun_map_set(port, lm->plun, lm->lun);
3509 			else
3510 				return (ENXIO);
3511 		} else {
3512 			if (lm->lun == UINT32_MAX)
3513 				retval = ctl_lun_map_deinit(port);
3514 			else
3515 				retval = ctl_lun_map_init(port);
3516 		}
3517 		if (port->status & CTL_PORT_STATUS_ONLINE)
3518 			ctl_isc_announce_port(port);
3519 		break;
3520 	}
3521 	case CTL_GET_LUN_STATS: {
3522 		struct ctl_get_io_stats *stats = (struct ctl_get_io_stats *)addr;
3523 		int i;
3524 
3525 		/*
3526 		 * XXX KDM no locking here.  If the LUN list changes,
3527 		 * things can blow up.
3528 		 */
3529 		i = 0;
3530 		stats->status = CTL_SS_OK;
3531 		stats->fill_len = 0;
3532 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
3533 			if (lun->lun < stats->first_item)
3534 				continue;
3535 			if (stats->fill_len + sizeof(lun->stats) >
3536 			    stats->alloc_len) {
3537 				stats->status = CTL_SS_NEED_MORE_SPACE;
3538 				break;
3539 			}
3540 			retval = copyout(&lun->stats, &stats->stats[i++],
3541 					 sizeof(lun->stats));
3542 			if (retval != 0)
3543 				break;
3544 			stats->fill_len += sizeof(lun->stats);
3545 		}
3546 		stats->num_items = softc->num_luns;
3547 		stats->flags = CTL_STATS_FLAG_NONE;
3548 #ifdef CTL_TIME_IO
3549 		stats->flags |= CTL_STATS_FLAG_TIME_VALID;
3550 #endif
3551 		getnanouptime(&stats->timestamp);
3552 		break;
3553 	}
3554 	case CTL_GET_PORT_STATS: {
3555 		struct ctl_get_io_stats *stats = (struct ctl_get_io_stats *)addr;
3556 		int i;
3557 
3558 		/*
3559 		 * XXX KDM no locking here.  If the LUN list changes,
3560 		 * things can blow up.
3561 		 */
3562 		i = 0;
3563 		stats->status = CTL_SS_OK;
3564 		stats->fill_len = 0;
3565 		STAILQ_FOREACH(port, &softc->port_list, links) {
3566 			if (port->targ_port < stats->first_item)
3567 				continue;
3568 			if (stats->fill_len + sizeof(port->stats) >
3569 			    stats->alloc_len) {
3570 				stats->status = CTL_SS_NEED_MORE_SPACE;
3571 				break;
3572 			}
3573 			retval = copyout(&port->stats, &stats->stats[i++],
3574 					 sizeof(port->stats));
3575 			if (retval != 0)
3576 				break;
3577 			stats->fill_len += sizeof(port->stats);
3578 		}
3579 		stats->num_items = softc->num_ports;
3580 		stats->flags = CTL_STATS_FLAG_NONE;
3581 #ifdef CTL_TIME_IO
3582 		stats->flags |= CTL_STATS_FLAG_TIME_VALID;
3583 #endif
3584 		getnanouptime(&stats->timestamp);
3585 		break;
3586 	}
3587 	default: {
3588 		/* XXX KDM should we fix this? */
3589 #if 0
3590 		struct ctl_backend_driver *backend;
3591 		unsigned int type;
3592 		int found;
3593 
3594 		found = 0;
3595 
3596 		/*
3597 		 * We encode the backend type as the ioctl type for backend
3598 		 * ioctls.  So parse it out here, and then search for a
3599 		 * backend of this type.
3600 		 */
3601 		type = _IOC_TYPE(cmd);
3602 
3603 		STAILQ_FOREACH(backend, &softc->be_list, links) {
3604 			if (backend->type == type) {
3605 				found = 1;
3606 				break;
3607 			}
3608 		}
3609 		if (found == 0) {
3610 			printf("ctl: unknown ioctl command %#lx or backend "
3611 			       "%d\n", cmd, type);
3612 			retval = EINVAL;
3613 			break;
3614 		}
3615 		retval = backend->ioctl(dev, cmd, addr, flag, td);
3616 #endif
3617 		retval = ENOTTY;
3618 		break;
3619 	}
3620 	}
3621 	return (retval);
3622 }
3623 
3624 uint32_t
3625 ctl_get_initindex(struct ctl_nexus *nexus)
3626 {
3627 	return (nexus->initid + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3628 }
3629 
3630 int
3631 ctl_lun_map_init(struct ctl_port *port)
3632 {
3633 	struct ctl_softc *softc = port->ctl_softc;
3634 	struct ctl_lun *lun;
3635 	int size = ctl_lun_map_size;
3636 	uint32_t i;
3637 
3638 	if (port->lun_map == NULL || port->lun_map_size < size) {
3639 		port->lun_map_size = 0;
3640 		free(port->lun_map, M_CTL);
3641 		port->lun_map = malloc(size * sizeof(uint32_t),
3642 		    M_CTL, M_NOWAIT);
3643 	}
3644 	if (port->lun_map == NULL)
3645 		return (ENOMEM);
3646 	for (i = 0; i < size; i++)
3647 		port->lun_map[i] = UINT32_MAX;
3648 	port->lun_map_size = size;
3649 	if (port->status & CTL_PORT_STATUS_ONLINE) {
3650 		if (port->lun_disable != NULL) {
3651 			STAILQ_FOREACH(lun, &softc->lun_list, links)
3652 				port->lun_disable(port->targ_lun_arg, lun->lun);
3653 		}
3654 		ctl_isc_announce_port(port);
3655 	}
3656 	return (0);
3657 }
3658 
3659 int
3660 ctl_lun_map_deinit(struct ctl_port *port)
3661 {
3662 	struct ctl_softc *softc = port->ctl_softc;
3663 	struct ctl_lun *lun;
3664 
3665 	if (port->lun_map == NULL)
3666 		return (0);
3667 	port->lun_map_size = 0;
3668 	free(port->lun_map, M_CTL);
3669 	port->lun_map = NULL;
3670 	if (port->status & CTL_PORT_STATUS_ONLINE) {
3671 		if (port->lun_enable != NULL) {
3672 			STAILQ_FOREACH(lun, &softc->lun_list, links)
3673 				port->lun_enable(port->targ_lun_arg, lun->lun);
3674 		}
3675 		ctl_isc_announce_port(port);
3676 	}
3677 	return (0);
3678 }
3679 
3680 int
3681 ctl_lun_map_set(struct ctl_port *port, uint32_t plun, uint32_t glun)
3682 {
3683 	int status;
3684 	uint32_t old;
3685 
3686 	if (port->lun_map == NULL) {
3687 		status = ctl_lun_map_init(port);
3688 		if (status != 0)
3689 			return (status);
3690 	}
3691 	if (plun >= port->lun_map_size)
3692 		return (EINVAL);
3693 	old = port->lun_map[plun];
3694 	port->lun_map[plun] = glun;
3695 	if ((port->status & CTL_PORT_STATUS_ONLINE) && old == UINT32_MAX) {
3696 		if (port->lun_enable != NULL)
3697 			port->lun_enable(port->targ_lun_arg, plun);
3698 		ctl_isc_announce_port(port);
3699 	}
3700 	return (0);
3701 }
3702 
3703 int
3704 ctl_lun_map_unset(struct ctl_port *port, uint32_t plun)
3705 {
3706 	uint32_t old;
3707 
3708 	if (port->lun_map == NULL || plun >= port->lun_map_size)
3709 		return (0);
3710 	old = port->lun_map[plun];
3711 	port->lun_map[plun] = UINT32_MAX;
3712 	if ((port->status & CTL_PORT_STATUS_ONLINE) && old != UINT32_MAX) {
3713 		if (port->lun_disable != NULL)
3714 			port->lun_disable(port->targ_lun_arg, plun);
3715 		ctl_isc_announce_port(port);
3716 	}
3717 	return (0);
3718 }
3719 
3720 uint32_t
3721 ctl_lun_map_from_port(struct ctl_port *port, uint32_t lun_id)
3722 {
3723 
3724 	if (port == NULL)
3725 		return (UINT32_MAX);
3726 	if (port->lun_map == NULL)
3727 		return (lun_id);
3728 	if (lun_id > port->lun_map_size)
3729 		return (UINT32_MAX);
3730 	return (port->lun_map[lun_id]);
3731 }
3732 
3733 uint32_t
3734 ctl_lun_map_to_port(struct ctl_port *port, uint32_t lun_id)
3735 {
3736 	uint32_t i;
3737 
3738 	if (port == NULL)
3739 		return (UINT32_MAX);
3740 	if (port->lun_map == NULL)
3741 		return (lun_id);
3742 	for (i = 0; i < port->lun_map_size; i++) {
3743 		if (port->lun_map[i] == lun_id)
3744 			return (i);
3745 	}
3746 	return (UINT32_MAX);
3747 }
3748 
3749 uint32_t
3750 ctl_decode_lun(uint64_t encoded)
3751 {
3752 	uint8_t lun[8];
3753 	uint32_t result = 0xffffffff;
3754 
3755 	be64enc(lun, encoded);
3756 	switch (lun[0] & RPL_LUNDATA_ATYP_MASK) {
3757 	case RPL_LUNDATA_ATYP_PERIPH:
3758 		if ((lun[0] & 0x3f) == 0 && lun[2] == 0 && lun[3] == 0 &&
3759 		    lun[4] == 0 && lun[5] == 0 && lun[6] == 0 && lun[7] == 0)
3760 			result = lun[1];
3761 		break;
3762 	case RPL_LUNDATA_ATYP_FLAT:
3763 		if (lun[2] == 0 && lun[3] == 0 && lun[4] == 0 && lun[5] == 0 &&
3764 		    lun[6] == 0 && lun[7] == 0)
3765 			result = ((lun[0] & 0x3f) << 8) + lun[1];
3766 		break;
3767 	case RPL_LUNDATA_ATYP_EXTLUN:
3768 		switch (lun[0] & RPL_LUNDATA_EXT_EAM_MASK) {
3769 		case 0x02:
3770 			switch (lun[0] & RPL_LUNDATA_EXT_LEN_MASK) {
3771 			case 0x00:
3772 				result = lun[1];
3773 				break;
3774 			case 0x10:
3775 				result = (lun[1] << 16) + (lun[2] << 8) +
3776 				    lun[3];
3777 				break;
3778 			case 0x20:
3779 				if (lun[1] == 0 && lun[6] == 0 && lun[7] == 0)
3780 					result = (lun[2] << 24) +
3781 					    (lun[3] << 16) + (lun[4] << 8) +
3782 					    lun[5];
3783 				break;
3784 			}
3785 			break;
3786 		case RPL_LUNDATA_EXT_EAM_NOT_SPEC:
3787 			result = 0xffffffff;
3788 			break;
3789 		}
3790 		break;
3791 	}
3792 	return (result);
3793 }
3794 
3795 uint64_t
3796 ctl_encode_lun(uint32_t decoded)
3797 {
3798 	uint64_t l = decoded;
3799 
3800 	if (l <= 0xff)
3801 		return (((uint64_t)RPL_LUNDATA_ATYP_PERIPH << 56) | (l << 48));
3802 	if (l <= 0x3fff)
3803 		return (((uint64_t)RPL_LUNDATA_ATYP_FLAT << 56) | (l << 48));
3804 	if (l <= 0xffffff)
3805 		return (((uint64_t)(RPL_LUNDATA_ATYP_EXTLUN | 0x12) << 56) |
3806 		    (l << 32));
3807 	return ((((uint64_t)RPL_LUNDATA_ATYP_EXTLUN | 0x22) << 56) | (l << 16));
3808 }
3809 
3810 int
3811 ctl_ffz(uint32_t *mask, uint32_t first, uint32_t last)
3812 {
3813 	int i;
3814 
3815 	for (i = first; i < last; i++) {
3816 		if ((mask[i / 32] & (1 << (i % 32))) == 0)
3817 			return (i);
3818 	}
3819 	return (-1);
3820 }
3821 
3822 int
3823 ctl_set_mask(uint32_t *mask, uint32_t bit)
3824 {
3825 	uint32_t chunk, piece;
3826 
3827 	chunk = bit >> 5;
3828 	piece = bit % (sizeof(uint32_t) * 8);
3829 
3830 	if ((mask[chunk] & (1 << piece)) != 0)
3831 		return (-1);
3832 	else
3833 		mask[chunk] |= (1 << piece);
3834 
3835 	return (0);
3836 }
3837 
3838 int
3839 ctl_clear_mask(uint32_t *mask, uint32_t bit)
3840 {
3841 	uint32_t chunk, piece;
3842 
3843 	chunk = bit >> 5;
3844 	piece = bit % (sizeof(uint32_t) * 8);
3845 
3846 	if ((mask[chunk] & (1 << piece)) == 0)
3847 		return (-1);
3848 	else
3849 		mask[chunk] &= ~(1 << piece);
3850 
3851 	return (0);
3852 }
3853 
3854 int
3855 ctl_is_set(uint32_t *mask, uint32_t bit)
3856 {
3857 	uint32_t chunk, piece;
3858 
3859 	chunk = bit >> 5;
3860 	piece = bit % (sizeof(uint32_t) * 8);
3861 
3862 	if ((mask[chunk] & (1 << piece)) == 0)
3863 		return (0);
3864 	else
3865 		return (1);
3866 }
3867 
3868 static uint64_t
3869 ctl_get_prkey(struct ctl_lun *lun, uint32_t residx)
3870 {
3871 	uint64_t *t;
3872 
3873 	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3874 	if (t == NULL)
3875 		return (0);
3876 	return (t[residx % CTL_MAX_INIT_PER_PORT]);
3877 }
3878 
3879 static void
3880 ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx)
3881 {
3882 	uint64_t *t;
3883 
3884 	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3885 	if (t == NULL)
3886 		return;
3887 	t[residx % CTL_MAX_INIT_PER_PORT] = 0;
3888 }
3889 
3890 static void
3891 ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx)
3892 {
3893 	uint64_t *p;
3894 	u_int i;
3895 
3896 	i = residx/CTL_MAX_INIT_PER_PORT;
3897 	if (lun->pr_keys[i] != NULL)
3898 		return;
3899 	mtx_unlock(&lun->lun_lock);
3900 	p = malloc(sizeof(uint64_t) * CTL_MAX_INIT_PER_PORT, M_CTL,
3901 	    M_WAITOK | M_ZERO);
3902 	mtx_lock(&lun->lun_lock);
3903 	if (lun->pr_keys[i] == NULL)
3904 		lun->pr_keys[i] = p;
3905 	else
3906 		free(p, M_CTL);
3907 }
3908 
3909 static void
3910 ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key)
3911 {
3912 	uint64_t *t;
3913 
3914 	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3915 	KASSERT(t != NULL, ("prkey %d is not allocated", residx));
3916 	t[residx % CTL_MAX_INIT_PER_PORT] = key;
3917 }
3918 
3919 /*
3920  * ctl_softc, pool_name, total_ctl_io are passed in.
3921  * npool is passed out.
3922  */
3923 int
3924 ctl_pool_create(struct ctl_softc *ctl_softc, const char *pool_name,
3925 		uint32_t total_ctl_io, void **npool)
3926 {
3927 	struct ctl_io_pool *pool;
3928 
3929 	pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3930 					    M_NOWAIT | M_ZERO);
3931 	if (pool == NULL)
3932 		return (ENOMEM);
3933 
3934 	snprintf(pool->name, sizeof(pool->name), "CTL IO %s", pool_name);
3935 	pool->ctl_softc = ctl_softc;
3936 #ifdef IO_POOLS
3937 	pool->zone = uma_zsecond_create(pool->name, NULL,
3938 	    NULL, NULL, NULL, ctl_softc->io_zone);
3939 	/* uma_prealloc(pool->zone, total_ctl_io); */
3940 #else
3941 	pool->zone = ctl_softc->io_zone;
3942 #endif
3943 
3944 	*npool = pool;
3945 	return (0);
3946 }
3947 
3948 void
3949 ctl_pool_free(struct ctl_io_pool *pool)
3950 {
3951 
3952 	if (pool == NULL)
3953 		return;
3954 
3955 #ifdef IO_POOLS
3956 	uma_zdestroy(pool->zone);
3957 #endif
3958 	free(pool, M_CTL);
3959 }
3960 
3961 union ctl_io *
3962 ctl_alloc_io(void *pool_ref)
3963 {
3964 	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3965 	union ctl_io *io;
3966 
3967 	io = uma_zalloc(pool->zone, M_WAITOK);
3968 	if (io != NULL) {
3969 		io->io_hdr.pool = pool_ref;
3970 		CTL_SOFTC(io) = pool->ctl_softc;
3971 		TAILQ_INIT(&io->io_hdr.blocked_queue);
3972 	}
3973 	return (io);
3974 }
3975 
3976 union ctl_io *
3977 ctl_alloc_io_nowait(void *pool_ref)
3978 {
3979 	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3980 	union ctl_io *io;
3981 
3982 	io = uma_zalloc(pool->zone, M_NOWAIT);
3983 	if (io != NULL) {
3984 		io->io_hdr.pool = pool_ref;
3985 		CTL_SOFTC(io) = pool->ctl_softc;
3986 		TAILQ_INIT(&io->io_hdr.blocked_queue);
3987 	}
3988 	return (io);
3989 }
3990 
3991 void
3992 ctl_free_io(union ctl_io *io)
3993 {
3994 	struct ctl_io_pool *pool;
3995 
3996 	if (io == NULL)
3997 		return;
3998 
3999 	pool = (struct ctl_io_pool *)io->io_hdr.pool;
4000 	uma_zfree(pool->zone, io);
4001 }
4002 
4003 void
4004 ctl_zero_io(union ctl_io *io)
4005 {
4006 	struct ctl_io_pool *pool;
4007 
4008 	if (io == NULL)
4009 		return;
4010 
4011 	/*
4012 	 * May need to preserve linked list pointers at some point too.
4013 	 */
4014 	pool = io->io_hdr.pool;
4015 	memset(io, 0, sizeof(*io));
4016 	io->io_hdr.pool = pool;
4017 	CTL_SOFTC(io) = pool->ctl_softc;
4018 	TAILQ_INIT(&io->io_hdr.blocked_queue);
4019 }
4020 
4021 int
4022 ctl_expand_number(const char *buf, uint64_t *num)
4023 {
4024 	char *endptr;
4025 	uint64_t number;
4026 	unsigned shift;
4027 
4028 	number = strtoq(buf, &endptr, 0);
4029 
4030 	switch (tolower((unsigned char)*endptr)) {
4031 	case 'e':
4032 		shift = 60;
4033 		break;
4034 	case 'p':
4035 		shift = 50;
4036 		break;
4037 	case 't':
4038 		shift = 40;
4039 		break;
4040 	case 'g':
4041 		shift = 30;
4042 		break;
4043 	case 'm':
4044 		shift = 20;
4045 		break;
4046 	case 'k':
4047 		shift = 10;
4048 		break;
4049 	case 'b':
4050 	case '\0': /* No unit. */
4051 		*num = number;
4052 		return (0);
4053 	default:
4054 		/* Unrecognized unit. */
4055 		return (-1);
4056 	}
4057 
4058 	if ((number << shift) >> shift != number) {
4059 		/* Overflow */
4060 		return (-1);
4061 	}
4062 	*num = number << shift;
4063 	return (0);
4064 }
4065 
4066 /*
4067  * This routine could be used in the future to load default and/or saved
4068  * mode page parameters for a particuar lun.
4069  */
4070 static int
4071 ctl_init_page_index(struct ctl_lun *lun)
4072 {
4073 	int i, page_code;
4074 	struct ctl_page_index *page_index;
4075 	const char *value;
4076 	uint64_t ival;
4077 
4078 	memcpy(&lun->mode_pages.index, page_index_template,
4079 	       sizeof(page_index_template));
4080 
4081 	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
4082 		page_index = &lun->mode_pages.index[i];
4083 		if (lun->be_lun->lun_type == T_DIRECT &&
4084 		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
4085 			continue;
4086 		if (lun->be_lun->lun_type == T_PROCESSOR &&
4087 		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
4088 			continue;
4089 		if (lun->be_lun->lun_type == T_CDROM &&
4090 		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
4091 			continue;
4092 
4093 		page_code = page_index->page_code & SMPH_PC_MASK;
4094 		switch (page_code) {
4095 		case SMS_RW_ERROR_RECOVERY_PAGE: {
4096 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4097 			    ("subpage %#x for page %#x is incorrect!",
4098 			    page_index->subpage, page_code));
4099 			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT],
4100 			       &rw_er_page_default,
4101 			       sizeof(rw_er_page_default));
4102 			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CHANGEABLE],
4103 			       &rw_er_page_changeable,
4104 			       sizeof(rw_er_page_changeable));
4105 			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_DEFAULT],
4106 			       &rw_er_page_default,
4107 			       sizeof(rw_er_page_default));
4108 			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_SAVED],
4109 			       &rw_er_page_default,
4110 			       sizeof(rw_er_page_default));
4111 			page_index->page_data =
4112 				(uint8_t *)lun->mode_pages.rw_er_page;
4113 			break;
4114 		}
4115 		case SMS_VERIFY_ERROR_RECOVERY_PAGE: {
4116 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4117 			    ("subpage %#x for page %#x is incorrect!",
4118 			    page_index->subpage, page_code));
4119 			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_CURRENT],
4120 			       &verify_er_page_default,
4121 			       sizeof(verify_er_page_default));
4122 			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_CHANGEABLE],
4123 			       &verify_er_page_changeable,
4124 			       sizeof(verify_er_page_changeable));
4125 			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_DEFAULT],
4126 			       &verify_er_page_default,
4127 			       sizeof(verify_er_page_default));
4128 			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_SAVED],
4129 			       &verify_er_page_default,
4130 			       sizeof(verify_er_page_default));
4131 			page_index->page_data =
4132 				(uint8_t *)lun->mode_pages.verify_er_page;
4133 			break;
4134 		}
4135 		case SMS_CACHING_PAGE: {
4136 			struct scsi_caching_page *caching_page;
4137 
4138 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4139 			    ("subpage %#x for page %#x is incorrect!",
4140 			    page_index->subpage, page_code));
4141 			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4142 			       &caching_page_default,
4143 			       sizeof(caching_page_default));
4144 			memcpy(&lun->mode_pages.caching_page[
4145 			       CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4146 			       sizeof(caching_page_changeable));
4147 			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4148 			       &caching_page_default,
4149 			       sizeof(caching_page_default));
4150 			caching_page = &lun->mode_pages.caching_page[
4151 			    CTL_PAGE_SAVED];
4152 			value = dnvlist_get_string(lun->be_lun->options,
4153 			    "writecache", NULL);
4154 			if (value != NULL && strcmp(value, "off") == 0)
4155 				caching_page->flags1 &= ~SCP_WCE;
4156 			value = dnvlist_get_string(lun->be_lun->options,
4157 			    "readcache", NULL);
4158 			if (value != NULL && strcmp(value, "off") == 0)
4159 				caching_page->flags1 |= SCP_RCD;
4160 			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4161 			       &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4162 			       sizeof(caching_page_default));
4163 			page_index->page_data =
4164 				(uint8_t *)lun->mode_pages.caching_page;
4165 			break;
4166 		}
4167 		case SMS_CONTROL_MODE_PAGE: {
4168 			switch (page_index->subpage) {
4169 			case SMS_SUBPAGE_PAGE_0: {
4170 				struct scsi_control_page *control_page;
4171 
4172 				memcpy(&lun->mode_pages.control_page[
4173 				    CTL_PAGE_DEFAULT],
4174 				       &control_page_default,
4175 				       sizeof(control_page_default));
4176 				memcpy(&lun->mode_pages.control_page[
4177 				    CTL_PAGE_CHANGEABLE],
4178 				       &control_page_changeable,
4179 				       sizeof(control_page_changeable));
4180 				memcpy(&lun->mode_pages.control_page[
4181 				    CTL_PAGE_SAVED],
4182 				       &control_page_default,
4183 				       sizeof(control_page_default));
4184 				control_page = &lun->mode_pages.control_page[
4185 				    CTL_PAGE_SAVED];
4186 				value = dnvlist_get_string(lun->be_lun->options,
4187 				    "reordering", NULL);
4188 				if (value != NULL &&
4189 				    strcmp(value, "unrestricted") == 0) {
4190 					control_page->queue_flags &=
4191 					    ~SCP_QUEUE_ALG_MASK;
4192 					control_page->queue_flags |=
4193 					    SCP_QUEUE_ALG_UNRESTRICTED;
4194 				}
4195 				memcpy(&lun->mode_pages.control_page[
4196 				    CTL_PAGE_CURRENT],
4197 				       &lun->mode_pages.control_page[
4198 				    CTL_PAGE_SAVED],
4199 				       sizeof(control_page_default));
4200 				page_index->page_data =
4201 				    (uint8_t *)lun->mode_pages.control_page;
4202 				break;
4203 			}
4204 			case 0x01:
4205 				memcpy(&lun->mode_pages.control_ext_page[
4206 				    CTL_PAGE_DEFAULT],
4207 				       &control_ext_page_default,
4208 				       sizeof(control_ext_page_default));
4209 				memcpy(&lun->mode_pages.control_ext_page[
4210 				    CTL_PAGE_CHANGEABLE],
4211 				       &control_ext_page_changeable,
4212 				       sizeof(control_ext_page_changeable));
4213 				memcpy(&lun->mode_pages.control_ext_page[
4214 				    CTL_PAGE_SAVED],
4215 				       &control_ext_page_default,
4216 				       sizeof(control_ext_page_default));
4217 				memcpy(&lun->mode_pages.control_ext_page[
4218 				    CTL_PAGE_CURRENT],
4219 				       &lun->mode_pages.control_ext_page[
4220 				    CTL_PAGE_SAVED],
4221 				       sizeof(control_ext_page_default));
4222 				page_index->page_data =
4223 				    (uint8_t *)lun->mode_pages.control_ext_page;
4224 				break;
4225 			default:
4226 				panic("subpage %#x for page %#x is incorrect!",
4227 				      page_index->subpage, page_code);
4228 			}
4229 			break;
4230 		}
4231 		case SMS_INFO_EXCEPTIONS_PAGE: {
4232 			switch (page_index->subpage) {
4233 			case SMS_SUBPAGE_PAGE_0:
4234 				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_CURRENT],
4235 				       &ie_page_default,
4236 				       sizeof(ie_page_default));
4237 				memcpy(&lun->mode_pages.ie_page[
4238 				       CTL_PAGE_CHANGEABLE], &ie_page_changeable,
4239 				       sizeof(ie_page_changeable));
4240 				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_DEFAULT],
4241 				       &ie_page_default,
4242 				       sizeof(ie_page_default));
4243 				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_SAVED],
4244 				       &ie_page_default,
4245 				       sizeof(ie_page_default));
4246 				page_index->page_data =
4247 					(uint8_t *)lun->mode_pages.ie_page;
4248 				break;
4249 			case 0x02: {
4250 				struct ctl_logical_block_provisioning_page *page;
4251 
4252 				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_DEFAULT],
4253 				       &lbp_page_default,
4254 				       sizeof(lbp_page_default));
4255 				memcpy(&lun->mode_pages.lbp_page[
4256 				       CTL_PAGE_CHANGEABLE], &lbp_page_changeable,
4257 				       sizeof(lbp_page_changeable));
4258 				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4259 				       &lbp_page_default,
4260 				       sizeof(lbp_page_default));
4261 				page = &lun->mode_pages.lbp_page[CTL_PAGE_SAVED];
4262 				value = dnvlist_get_string(lun->be_lun->options,
4263 				    "avail-threshold", NULL);
4264 				if (value != NULL &&
4265 				    ctl_expand_number(value, &ival) == 0) {
4266 					page->descr[0].flags |= SLBPPD_ENABLED |
4267 					    SLBPPD_ARMING_DEC;
4268 					if (lun->be_lun->blocksize)
4269 						ival /= lun->be_lun->blocksize;
4270 					else
4271 						ival /= 512;
4272 					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4273 					    page->descr[0].count);
4274 				}
4275 				value = dnvlist_get_string(lun->be_lun->options,
4276 				    "used-threshold", NULL);
4277 				if (value != NULL &&
4278 				    ctl_expand_number(value, &ival) == 0) {
4279 					page->descr[1].flags |= SLBPPD_ENABLED |
4280 					    SLBPPD_ARMING_INC;
4281 					if (lun->be_lun->blocksize)
4282 						ival /= lun->be_lun->blocksize;
4283 					else
4284 						ival /= 512;
4285 					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4286 					    page->descr[1].count);
4287 				}
4288 				value = dnvlist_get_string(lun->be_lun->options,
4289 				    "pool-avail-threshold", NULL);
4290 				if (value != NULL &&
4291 				    ctl_expand_number(value, &ival) == 0) {
4292 					page->descr[2].flags |= SLBPPD_ENABLED |
4293 					    SLBPPD_ARMING_DEC;
4294 					if (lun->be_lun->blocksize)
4295 						ival /= lun->be_lun->blocksize;
4296 					else
4297 						ival /= 512;
4298 					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4299 					    page->descr[2].count);
4300 				}
4301 				value = dnvlist_get_string(lun->be_lun->options,
4302 				    "pool-used-threshold", NULL);
4303 				if (value != NULL &&
4304 				    ctl_expand_number(value, &ival) == 0) {
4305 					page->descr[3].flags |= SLBPPD_ENABLED |
4306 					    SLBPPD_ARMING_INC;
4307 					if (lun->be_lun->blocksize)
4308 						ival /= lun->be_lun->blocksize;
4309 					else
4310 						ival /= 512;
4311 					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4312 					    page->descr[3].count);
4313 				}
4314 				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_CURRENT],
4315 				       &lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4316 				       sizeof(lbp_page_default));
4317 				page_index->page_data =
4318 					(uint8_t *)lun->mode_pages.lbp_page;
4319 				break;
4320 			}
4321 			default:
4322 				panic("subpage %#x for page %#x is incorrect!",
4323 				      page_index->subpage, page_code);
4324 			}
4325 			break;
4326 		}
4327 		case SMS_CDDVD_CAPS_PAGE:{
4328 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4329 			    ("subpage %#x for page %#x is incorrect!",
4330 			    page_index->subpage, page_code));
4331 			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_DEFAULT],
4332 			       &cddvd_page_default,
4333 			       sizeof(cddvd_page_default));
4334 			memcpy(&lun->mode_pages.cddvd_page[
4335 			       CTL_PAGE_CHANGEABLE], &cddvd_page_changeable,
4336 			       sizeof(cddvd_page_changeable));
4337 			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_SAVED],
4338 			       &cddvd_page_default,
4339 			       sizeof(cddvd_page_default));
4340 			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_CURRENT],
4341 			       &lun->mode_pages.cddvd_page[CTL_PAGE_SAVED],
4342 			       sizeof(cddvd_page_default));
4343 			page_index->page_data =
4344 				(uint8_t *)lun->mode_pages.cddvd_page;
4345 			break;
4346 		}
4347 		default:
4348 			panic("invalid page code value %#x", page_code);
4349 		}
4350 	}
4351 
4352 	return (CTL_RETVAL_COMPLETE);
4353 }
4354 
4355 static int
4356 ctl_init_log_page_index(struct ctl_lun *lun)
4357 {
4358 	struct ctl_page_index *page_index;
4359 	int i, j, k, prev;
4360 
4361 	memcpy(&lun->log_pages.index, log_page_index_template,
4362 	       sizeof(log_page_index_template));
4363 
4364 	prev = -1;
4365 	for (i = 0, j = 0, k = 0; i < CTL_NUM_LOG_PAGES; i++) {
4366 		page_index = &lun->log_pages.index[i];
4367 		if (lun->be_lun->lun_type == T_DIRECT &&
4368 		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
4369 			continue;
4370 		if (lun->be_lun->lun_type == T_PROCESSOR &&
4371 		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
4372 			continue;
4373 		if (lun->be_lun->lun_type == T_CDROM &&
4374 		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
4375 			continue;
4376 
4377 		if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING &&
4378 		    lun->backend->lun_attr == NULL)
4379 			continue;
4380 
4381 		if (page_index->page_code != prev) {
4382 			lun->log_pages.pages_page[j] = page_index->page_code;
4383 			prev = page_index->page_code;
4384 			j++;
4385 		}
4386 		lun->log_pages.subpages_page[k*2] = page_index->page_code;
4387 		lun->log_pages.subpages_page[k*2+1] = page_index->subpage;
4388 		k++;
4389 	}
4390 	lun->log_pages.index[0].page_data = &lun->log_pages.pages_page[0];
4391 	lun->log_pages.index[0].page_len = j;
4392 	lun->log_pages.index[1].page_data = &lun->log_pages.subpages_page[0];
4393 	lun->log_pages.index[1].page_len = k * 2;
4394 	lun->log_pages.index[2].page_data = (uint8_t *)&lun->log_pages.temp_page;
4395 	lun->log_pages.index[2].page_len = sizeof(lun->log_pages.temp_page);
4396 	lun->log_pages.index[3].page_data = &lun->log_pages.lbp_page[0];
4397 	lun->log_pages.index[3].page_len = 12*CTL_NUM_LBP_PARAMS;
4398 	lun->log_pages.index[4].page_data = (uint8_t *)&lun->log_pages.stat_page;
4399 	lun->log_pages.index[4].page_len = sizeof(lun->log_pages.stat_page);
4400 	lun->log_pages.index[5].page_data = (uint8_t *)&lun->log_pages.ie_page;
4401 	lun->log_pages.index[5].page_len = sizeof(lun->log_pages.ie_page);
4402 
4403 	return (CTL_RETVAL_COMPLETE);
4404 }
4405 
4406 static int
4407 hex2bin(const char *str, uint8_t *buf, int buf_size)
4408 {
4409 	int i;
4410 	u_char c;
4411 
4412 	memset(buf, 0, buf_size);
4413 	while (isspace(str[0]))
4414 		str++;
4415 	if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
4416 		str += 2;
4417 	buf_size *= 2;
4418 	for (i = 0; str[i] != 0 && i < buf_size; i++) {
4419 		while (str[i] == '-')	/* Skip dashes in UUIDs. */
4420 			str++;
4421 		c = str[i];
4422 		if (isdigit(c))
4423 			c -= '0';
4424 		else if (isalpha(c))
4425 			c -= isupper(c) ? 'A' - 10 : 'a' - 10;
4426 		else
4427 			break;
4428 		if (c >= 16)
4429 			break;
4430 		if ((i & 1) == 0)
4431 			buf[i / 2] |= (c << 4);
4432 		else
4433 			buf[i / 2] |= c;
4434 	}
4435 	return ((i + 1) / 2);
4436 }
4437 
4438 /*
4439  * Add LUN.
4440  *
4441  * Returns 0 for success, non-zero (errno) for failure.
4442  */
4443 int
4444 ctl_add_lun(struct ctl_be_lun *be_lun)
4445 {
4446 	struct ctl_softc *ctl_softc = control_softc;
4447 	struct ctl_lun *nlun, *lun;
4448 	struct scsi_vpd_id_descriptor *desc;
4449 	struct scsi_vpd_id_t10 *t10id;
4450 	const char *eui, *naa, *scsiname, *uuid, *vendor, *value;
4451 	int lun_number;
4452 	int devidlen, idlen1, idlen2 = 0, len;
4453 
4454 	/*
4455 	 * We support only Direct Access, CD-ROM or Processor LUN types.
4456 	 */
4457 	switch (be_lun->lun_type) {
4458 	case T_DIRECT:
4459 	case T_PROCESSOR:
4460 	case T_CDROM:
4461 		break;
4462 	case T_SEQUENTIAL:
4463 	case T_CHANGER:
4464 	default:
4465 		return (EINVAL);
4466 	}
4467 	lun = malloc(sizeof(*lun), M_CTL, M_WAITOK | M_ZERO);
4468 
4469 	lun->pending_sense = malloc(sizeof(struct scsi_sense_data *) *
4470 	    ctl_max_ports, M_DEVBUF, M_WAITOK | M_ZERO);
4471 	lun->pending_ua = malloc(sizeof(ctl_ua_type *) * ctl_max_ports,
4472 	    M_DEVBUF, M_WAITOK | M_ZERO);
4473 	lun->pr_keys = malloc(sizeof(uint64_t *) * ctl_max_ports,
4474 	    M_DEVBUF, M_WAITOK | M_ZERO);
4475 
4476 	/* Generate LUN ID. */
4477 	devidlen = max(CTL_DEVID_MIN_LEN,
4478 	    strnlen(be_lun->device_id, CTL_DEVID_LEN));
4479 	idlen1 = sizeof(*t10id) + devidlen;
4480 	len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4481 	scsiname = dnvlist_get_string(be_lun->options, "scsiname", NULL);
4482 	if (scsiname != NULL) {
4483 		idlen2 = roundup2(strlen(scsiname) + 1, 4);
4484 		len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4485 	}
4486 	eui = dnvlist_get_string(be_lun->options, "eui", NULL);
4487 	if (eui != NULL) {
4488 		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4489 	}
4490 	naa = dnvlist_get_string(be_lun->options, "naa", NULL);
4491 	if (naa != NULL) {
4492 		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4493 	}
4494 	uuid = dnvlist_get_string(be_lun->options, "uuid", NULL);
4495 	if (uuid != NULL) {
4496 		len += sizeof(struct scsi_vpd_id_descriptor) + 18;
4497 	}
4498 	lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4499 	    M_CTL, M_WAITOK | M_ZERO);
4500 	desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4501 	desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4502 	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4503 	desc->length = idlen1;
4504 	t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4505 	memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4506 	if ((vendor = dnvlist_get_string(be_lun->options, "vendor", NULL)) == NULL) {
4507 		strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4508 	} else {
4509 		strncpy(t10id->vendor, vendor,
4510 		    min(sizeof(t10id->vendor), strlen(vendor)));
4511 	}
4512 	strncpy((char *)t10id->vendor_spec_id,
4513 	    (char *)be_lun->device_id, devidlen);
4514 	if (scsiname != NULL) {
4515 		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4516 		    desc->length);
4517 		desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4518 		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4519 		    SVPD_ID_TYPE_SCSI_NAME;
4520 		desc->length = idlen2;
4521 		strlcpy(desc->identifier, scsiname, idlen2);
4522 	}
4523 	if (eui != NULL) {
4524 		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4525 		    desc->length);
4526 		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4527 		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4528 		    SVPD_ID_TYPE_EUI64;
4529 		desc->length = hex2bin(eui, desc->identifier, 16);
4530 		desc->length = desc->length > 12 ? 16 :
4531 		    (desc->length > 8 ? 12 : 8);
4532 		len -= 16 - desc->length;
4533 	}
4534 	if (naa != NULL) {
4535 		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4536 		    desc->length);
4537 		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4538 		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4539 		    SVPD_ID_TYPE_NAA;
4540 		desc->length = hex2bin(naa, desc->identifier, 16);
4541 		desc->length = desc->length > 8 ? 16 : 8;
4542 		len -= 16 - desc->length;
4543 	}
4544 	if (uuid != NULL) {
4545 		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4546 		    desc->length);
4547 		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4548 		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4549 		    SVPD_ID_TYPE_UUID;
4550 		desc->identifier[0] = 0x10;
4551 		hex2bin(uuid, &desc->identifier[2], 16);
4552 		desc->length = 18;
4553 	}
4554 	lun->lun_devid->len = len;
4555 
4556 	mtx_lock(&ctl_softc->ctl_lock);
4557 	/*
4558 	 * See if the caller requested a particular LUN number.  If so, see
4559 	 * if it is available.  Otherwise, allocate the first available LUN.
4560 	 */
4561 	if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4562 		if ((be_lun->req_lun_id > (ctl_max_luns - 1))
4563 		 || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4564 			mtx_unlock(&ctl_softc->ctl_lock);
4565 			if (be_lun->req_lun_id > (ctl_max_luns - 1)) {
4566 				printf("ctl: requested LUN ID %d is higher "
4567 				       "than ctl_max_luns - 1 (%d)\n",
4568 				       be_lun->req_lun_id, ctl_max_luns - 1);
4569 			} else {
4570 				/*
4571 				 * XXX KDM return an error, or just assign
4572 				 * another LUN ID in this case??
4573 				 */
4574 				printf("ctl: requested LUN ID %d is already "
4575 				       "in use\n", be_lun->req_lun_id);
4576 			}
4577 fail:
4578 			free(lun->lun_devid, M_CTL);
4579 			free(lun, M_CTL);
4580 			return (ENOSPC);
4581 		}
4582 		lun_number = be_lun->req_lun_id;
4583 	} else {
4584 		lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, 0, ctl_max_luns);
4585 		if (lun_number == -1) {
4586 			mtx_unlock(&ctl_softc->ctl_lock);
4587 			printf("ctl: can't allocate LUN, out of LUNs\n");
4588 			goto fail;
4589 		}
4590 	}
4591 	ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4592 	mtx_unlock(&ctl_softc->ctl_lock);
4593 
4594 	mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4595 	lun->lun = lun_number;
4596 	lun->be_lun = be_lun;
4597 	/*
4598 	 * The processor LUN is always enabled.  Disk LUNs come on line
4599 	 * disabled, and must be enabled by the backend.
4600 	 */
4601 	lun->flags |= CTL_LUN_DISABLED;
4602 	lun->backend = be_lun->be;
4603 	be_lun->ctl_lun = lun;
4604 	be_lun->lun_id = lun_number;
4605 	if (be_lun->flags & CTL_LUN_FLAG_EJECTED)
4606 		lun->flags |= CTL_LUN_EJECTED;
4607 	if (be_lun->flags & CTL_LUN_FLAG_NO_MEDIA)
4608 		lun->flags |= CTL_LUN_NO_MEDIA;
4609 	if (be_lun->flags & CTL_LUN_FLAG_STOPPED)
4610 		lun->flags |= CTL_LUN_STOPPED;
4611 
4612 	if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4613 		lun->flags |= CTL_LUN_PRIMARY_SC;
4614 
4615 	value = dnvlist_get_string(be_lun->options, "removable", NULL);
4616 	if (value != NULL) {
4617 		if (strcmp(value, "on") == 0)
4618 			lun->flags |= CTL_LUN_REMOVABLE;
4619 	} else if (be_lun->lun_type == T_CDROM)
4620 		lun->flags |= CTL_LUN_REMOVABLE;
4621 
4622 	lun->ctl_softc = ctl_softc;
4623 #ifdef CTL_TIME_IO
4624 	lun->last_busy = getsbinuptime();
4625 #endif
4626 	LIST_INIT(&lun->ooa_queue);
4627 	STAILQ_INIT(&lun->error_list);
4628 	lun->ie_reported = 1;
4629 	callout_init_mtx(&lun->ie_callout, &lun->lun_lock, 0);
4630 	ctl_tpc_lun_init(lun);
4631 	if (lun->flags & CTL_LUN_REMOVABLE) {
4632 		lun->prevent = malloc((CTL_MAX_INITIATORS + 31) / 32 * 4,
4633 		    M_CTL, M_WAITOK | M_ZERO);
4634 	}
4635 
4636 	/*
4637 	 * Initialize the mode and log page index.
4638 	 */
4639 	ctl_init_page_index(lun);
4640 	ctl_init_log_page_index(lun);
4641 
4642 	/* Setup statistics gathering */
4643 	lun->stats.item = lun_number;
4644 
4645 	/*
4646 	 * Now, before we insert this lun on the lun list, set the lun
4647 	 * inventory changed UA for all other luns.
4648 	 */
4649 	mtx_lock(&ctl_softc->ctl_lock);
4650 	STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4651 		mtx_lock(&nlun->lun_lock);
4652 		ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4653 		mtx_unlock(&nlun->lun_lock);
4654 	}
4655 	STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4656 	ctl_softc->ctl_luns[lun_number] = lun;
4657 	ctl_softc->num_luns++;
4658 	mtx_unlock(&ctl_softc->ctl_lock);
4659 
4660 	/*
4661 	 * We successfully added the LUN, attempt to enable it.
4662 	 */
4663 	if (ctl_enable_lun(lun) != 0) {
4664 		printf("%s: ctl_enable_lun() failed!\n", __func__);
4665 		mtx_lock(&ctl_softc->ctl_lock);
4666 		STAILQ_REMOVE(&ctl_softc->lun_list, lun, ctl_lun, links);
4667 		ctl_clear_mask(ctl_softc->ctl_lun_mask, lun_number);
4668 		ctl_softc->ctl_luns[lun_number] = NULL;
4669 		ctl_softc->num_luns--;
4670 		mtx_unlock(&ctl_softc->ctl_lock);
4671 		free(lun->lun_devid, M_CTL);
4672 		free(lun, M_CTL);
4673 		return (EIO);
4674 	}
4675 
4676 	return (0);
4677 }
4678 
4679 /*
4680  * Free LUN that has no active requests.
4681  */
4682 static int
4683 ctl_free_lun(struct ctl_lun *lun)
4684 {
4685 	struct ctl_softc *softc = lun->ctl_softc;
4686 	struct ctl_lun *nlun;
4687 	int i;
4688 
4689 	KASSERT(LIST_EMPTY(&lun->ooa_queue),
4690 	    ("Freeing a LUN %p with outstanding I/O!\n", lun));
4691 
4692 	mtx_lock(&softc->ctl_lock);
4693 	STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4694 	ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4695 	softc->ctl_luns[lun->lun] = NULL;
4696 	softc->num_luns--;
4697 	STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4698 		mtx_lock(&nlun->lun_lock);
4699 		ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4700 		mtx_unlock(&nlun->lun_lock);
4701 	}
4702 	mtx_unlock(&softc->ctl_lock);
4703 
4704 	/*
4705 	 * Tell the backend to free resources, if this LUN has a backend.
4706 	 */
4707 	lun->be_lun->lun_shutdown(lun->be_lun);
4708 
4709 	lun->ie_reportcnt = UINT32_MAX;
4710 	callout_drain(&lun->ie_callout);
4711 	ctl_tpc_lun_shutdown(lun);
4712 	mtx_destroy(&lun->lun_lock);
4713 	free(lun->lun_devid, M_CTL);
4714 	for (i = 0; i < ctl_max_ports; i++)
4715 		free(lun->pending_ua[i], M_CTL);
4716 	free(lun->pending_ua, M_DEVBUF);
4717 	for (i = 0; i < ctl_max_ports; i++)
4718 		free(lun->pr_keys[i], M_CTL);
4719 	free(lun->pr_keys, M_DEVBUF);
4720 	free(lun->write_buffer, M_CTL);
4721 	free(lun->prevent, M_CTL);
4722 	free(lun, M_CTL);
4723 
4724 	return (0);
4725 }
4726 
4727 static int
4728 ctl_enable_lun(struct ctl_lun *lun)
4729 {
4730 	struct ctl_softc *softc;
4731 	struct ctl_port *port, *nport;
4732 	int retval;
4733 
4734 	softc = lun->ctl_softc;
4735 
4736 	mtx_lock(&softc->ctl_lock);
4737 	mtx_lock(&lun->lun_lock);
4738 	KASSERT((lun->flags & CTL_LUN_DISABLED) != 0,
4739 	    ("%s: LUN not disabled", __func__));
4740 	lun->flags &= ~CTL_LUN_DISABLED;
4741 	mtx_unlock(&lun->lun_lock);
4742 
4743 	STAILQ_FOREACH_SAFE(port, &softc->port_list, links, nport) {
4744 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4745 		    port->lun_map != NULL || port->lun_enable == NULL)
4746 			continue;
4747 
4748 		/*
4749 		 * Drop the lock while we call the FETD's enable routine.
4750 		 * This can lead to a callback into CTL (at least in the
4751 		 * case of the internal initiator frontend.
4752 		 */
4753 		mtx_unlock(&softc->ctl_lock);
4754 		retval = port->lun_enable(port->targ_lun_arg, lun->lun);
4755 		mtx_lock(&softc->ctl_lock);
4756 		if (retval != 0) {
4757 			printf("%s: FETD %s port %d returned error "
4758 			       "%d for lun_enable on lun %jd\n",
4759 			       __func__, port->port_name, port->targ_port,
4760 			       retval, (intmax_t)lun->lun);
4761 		}
4762 	}
4763 
4764 	mtx_unlock(&softc->ctl_lock);
4765 	ctl_isc_announce_lun(lun);
4766 
4767 	return (0);
4768 }
4769 
4770 static int
4771 ctl_disable_lun(struct ctl_lun *lun)
4772 {
4773 	struct ctl_softc *softc;
4774 	struct ctl_port *port;
4775 	int retval;
4776 
4777 	softc = lun->ctl_softc;
4778 
4779 	mtx_lock(&softc->ctl_lock);
4780 	mtx_lock(&lun->lun_lock);
4781 	KASSERT((lun->flags & CTL_LUN_DISABLED) == 0,
4782 	    ("%s: LUN not enabled", __func__));
4783 	lun->flags |= CTL_LUN_DISABLED;
4784 	mtx_unlock(&lun->lun_lock);
4785 
4786 	STAILQ_FOREACH(port, &softc->port_list, links) {
4787 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4788 		    port->lun_map != NULL || port->lun_disable == NULL)
4789 			continue;
4790 
4791 		/*
4792 		 * Drop the lock before we call the frontend's disable
4793 		 * routine, to avoid lock order reversals.
4794 		 *
4795 		 * XXX KDM what happens if the frontend list changes while
4796 		 * we're traversing it?  It's unlikely, but should be handled.
4797 		 */
4798 		mtx_unlock(&softc->ctl_lock);
4799 		retval = port->lun_disable(port->targ_lun_arg, lun->lun);
4800 		mtx_lock(&softc->ctl_lock);
4801 		if (retval != 0) {
4802 			printf("%s: FETD %s port %d returned error "
4803 			       "%d for lun_disable on lun %jd\n",
4804 			       __func__, port->port_name, port->targ_port,
4805 			       retval, (intmax_t)lun->lun);
4806 		}
4807 	}
4808 
4809 	mtx_unlock(&softc->ctl_lock);
4810 	ctl_isc_announce_lun(lun);
4811 
4812 	return (0);
4813 }
4814 
4815 int
4816 ctl_start_lun(struct ctl_be_lun *be_lun)
4817 {
4818 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4819 
4820 	mtx_lock(&lun->lun_lock);
4821 	lun->flags &= ~CTL_LUN_STOPPED;
4822 	mtx_unlock(&lun->lun_lock);
4823 	return (0);
4824 }
4825 
4826 int
4827 ctl_stop_lun(struct ctl_be_lun *be_lun)
4828 {
4829 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4830 
4831 	mtx_lock(&lun->lun_lock);
4832 	lun->flags |= CTL_LUN_STOPPED;
4833 	mtx_unlock(&lun->lun_lock);
4834 	return (0);
4835 }
4836 
4837 int
4838 ctl_lun_no_media(struct ctl_be_lun *be_lun)
4839 {
4840 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4841 
4842 	mtx_lock(&lun->lun_lock);
4843 	lun->flags |= CTL_LUN_NO_MEDIA;
4844 	mtx_unlock(&lun->lun_lock);
4845 	return (0);
4846 }
4847 
4848 int
4849 ctl_lun_has_media(struct ctl_be_lun *be_lun)
4850 {
4851 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4852 	union ctl_ha_msg msg;
4853 
4854 	mtx_lock(&lun->lun_lock);
4855 	lun->flags &= ~(CTL_LUN_NO_MEDIA | CTL_LUN_EJECTED);
4856 	if (lun->flags & CTL_LUN_REMOVABLE)
4857 		ctl_est_ua_all(lun, -1, CTL_UA_MEDIUM_CHANGE);
4858 	mtx_unlock(&lun->lun_lock);
4859 	if ((lun->flags & CTL_LUN_REMOVABLE) &&
4860 	    lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
4861 		bzero(&msg.ua, sizeof(msg.ua));
4862 		msg.hdr.msg_type = CTL_MSG_UA;
4863 		msg.hdr.nexus.initid = -1;
4864 		msg.hdr.nexus.targ_port = -1;
4865 		msg.hdr.nexus.targ_lun = lun->lun;
4866 		msg.hdr.nexus.targ_mapped_lun = lun->lun;
4867 		msg.ua.ua_all = 1;
4868 		msg.ua.ua_set = 1;
4869 		msg.ua.ua_type = CTL_UA_MEDIUM_CHANGE;
4870 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
4871 		    M_WAITOK);
4872 	}
4873 	return (0);
4874 }
4875 
4876 int
4877 ctl_lun_ejected(struct ctl_be_lun *be_lun)
4878 {
4879 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4880 
4881 	mtx_lock(&lun->lun_lock);
4882 	lun->flags |= CTL_LUN_EJECTED;
4883 	mtx_unlock(&lun->lun_lock);
4884 	return (0);
4885 }
4886 
4887 int
4888 ctl_lun_primary(struct ctl_be_lun *be_lun)
4889 {
4890 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4891 
4892 	mtx_lock(&lun->lun_lock);
4893 	lun->flags |= CTL_LUN_PRIMARY_SC;
4894 	ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
4895 	mtx_unlock(&lun->lun_lock);
4896 	ctl_isc_announce_lun(lun);
4897 	return (0);
4898 }
4899 
4900 int
4901 ctl_lun_secondary(struct ctl_be_lun *be_lun)
4902 {
4903 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4904 
4905 	mtx_lock(&lun->lun_lock);
4906 	lun->flags &= ~CTL_LUN_PRIMARY_SC;
4907 	ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
4908 	mtx_unlock(&lun->lun_lock);
4909 	ctl_isc_announce_lun(lun);
4910 	return (0);
4911 }
4912 
4913 /*
4914  * Remove LUN.  If there are active requests, wait for completion.
4915  *
4916  * Returns 0 for success, non-zero (errno) for failure.
4917  * Completion is reported to backed via the lun_shutdown() method.
4918  */
4919 int
4920 ctl_remove_lun(struct ctl_be_lun *be_lun)
4921 {
4922 	struct ctl_lun *lun;
4923 
4924 	lun = (struct ctl_lun *)be_lun->ctl_lun;
4925 
4926 	ctl_disable_lun(lun);
4927 
4928 	mtx_lock(&lun->lun_lock);
4929 	lun->flags |= CTL_LUN_INVALID;
4930 
4931 	/*
4932 	 * If there is nothing in the OOA queue, go ahead and free the LUN.
4933 	 * If we have something in the OOA queue, we'll free it when the
4934 	 * last I/O completes.
4935 	 */
4936 	if (LIST_EMPTY(&lun->ooa_queue)) {
4937 		mtx_unlock(&lun->lun_lock);
4938 		ctl_free_lun(lun);
4939 	} else
4940 		mtx_unlock(&lun->lun_lock);
4941 
4942 	return (0);
4943 }
4944 
4945 void
4946 ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
4947 {
4948 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4949 	union ctl_ha_msg msg;
4950 
4951 	mtx_lock(&lun->lun_lock);
4952 	ctl_est_ua_all(lun, -1, CTL_UA_CAPACITY_CHANGE);
4953 	mtx_unlock(&lun->lun_lock);
4954 	if (lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
4955 		/* Send msg to other side. */
4956 		bzero(&msg.ua, sizeof(msg.ua));
4957 		msg.hdr.msg_type = CTL_MSG_UA;
4958 		msg.hdr.nexus.initid = -1;
4959 		msg.hdr.nexus.targ_port = -1;
4960 		msg.hdr.nexus.targ_lun = lun->lun;
4961 		msg.hdr.nexus.targ_mapped_lun = lun->lun;
4962 		msg.ua.ua_all = 1;
4963 		msg.ua.ua_set = 1;
4964 		msg.ua.ua_type = CTL_UA_CAPACITY_CHANGE;
4965 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
4966 		    M_WAITOK);
4967 	}
4968 }
4969 
4970 void
4971 ctl_lun_nsdata_ids(struct ctl_be_lun *be_lun,
4972     struct nvme_namespace_data *nsdata)
4973 {
4974 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4975 	struct scsi_vpd_id_descriptor *idd;
4976 
4977 	if (lun->lun_devid == NULL)
4978 		return;
4979 
4980 	idd = scsi_get_devid_desc((struct scsi_vpd_id_descriptor *)
4981 	    lun->lun_devid->data, lun->lun_devid->len, scsi_devid_is_lun_naa);
4982 	if (idd != NULL) {
4983 		if (idd->length == 16) {
4984 			memcpy(nsdata->nguid, idd->identifier, 16);
4985 			return;
4986 		}
4987 		if (idd->length == 8) {
4988 			memcpy(nsdata->eui64, idd->identifier, 8);
4989 			return;
4990 		}
4991 	}
4992 
4993 	idd = scsi_get_devid_desc((struct scsi_vpd_id_descriptor *)
4994 	    lun->lun_devid->data, lun->lun_devid->len, scsi_devid_is_lun_eui64);
4995 	if (idd != NULL) {
4996 		if (idd->length == 8) {
4997 			memcpy(nsdata->eui64, idd->identifier, 8);
4998 			return;
4999 		}
5000 	}
5001 }
5002 
5003 void
5004 ctl_lun_nvme_ids(struct ctl_be_lun *be_lun, void *data)
5005 {
5006 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5007 	struct scsi_vpd_id_descriptor *naa, *eui64, *uuid;
5008 	char *p;
5009 
5010 	memset(data, 0, 4096);
5011 
5012 	if (lun->lun_devid == NULL)
5013 		return;
5014 
5015 	naa = scsi_get_devid_desc((struct scsi_vpd_id_descriptor *)
5016 	    lun->lun_devid->data, lun->lun_devid->len, scsi_devid_is_lun_naa);
5017 	eui64 = scsi_get_devid_desc((struct scsi_vpd_id_descriptor *)
5018 	    lun->lun_devid->data, lun->lun_devid->len, scsi_devid_is_lun_eui64);
5019 	uuid = scsi_get_devid_desc((struct scsi_vpd_id_descriptor *)
5020 	    lun->lun_devid->data, lun->lun_devid->len, scsi_devid_is_lun_uuid);
5021 
5022 	p = data;
5023 
5024 	/* EUI64 */
5025 	if ((naa != NULL && naa->length == 8) || eui64 != NULL) {
5026 		*p++ = 1;
5027 		*p++ = 8;
5028 		p += 2;
5029 		if (naa != NULL && naa->length == 8)
5030 			memcpy(p, naa->identifier, 8);
5031 		else
5032 			memcpy(p, eui64->identifier, 8);
5033 		p += 8;
5034 	}
5035 
5036 	/* NGUID */
5037 	if (naa != NULL && naa->length == 16) {
5038 		*p++ = 1;
5039 		*p++ = 16;
5040 		p += 2;
5041 		memcpy(p, naa->identifier, 16);
5042 		p += 16;
5043 	}
5044 
5045 	/* UUID */
5046 	if (uuid != NULL) {
5047 		*p++ = 1;
5048 		*p++ = uuid->length;
5049 		p += 2;
5050 		memcpy(p, uuid->identifier, uuid->length);
5051 		p += uuid->length;
5052 	}
5053 }
5054 
5055 /*
5056  * Backend "memory move is complete" callback for requests that never
5057  * make it down to say RAIDCore's configuration code.
5058  */
5059 int
5060 ctl_config_move_done(union ctl_io *io, bool samethr)
5061 {
5062 	int retval;
5063 
5064 	CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
5065 
5066 	if (ctl_debug & CTL_DEBUG_CDB_DATA)
5067 		ctl_data_print(io);
5068 	if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN) ||
5069 	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5070 	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) ||
5071 	    ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
5072 		/*
5073 		 * XXX KDM just assuming a single pointer here, and not a
5074 		 * S/G list.  If we start using S/G lists for config data,
5075 		 * we'll need to know how to clean them up here as well.
5076 		 */
5077 		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5078 			free(ctl_kern_data_ptr(io), M_CTL);
5079 		ctl_done(io);
5080 		retval = CTL_RETVAL_COMPLETE;
5081 	} else {
5082 		/*
5083 		 * XXX KDM now we need to continue data movement.  Some
5084 		 * options:
5085 		 * - call ctl_scsiio() again?  We don't do this for data
5086 		 *   writes, because for those at least we know ahead of
5087 		 *   time where the write will go and how long it is.  For
5088 		 *   config writes, though, that information is largely
5089 		 *   contained within the write itself, thus we need to
5090 		 *   parse out the data again.
5091 		 *
5092 		 * - Call some other function once the data is in?
5093 		 */
5094 
5095 		/*
5096 		 * XXX KDM call ctl_scsiio() again for now, and check flag
5097 		 * bits to see whether we're allocated or not.
5098 		 */
5099 		switch (io->io_hdr.io_type) {
5100 		case CTL_IO_SCSI:
5101 			retval = ctl_scsiio(&io->scsiio);
5102 			break;
5103 		case CTL_IO_NVME:
5104 		case CTL_IO_NVME_ADMIN:
5105 			retval = ctl_nvmeio(&io->nvmeio);
5106 			break;
5107 		default:
5108 			__assert_unreachable();
5109 		}
5110 	}
5111 	return (retval);
5112 }
5113 
5114 /*
5115  * This gets called by a backend driver when it is done with a
5116  * data_submit method.
5117  */
5118 void
5119 ctl_data_submit_done(union ctl_io *io)
5120 {
5121 	/*
5122 	 * If the IO_CONT flag is set, we need to call the supplied
5123 	 * function to continue processing the I/O, instead of completing
5124 	 * the I/O just yet.
5125 	 *
5126 	 * If there is an error, though, we don't want to keep processing.
5127 	 * Instead, just send status back to the initiator.
5128 	 */
5129 	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5130 	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5131 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5132 	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5133 		ctl_continue_io(io);
5134 		return;
5135 	}
5136 	ctl_done(io);
5137 }
5138 
5139 /*
5140  * This gets called by a backend driver when it is done with a
5141  * configuration write.
5142  */
5143 void
5144 ctl_config_write_done(union ctl_io *io)
5145 {
5146 	uint8_t *buf;
5147 
5148 	/*
5149 	 * If the IO_CONT flag is set, we need to call the supplied
5150 	 * function to continue processing the I/O, instead of completing
5151 	 * the I/O just yet.
5152 	 *
5153 	 * If there is an error, though, we don't want to keep processing.
5154 	 * Instead, just send status back to the initiator.
5155 	 */
5156 	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5157 	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5158 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5159 	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5160 		ctl_continue_io(io);
5161 		return;
5162 	}
5163 	/*
5164 	 * Since a configuration write can be done for commands that actually
5165 	 * have data allocated, like write buffer, and commands that have
5166 	 * no data, like start/stop unit, we need to check here.
5167 	 */
5168 	if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5169 		buf = ctl_kern_data_ptr(io);
5170 	else
5171 		buf = NULL;
5172 	ctl_done(io);
5173 	if (buf)
5174 		free(buf, M_CTL);
5175 }
5176 
5177 void
5178 ctl_config_read_done(union ctl_io *io)
5179 {
5180 	uint8_t *buf;
5181 
5182 	/*
5183 	 * If there is some error -- we are done, skip data transfer.
5184 	 */
5185 	if ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0 ||
5186 	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5187 	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)) {
5188 		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5189 			buf = ctl_kern_data_ptr(io);
5190 		else
5191 			buf = NULL;
5192 		ctl_done(io);
5193 		if (buf)
5194 			free(buf, M_CTL);
5195 		return;
5196 	}
5197 
5198 	/*
5199 	 * If the IO_CONT flag is set, we need to call the supplied
5200 	 * function to continue processing the I/O, instead of completing
5201 	 * the I/O just yet.
5202 	 */
5203 	if (io->io_hdr.flags & CTL_FLAG_IO_CONT) {
5204 		ctl_continue_io(io);
5205 		return;
5206 	}
5207 
5208 	ctl_datamove(io);
5209 }
5210 
5211 /*
5212  * SCSI release command.
5213  */
5214 int
5215 ctl_scsi_release(struct ctl_scsiio *ctsio)
5216 {
5217 	struct ctl_lun *lun = CTL_LUN(ctsio);
5218 	uint32_t residx;
5219 
5220 	CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5221 
5222 	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5223 
5224 	/*
5225 	 * XXX KDM right now, we only support LUN reservation.  We don't
5226 	 * support 3rd party reservations, or extent reservations, which
5227 	 * might actually need the parameter list.  If we've gotten this
5228 	 * far, we've got a LUN reservation.  Anything else got kicked out
5229 	 * above.  So, according to SPC, ignore the length.
5230 	 */
5231 
5232 	mtx_lock(&lun->lun_lock);
5233 
5234 	/*
5235 	 * According to SPC, it is not an error for an intiator to attempt
5236 	 * to release a reservation on a LUN that isn't reserved, or that
5237 	 * is reserved by another initiator.  The reservation can only be
5238 	 * released, though, by the initiator who made it or by one of
5239 	 * several reset type events.
5240 	 */
5241 	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
5242 			lun->flags &= ~CTL_LUN_RESERVED;
5243 
5244 	mtx_unlock(&lun->lun_lock);
5245 
5246 	ctl_set_success(ctsio);
5247 	ctl_done((union ctl_io *)ctsio);
5248 	return (CTL_RETVAL_COMPLETE);
5249 }
5250 
5251 int
5252 ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5253 {
5254 	struct ctl_lun *lun = CTL_LUN(ctsio);
5255 	uint32_t residx;
5256 
5257 	CTL_DEBUG_PRINT(("ctl_reserve\n"));
5258 
5259 	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5260 
5261 	/*
5262 	 * XXX KDM right now, we only support LUN reservation.  We don't
5263 	 * support 3rd party reservations, or extent reservations, which
5264 	 * might actually need the parameter list.  If we've gotten this
5265 	 * far, we've got a LUN reservation.  Anything else got kicked out
5266 	 * above.  So, according to SPC, ignore the length.
5267 	 */
5268 
5269 	mtx_lock(&lun->lun_lock);
5270 	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
5271 		ctl_set_reservation_conflict(ctsio);
5272 		goto bailout;
5273 	}
5274 
5275 	/* SPC-3 exceptions to SPC-2 RESERVE and RELEASE behavior. */
5276 	if (lun->flags & CTL_LUN_PR_RESERVED) {
5277 		ctl_set_success(ctsio);
5278 		goto bailout;
5279 	}
5280 
5281 	lun->flags |= CTL_LUN_RESERVED;
5282 	lun->res_idx = residx;
5283 	ctl_set_success(ctsio);
5284 
5285 bailout:
5286 	mtx_unlock(&lun->lun_lock);
5287 	ctl_done((union ctl_io *)ctsio);
5288 	return (CTL_RETVAL_COMPLETE);
5289 }
5290 
5291 int
5292 ctl_start_stop(struct ctl_scsiio *ctsio)
5293 {
5294 	struct ctl_lun *lun = CTL_LUN(ctsio);
5295 	struct scsi_start_stop_unit *cdb;
5296 	int retval;
5297 
5298 	CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5299 
5300 	cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5301 
5302 	if ((cdb->how & SSS_PC_MASK) == 0) {
5303 		if ((lun->flags & CTL_LUN_PR_RESERVED) &&
5304 		    (cdb->how & SSS_START) == 0) {
5305 			uint32_t residx;
5306 
5307 			residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5308 			if (ctl_get_prkey(lun, residx) == 0 ||
5309 			    (lun->pr_res_idx != residx && lun->pr_res_type < 4)) {
5310 				ctl_set_reservation_conflict(ctsio);
5311 				ctl_done((union ctl_io *)ctsio);
5312 				return (CTL_RETVAL_COMPLETE);
5313 			}
5314 		}
5315 
5316 		if ((cdb->how & SSS_LOEJ) &&
5317 		    (lun->flags & CTL_LUN_REMOVABLE) == 0) {
5318 			ctl_set_invalid_field(ctsio,
5319 					      /*sks_valid*/ 1,
5320 					      /*command*/ 1,
5321 					      /*field*/ 4,
5322 					      /*bit_valid*/ 1,
5323 					      /*bit*/ 1);
5324 			ctl_done((union ctl_io *)ctsio);
5325 			return (CTL_RETVAL_COMPLETE);
5326 		}
5327 
5328 		if ((cdb->how & SSS_START) == 0 && (cdb->how & SSS_LOEJ) &&
5329 		    lun->prevent_count > 0) {
5330 			/* "Medium removal prevented" */
5331 			ctl_set_sense(ctsio, /*current_error*/ 1,
5332 			    /*sense_key*/(lun->flags & CTL_LUN_NO_MEDIA) ?
5333 			     SSD_KEY_NOT_READY : SSD_KEY_ILLEGAL_REQUEST,
5334 			    /*asc*/ 0x53, /*ascq*/ 0x02, SSD_ELEM_NONE);
5335 			ctl_done((union ctl_io *)ctsio);
5336 			return (CTL_RETVAL_COMPLETE);
5337 		}
5338 	}
5339 
5340 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5341 	return (retval);
5342 }
5343 
5344 int
5345 ctl_prevent_allow(struct ctl_scsiio *ctsio)
5346 {
5347 	struct ctl_lun *lun = CTL_LUN(ctsio);
5348 	struct scsi_prevent *cdb;
5349 	int retval;
5350 	uint32_t initidx;
5351 
5352 	CTL_DEBUG_PRINT(("ctl_prevent_allow\n"));
5353 
5354 	cdb = (struct scsi_prevent *)ctsio->cdb;
5355 
5356 	if ((lun->flags & CTL_LUN_REMOVABLE) == 0 || lun->prevent == NULL) {
5357 		ctl_set_invalid_opcode(ctsio);
5358 		ctl_done((union ctl_io *)ctsio);
5359 		return (CTL_RETVAL_COMPLETE);
5360 	}
5361 
5362 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5363 	mtx_lock(&lun->lun_lock);
5364 	if ((cdb->how & PR_PREVENT) &&
5365 	    ctl_is_set(lun->prevent, initidx) == 0) {
5366 		ctl_set_mask(lun->prevent, initidx);
5367 		lun->prevent_count++;
5368 	} else if ((cdb->how & PR_PREVENT) == 0 &&
5369 	    ctl_is_set(lun->prevent, initidx)) {
5370 		ctl_clear_mask(lun->prevent, initidx);
5371 		lun->prevent_count--;
5372 	}
5373 	mtx_unlock(&lun->lun_lock);
5374 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5375 	return (retval);
5376 }
5377 
5378 /*
5379  * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5380  * we don't really do anything with the LBA and length fields if the user
5381  * passes them in.  Instead we'll just flush out the cache for the entire
5382  * LUN.
5383  */
5384 int
5385 ctl_sync_cache(struct ctl_scsiio *ctsio)
5386 {
5387 	struct ctl_lun *lun = CTL_LUN(ctsio);
5388 	struct ctl_lba_len_flags *lbalen;
5389 	uint64_t starting_lba;
5390 	uint32_t block_count;
5391 	int retval;
5392 	uint8_t byte2;
5393 
5394 	CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5395 
5396 	retval = 0;
5397 
5398 	switch (ctsio->cdb[0]) {
5399 	case SYNCHRONIZE_CACHE: {
5400 		struct scsi_sync_cache *cdb;
5401 		cdb = (struct scsi_sync_cache *)ctsio->cdb;
5402 
5403 		starting_lba = scsi_4btoul(cdb->begin_lba);
5404 		block_count = scsi_2btoul(cdb->lb_count);
5405 		byte2 = cdb->byte2;
5406 		break;
5407 	}
5408 	case SYNCHRONIZE_CACHE_16: {
5409 		struct scsi_sync_cache_16 *cdb;
5410 		cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5411 
5412 		starting_lba = scsi_8btou64(cdb->begin_lba);
5413 		block_count = scsi_4btoul(cdb->lb_count);
5414 		byte2 = cdb->byte2;
5415 		break;
5416 	}
5417 	default:
5418 		ctl_set_invalid_opcode(ctsio);
5419 		ctl_done((union ctl_io *)ctsio);
5420 		goto bailout;
5421 		break; /* NOTREACHED */
5422 	}
5423 
5424 	/*
5425 	 * We check the LBA and length, but don't do anything with them.
5426 	 * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5427 	 * get flushed.  This check will just help satisfy anyone who wants
5428 	 * to see an error for an out of range LBA.
5429 	 */
5430 	if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5431 		ctl_set_lba_out_of_range(ctsio,
5432 		    MAX(starting_lba, lun->be_lun->maxlba + 1));
5433 		ctl_done((union ctl_io *)ctsio);
5434 		goto bailout;
5435 	}
5436 
5437 	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5438 	lbalen->lba = starting_lba;
5439 	lbalen->len = block_count;
5440 	lbalen->flags = byte2;
5441 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5442 
5443 bailout:
5444 	return (retval);
5445 }
5446 
5447 int
5448 ctl_format(struct ctl_scsiio *ctsio)
5449 {
5450 	struct scsi_format *cdb;
5451 	int length, defect_list_len;
5452 
5453 	CTL_DEBUG_PRINT(("ctl_format\n"));
5454 
5455 	cdb = (struct scsi_format *)ctsio->cdb;
5456 
5457 	length = 0;
5458 	if (cdb->byte2 & SF_FMTDATA) {
5459 		if (cdb->byte2 & SF_LONGLIST)
5460 			length = sizeof(struct scsi_format_header_long);
5461 		else
5462 			length = sizeof(struct scsi_format_header_short);
5463 	}
5464 
5465 	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5466 	 && (length > 0)) {
5467 		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5468 		ctsio->kern_data_len = length;
5469 		ctsio->kern_total_len = length;
5470 		ctsio->kern_rel_offset = 0;
5471 		ctsio->kern_sg_entries = 0;
5472 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5473 		ctsio->be_move_done = ctl_config_move_done;
5474 		ctl_datamove((union ctl_io *)ctsio);
5475 
5476 		return (CTL_RETVAL_COMPLETE);
5477 	}
5478 
5479 	defect_list_len = 0;
5480 
5481 	if (cdb->byte2 & SF_FMTDATA) {
5482 		if (cdb->byte2 & SF_LONGLIST) {
5483 			struct scsi_format_header_long *header;
5484 
5485 			header = (struct scsi_format_header_long *)
5486 				ctsio->kern_data_ptr;
5487 
5488 			defect_list_len = scsi_4btoul(header->defect_list_len);
5489 			if (defect_list_len != 0) {
5490 				ctl_set_invalid_field(ctsio,
5491 						      /*sks_valid*/ 1,
5492 						      /*command*/ 0,
5493 						      /*field*/ 2,
5494 						      /*bit_valid*/ 0,
5495 						      /*bit*/ 0);
5496 				goto bailout;
5497 			}
5498 		} else {
5499 			struct scsi_format_header_short *header;
5500 
5501 			header = (struct scsi_format_header_short *)
5502 				ctsio->kern_data_ptr;
5503 
5504 			defect_list_len = scsi_2btoul(header->defect_list_len);
5505 			if (defect_list_len != 0) {
5506 				ctl_set_invalid_field(ctsio,
5507 						      /*sks_valid*/ 1,
5508 						      /*command*/ 0,
5509 						      /*field*/ 2,
5510 						      /*bit_valid*/ 0,
5511 						      /*bit*/ 0);
5512 				goto bailout;
5513 			}
5514 		}
5515 	}
5516 
5517 	ctl_set_success(ctsio);
5518 bailout:
5519 
5520 	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5521 		free(ctsio->kern_data_ptr, M_CTL);
5522 		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5523 	}
5524 
5525 	ctl_done((union ctl_io *)ctsio);
5526 	return (CTL_RETVAL_COMPLETE);
5527 }
5528 
5529 int
5530 ctl_read_buffer(struct ctl_scsiio *ctsio)
5531 {
5532 	struct ctl_lun *lun = CTL_LUN(ctsio);
5533 	uint64_t buffer_offset;
5534 	uint32_t len;
5535 	uint8_t byte2;
5536 	static uint8_t descr[4];
5537 	static uint8_t echo_descr[4] = { 0 };
5538 
5539 	CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5540 
5541 	switch (ctsio->cdb[0]) {
5542 	case READ_BUFFER: {
5543 		struct scsi_read_buffer *cdb;
5544 
5545 		cdb = (struct scsi_read_buffer *)ctsio->cdb;
5546 		buffer_offset = scsi_3btoul(cdb->offset);
5547 		len = scsi_3btoul(cdb->length);
5548 		byte2 = cdb->byte2;
5549 		break;
5550 	}
5551 	case READ_BUFFER_16: {
5552 		struct scsi_read_buffer_16 *cdb;
5553 
5554 		cdb = (struct scsi_read_buffer_16 *)ctsio->cdb;
5555 		buffer_offset = scsi_8btou64(cdb->offset);
5556 		len = scsi_4btoul(cdb->length);
5557 		byte2 = cdb->byte2;
5558 		break;
5559 	}
5560 	default: /* This shouldn't happen. */
5561 		ctl_set_invalid_opcode(ctsio);
5562 		ctl_done((union ctl_io *)ctsio);
5563 		return (CTL_RETVAL_COMPLETE);
5564 	}
5565 
5566 	if (buffer_offset > CTL_WRITE_BUFFER_SIZE ||
5567 	    buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5568 		ctl_set_invalid_field(ctsio,
5569 				      /*sks_valid*/ 1,
5570 				      /*command*/ 1,
5571 				      /*field*/ 6,
5572 				      /*bit_valid*/ 0,
5573 				      /*bit*/ 0);
5574 		ctl_done((union ctl_io *)ctsio);
5575 		return (CTL_RETVAL_COMPLETE);
5576 	}
5577 
5578 	if ((byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5579 		descr[0] = 0;
5580 		scsi_ulto3b(CTL_WRITE_BUFFER_SIZE, &descr[1]);
5581 		ctsio->kern_data_ptr = descr;
5582 		len = min(len, sizeof(descr));
5583 	} else if ((byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5584 		ctsio->kern_data_ptr = echo_descr;
5585 		len = min(len, sizeof(echo_descr));
5586 	} else {
5587 		if (lun->write_buffer == NULL) {
5588 			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5589 			    M_CTL, M_WAITOK | M_ZERO);
5590 		}
5591 		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5592 	}
5593 	ctsio->kern_data_len = len;
5594 	ctsio->kern_total_len = len;
5595 	ctsio->kern_rel_offset = 0;
5596 	ctsio->kern_sg_entries = 0;
5597 	ctl_set_success(ctsio);
5598 	ctsio->be_move_done = ctl_config_move_done;
5599 	ctl_datamove((union ctl_io *)ctsio);
5600 	return (CTL_RETVAL_COMPLETE);
5601 }
5602 
5603 int
5604 ctl_write_buffer(struct ctl_scsiio *ctsio)
5605 {
5606 	struct ctl_lun *lun = CTL_LUN(ctsio);
5607 	struct scsi_write_buffer *cdb;
5608 	int buffer_offset, len;
5609 
5610 	CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5611 
5612 	cdb = (struct scsi_write_buffer *)ctsio->cdb;
5613 
5614 	len = scsi_3btoul(cdb->length);
5615 	buffer_offset = scsi_3btoul(cdb->offset);
5616 
5617 	if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5618 		ctl_set_invalid_field(ctsio,
5619 				      /*sks_valid*/ 1,
5620 				      /*command*/ 1,
5621 				      /*field*/ 6,
5622 				      /*bit_valid*/ 0,
5623 				      /*bit*/ 0);
5624 		ctl_done((union ctl_io *)ctsio);
5625 		return (CTL_RETVAL_COMPLETE);
5626 	}
5627 
5628 	if (lun->write_buffer == NULL) {
5629 		lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5630 			    M_CTL, M_WAITOK | M_ZERO);
5631 	}
5632 
5633 	/*
5634 	 * If this kernel request hasn't started yet, initialize the data
5635 	 * buffer to the correct region of the LUN's write buffer.  Note that
5636 	 * this doesn't set CTL_FLAG_ALLOCATED since this points into a
5637 	 * persistent buffer belonging to the LUN rather than a buffer
5638 	 * dedicated to this request.
5639 	 */
5640 	if (ctsio->kern_data_ptr == NULL) {
5641 		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5642 		ctsio->kern_data_len = len;
5643 		ctsio->kern_total_len = len;
5644 		ctsio->kern_rel_offset = 0;
5645 		ctsio->kern_sg_entries = 0;
5646 		ctsio->be_move_done = ctl_config_move_done;
5647 		ctl_datamove((union ctl_io *)ctsio);
5648 
5649 		return (CTL_RETVAL_COMPLETE);
5650 	}
5651 
5652 	ctl_set_success(ctsio);
5653 	ctl_done((union ctl_io *)ctsio);
5654 	return (CTL_RETVAL_COMPLETE);
5655 }
5656 
5657 static int
5658 ctl_write_same_cont(union ctl_io *io)
5659 {
5660 	struct ctl_lun *lun = CTL_LUN(io);
5661 	struct ctl_scsiio *ctsio;
5662 	struct ctl_lba_len_flags *lbalen;
5663 	int retval;
5664 
5665 	CTL_IO_ASSERT(io, SCSI);
5666 
5667 	ctsio = &io->scsiio;
5668 	ctsio->io_hdr.status = CTL_STATUS_NONE;
5669 	lbalen = (struct ctl_lba_len_flags *)
5670 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5671 	lbalen->lba += lbalen->len;
5672 	if ((lun->be_lun->maxlba + 1) - lbalen->lba <= UINT32_MAX) {
5673 		ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
5674 		lbalen->len = (lun->be_lun->maxlba + 1) - lbalen->lba;
5675 	}
5676 
5677 	CTL_DEBUG_PRINT(("ctl_write_same_cont: calling config_write()\n"));
5678 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5679 	return (retval);
5680 }
5681 
5682 int
5683 ctl_write_same(struct ctl_scsiio *ctsio)
5684 {
5685 	struct ctl_lun *lun = CTL_LUN(ctsio);
5686 	struct ctl_lba_len_flags *lbalen;
5687 	const char *val;
5688 	uint64_t lba, ival;
5689 	uint32_t num_blocks;
5690 	int len, retval;
5691 	uint8_t byte2;
5692 
5693 	CTL_DEBUG_PRINT(("ctl_write_same\n"));
5694 
5695 	switch (ctsio->cdb[0]) {
5696 	case WRITE_SAME_10: {
5697 		struct scsi_write_same_10 *cdb;
5698 
5699 		cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5700 
5701 		lba = scsi_4btoul(cdb->addr);
5702 		num_blocks = scsi_2btoul(cdb->length);
5703 		byte2 = cdb->byte2;
5704 		break;
5705 	}
5706 	case WRITE_SAME_16: {
5707 		struct scsi_write_same_16 *cdb;
5708 
5709 		cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5710 
5711 		lba = scsi_8btou64(cdb->addr);
5712 		num_blocks = scsi_4btoul(cdb->length);
5713 		byte2 = cdb->byte2;
5714 		break;
5715 	}
5716 	default:
5717 		/*
5718 		 * We got a command we don't support.  This shouldn't
5719 		 * happen, commands should be filtered out above us.
5720 		 */
5721 		ctl_set_invalid_opcode(ctsio);
5722 		ctl_done((union ctl_io *)ctsio);
5723 
5724 		return (CTL_RETVAL_COMPLETE);
5725 		break; /* NOTREACHED */
5726 	}
5727 
5728 	/* ANCHOR flag can be used only together with UNMAP */
5729 	if ((byte2 & SWS_UNMAP) == 0 && (byte2 & SWS_ANCHOR) != 0) {
5730 		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
5731 		    /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
5732 		ctl_done((union ctl_io *)ctsio);
5733 		return (CTL_RETVAL_COMPLETE);
5734 	}
5735 
5736 	/*
5737 	 * The first check is to make sure we're in bounds, the second
5738 	 * check is to catch wrap-around problems.  If the lba + num blocks
5739 	 * is less than the lba, then we've wrapped around and the block
5740 	 * range is invalid anyway.
5741 	 */
5742 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5743 	 || ((lba + num_blocks) < lba)) {
5744 		ctl_set_lba_out_of_range(ctsio,
5745 		    MAX(lba, lun->be_lun->maxlba + 1));
5746 		ctl_done((union ctl_io *)ctsio);
5747 		return (CTL_RETVAL_COMPLETE);
5748 	}
5749 
5750 	/* Zero number of blocks means "to the last logical block" */
5751 	if (num_blocks == 0) {
5752 		ival = UINT64_MAX;
5753 		val = dnvlist_get_string(lun->be_lun->options,
5754 		    "write_same_max_lba", NULL);
5755 		if (val != NULL)
5756 			ctl_expand_number(val, &ival);
5757 		if ((lun->be_lun->maxlba + 1) - lba > ival) {
5758 			ctl_set_invalid_field(ctsio,
5759 			    /*sks_valid*/ 1, /*command*/ 1,
5760 			    /*field*/ ctsio->cdb[0] == WRITE_SAME_10 ? 7 : 10,
5761 			    /*bit_valid*/ 0, /*bit*/ 0);
5762 			ctl_done((union ctl_io *)ctsio);
5763 			return (CTL_RETVAL_COMPLETE);
5764 		}
5765 		if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5766 			ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
5767 			ctsio->io_cont = ctl_write_same_cont;
5768 			num_blocks = 1 << 31;
5769 		} else
5770 			num_blocks = (lun->be_lun->maxlba + 1) - lba;
5771 	}
5772 
5773 	len = lun->be_lun->blocksize;
5774 
5775 	/*
5776 	 * If we've got a kernel request that hasn't been malloced yet,
5777 	 * malloc it and tell the caller the data buffer is here.
5778 	 */
5779 	if ((byte2 & SWS_NDOB) == 0 &&
5780 	    (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5781 		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);
5782 		ctsio->kern_data_len = len;
5783 		ctsio->kern_total_len = len;
5784 		ctsio->kern_rel_offset = 0;
5785 		ctsio->kern_sg_entries = 0;
5786 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5787 		ctsio->be_move_done = ctl_config_move_done;
5788 		ctl_datamove((union ctl_io *)ctsio);
5789 
5790 		return (CTL_RETVAL_COMPLETE);
5791 	}
5792 
5793 	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5794 	lbalen->lba = lba;
5795 	lbalen->len = num_blocks;
5796 	lbalen->flags = byte2;
5797 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5798 
5799 	return (retval);
5800 }
5801 
5802 int
5803 ctl_unmap(struct ctl_scsiio *ctsio)
5804 {
5805 	struct ctl_lun *lun = CTL_LUN(ctsio);
5806 	struct scsi_unmap *cdb;
5807 	struct ctl_ptr_len_flags *ptrlen;
5808 	struct scsi_unmap_header *hdr;
5809 	struct scsi_unmap_desc *buf, *end, *endnz, *range;
5810 	uint64_t lba;
5811 	uint32_t num_blocks;
5812 	int len, retval;
5813 	uint8_t byte2;
5814 
5815 	CTL_DEBUG_PRINT(("ctl_unmap\n"));
5816 
5817 	cdb = (struct scsi_unmap *)ctsio->cdb;
5818 	len = scsi_2btoul(cdb->length);
5819 	byte2 = cdb->byte2;
5820 
5821 	/*
5822 	 * If we've got a kernel request that hasn't been malloced yet,
5823 	 * malloc it and tell the caller the data buffer is here.
5824 	 */
5825 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5826 		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);
5827 		ctsio->kern_data_len = len;
5828 		ctsio->kern_total_len = len;
5829 		ctsio->kern_rel_offset = 0;
5830 		ctsio->kern_sg_entries = 0;
5831 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5832 		ctsio->be_move_done = ctl_config_move_done;
5833 		ctl_datamove((union ctl_io *)ctsio);
5834 
5835 		return (CTL_RETVAL_COMPLETE);
5836 	}
5837 
5838 	len = ctsio->kern_total_len - ctsio->kern_data_resid;
5839 	hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
5840 	if (len < sizeof (*hdr) ||
5841 	    len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
5842 	    len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
5843 	    scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
5844 		ctl_set_invalid_field(ctsio,
5845 				      /*sks_valid*/ 0,
5846 				      /*command*/ 0,
5847 				      /*field*/ 0,
5848 				      /*bit_valid*/ 0,
5849 				      /*bit*/ 0);
5850 		goto done;
5851 	}
5852 	len = scsi_2btoul(hdr->desc_length);
5853 	buf = (struct scsi_unmap_desc *)(hdr + 1);
5854 	end = buf + len / sizeof(*buf);
5855 
5856 	endnz = buf;
5857 	for (range = buf; range < end; range++) {
5858 		lba = scsi_8btou64(range->lba);
5859 		num_blocks = scsi_4btoul(range->length);
5860 		if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5861 		 || ((lba + num_blocks) < lba)) {
5862 			ctl_set_lba_out_of_range(ctsio,
5863 			    MAX(lba, lun->be_lun->maxlba + 1));
5864 			ctl_done((union ctl_io *)ctsio);
5865 			return (CTL_RETVAL_COMPLETE);
5866 		}
5867 		if (num_blocks != 0)
5868 			endnz = range + 1;
5869 	}
5870 
5871 	/*
5872 	 * Block backend can not handle zero last range.
5873 	 * Filter it out and return if there is nothing left.
5874 	 */
5875 	len = (uint8_t *)endnz - (uint8_t *)buf;
5876 	if (len == 0) {
5877 		ctl_set_success(ctsio);
5878 		goto done;
5879 	}
5880 
5881 	mtx_lock(&lun->lun_lock);
5882 	ptrlen = (struct ctl_ptr_len_flags *)
5883 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5884 	ptrlen->ptr = (void *)buf;
5885 	ptrlen->len = len;
5886 	ptrlen->flags = byte2;
5887 	ctl_try_unblock_others(lun, (union ctl_io *)ctsio, FALSE);
5888 	mtx_unlock(&lun->lun_lock);
5889 
5890 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5891 	return (retval);
5892 
5893 done:
5894 	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5895 		free(ctsio->kern_data_ptr, M_CTL);
5896 		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5897 	}
5898 	ctl_done((union ctl_io *)ctsio);
5899 	return (CTL_RETVAL_COMPLETE);
5900 }
5901 
5902 int
5903 ctl_default_page_handler(struct ctl_scsiio *ctsio,
5904 			 struct ctl_page_index *page_index, uint8_t *page_ptr)
5905 {
5906 	struct ctl_lun *lun = CTL_LUN(ctsio);
5907 	uint8_t *current_cp;
5908 	int set_ua;
5909 	uint32_t initidx;
5910 
5911 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5912 	set_ua = 0;
5913 
5914 	current_cp = (page_index->page_data + (page_index->page_len *
5915 	    CTL_PAGE_CURRENT));
5916 
5917 	mtx_lock(&lun->lun_lock);
5918 	if (memcmp(current_cp, page_ptr, page_index->page_len)) {
5919 		memcpy(current_cp, page_ptr, page_index->page_len);
5920 		set_ua = 1;
5921 	}
5922 	if (set_ua != 0)
5923 		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
5924 	mtx_unlock(&lun->lun_lock);
5925 	if (set_ua) {
5926 		ctl_isc_announce_mode(lun,
5927 		    ctl_get_initindex(&ctsio->io_hdr.nexus),
5928 		    page_index->page_code, page_index->subpage);
5929 	}
5930 	return (CTL_RETVAL_COMPLETE);
5931 }
5932 
5933 static void
5934 ctl_ie_timer(void *arg)
5935 {
5936 	struct ctl_lun *lun = arg;
5937 	uint64_t t;
5938 
5939 	if (lun->ie_asc == 0)
5940 		return;
5941 
5942 	if (lun->MODE_IE.mrie == SIEP_MRIE_UA)
5943 		ctl_est_ua_all(lun, -1, CTL_UA_IE);
5944 	else
5945 		lun->ie_reported = 0;
5946 
5947 	if (lun->ie_reportcnt < scsi_4btoul(lun->MODE_IE.report_count)) {
5948 		lun->ie_reportcnt++;
5949 		t = scsi_4btoul(lun->MODE_IE.interval_timer);
5950 		if (t == 0 || t == UINT32_MAX)
5951 			t = 3000;  /* 5 min */
5952 		callout_schedule_sbt(&lun->ie_callout, SBT_1S / 10 * t,
5953 		    SBT_1S / 10, 0);
5954 	}
5955 }
5956 
5957 int
5958 ctl_ie_page_handler(struct ctl_scsiio *ctsio,
5959 			 struct ctl_page_index *page_index, uint8_t *page_ptr)
5960 {
5961 	struct ctl_lun *lun = CTL_LUN(ctsio);
5962 	struct scsi_info_exceptions_page *pg;
5963 	uint64_t t;
5964 
5965 	(void)ctl_default_page_handler(ctsio, page_index, page_ptr);
5966 
5967 	pg = (struct scsi_info_exceptions_page *)page_ptr;
5968 	mtx_lock(&lun->lun_lock);
5969 	if (pg->info_flags & SIEP_FLAGS_TEST) {
5970 		lun->ie_asc = 0x5d;
5971 		lun->ie_ascq = 0xff;
5972 		if (pg->mrie == SIEP_MRIE_UA) {
5973 			ctl_est_ua_all(lun, -1, CTL_UA_IE);
5974 			lun->ie_reported = 1;
5975 		} else {
5976 			ctl_clr_ua_all(lun, -1, CTL_UA_IE);
5977 			lun->ie_reported = -1;
5978 		}
5979 		lun->ie_reportcnt = 1;
5980 		if (lun->ie_reportcnt < scsi_4btoul(pg->report_count)) {
5981 			lun->ie_reportcnt++;
5982 			t = scsi_4btoul(pg->interval_timer);
5983 			if (t == 0 || t == UINT32_MAX)
5984 				t = 3000;  /* 5 min */
5985 			callout_reset_sbt(&lun->ie_callout, SBT_1S / 10 * t,
5986 			    SBT_1S / 10, ctl_ie_timer, lun, 0);
5987 		}
5988 	} else {
5989 		lun->ie_asc = 0;
5990 		lun->ie_ascq = 0;
5991 		lun->ie_reported = 1;
5992 		ctl_clr_ua_all(lun, -1, CTL_UA_IE);
5993 		lun->ie_reportcnt = UINT32_MAX;
5994 		callout_stop(&lun->ie_callout);
5995 	}
5996 	mtx_unlock(&lun->lun_lock);
5997 	return (CTL_RETVAL_COMPLETE);
5998 }
5999 
6000 static int
6001 ctl_do_mode_select(union ctl_io *io)
6002 {
6003 	struct ctl_lun *lun = CTL_LUN(io);
6004 	struct scsi_mode_page_header *page_header;
6005 	struct ctl_page_index *page_index;
6006 	struct ctl_scsiio *ctsio;
6007 	int page_len, page_len_offset, page_len_size;
6008 	union ctl_modepage_info *modepage_info;
6009 	uint16_t *len_left, *len_used;
6010 	int retval, i;
6011 
6012 	CTL_IO_ASSERT(io, SCSI);
6013 
6014 	ctsio = &io->scsiio;
6015 	page_index = NULL;
6016 	page_len = 0;
6017 
6018 	modepage_info = (union ctl_modepage_info *)
6019 		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6020 	len_left = &modepage_info->header.len_left;
6021 	len_used = &modepage_info->header.len_used;
6022 
6023 do_next_page:
6024 
6025 	page_header = (struct scsi_mode_page_header *)
6026 		(ctsio->kern_data_ptr + *len_used);
6027 
6028 	if (*len_left == 0) {
6029 		free(ctsio->kern_data_ptr, M_CTL);
6030 		ctl_set_success(ctsio);
6031 		ctl_done((union ctl_io *)ctsio);
6032 		return (CTL_RETVAL_COMPLETE);
6033 	} else if (*len_left < sizeof(struct scsi_mode_page_header)) {
6034 		free(ctsio->kern_data_ptr, M_CTL);
6035 		ctl_set_param_len_error(ctsio);
6036 		ctl_done((union ctl_io *)ctsio);
6037 		return (CTL_RETVAL_COMPLETE);
6038 
6039 	} else if ((page_header->page_code & SMPH_SPF)
6040 		&& (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
6041 		free(ctsio->kern_data_ptr, M_CTL);
6042 		ctl_set_param_len_error(ctsio);
6043 		ctl_done((union ctl_io *)ctsio);
6044 		return (CTL_RETVAL_COMPLETE);
6045 	}
6046 
6047 	/*
6048 	 * XXX KDM should we do something with the block descriptor?
6049 	 */
6050 	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6051 		page_index = &lun->mode_pages.index[i];
6052 		if (lun->be_lun->lun_type == T_DIRECT &&
6053 		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6054 			continue;
6055 		if (lun->be_lun->lun_type == T_PROCESSOR &&
6056 		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6057 			continue;
6058 		if (lun->be_lun->lun_type == T_CDROM &&
6059 		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6060 			continue;
6061 
6062 		if ((page_index->page_code & SMPH_PC_MASK) !=
6063 		    (page_header->page_code & SMPH_PC_MASK))
6064 			continue;
6065 
6066 		/*
6067 		 * If neither page has a subpage code, then we've got a
6068 		 * match.
6069 		 */
6070 		if (((page_index->page_code & SMPH_SPF) == 0)
6071 		 && ((page_header->page_code & SMPH_SPF) == 0)) {
6072 			page_len = page_header->page_length;
6073 			break;
6074 		}
6075 
6076 		/*
6077 		 * If both pages have subpages, then the subpage numbers
6078 		 * have to match.
6079 		 */
6080 		if ((page_index->page_code & SMPH_SPF)
6081 		  && (page_header->page_code & SMPH_SPF)) {
6082 			struct scsi_mode_page_header_sp *sph;
6083 
6084 			sph = (struct scsi_mode_page_header_sp *)page_header;
6085 			if (page_index->subpage == sph->subpage) {
6086 				page_len = scsi_2btoul(sph->page_length);
6087 				break;
6088 			}
6089 		}
6090 	}
6091 
6092 	/*
6093 	 * If we couldn't find the page, or if we don't have a mode select
6094 	 * handler for it, send back an error to the user.
6095 	 */
6096 	if ((i >= CTL_NUM_MODE_PAGES)
6097 	 || (page_index->select_handler == NULL)) {
6098 		ctl_set_invalid_field(ctsio,
6099 				      /*sks_valid*/ 1,
6100 				      /*command*/ 0,
6101 				      /*field*/ *len_used,
6102 				      /*bit_valid*/ 0,
6103 				      /*bit*/ 0);
6104 		free(ctsio->kern_data_ptr, M_CTL);
6105 		ctl_done((union ctl_io *)ctsio);
6106 		return (CTL_RETVAL_COMPLETE);
6107 	}
6108 
6109 	if (page_index->page_code & SMPH_SPF) {
6110 		page_len_offset = 2;
6111 		page_len_size = 2;
6112 	} else {
6113 		page_len_size = 1;
6114 		page_len_offset = 1;
6115 	}
6116 
6117 	/*
6118 	 * If the length the initiator gives us isn't the one we specify in
6119 	 * the mode page header, or if they didn't specify enough data in
6120 	 * the CDB to avoid truncating this page, kick out the request.
6121 	 */
6122 	if (page_len != page_index->page_len - page_len_offset - page_len_size) {
6123 		ctl_set_invalid_field(ctsio,
6124 				      /*sks_valid*/ 1,
6125 				      /*command*/ 0,
6126 				      /*field*/ *len_used + page_len_offset,
6127 				      /*bit_valid*/ 0,
6128 				      /*bit*/ 0);
6129 		free(ctsio->kern_data_ptr, M_CTL);
6130 		ctl_done((union ctl_io *)ctsio);
6131 		return (CTL_RETVAL_COMPLETE);
6132 	}
6133 	if (*len_left < page_index->page_len) {
6134 		free(ctsio->kern_data_ptr, M_CTL);
6135 		ctl_set_param_len_error(ctsio);
6136 		ctl_done((union ctl_io *)ctsio);
6137 		return (CTL_RETVAL_COMPLETE);
6138 	}
6139 
6140 	/*
6141 	 * Run through the mode page, checking to make sure that the bits
6142 	 * the user changed are actually legal for him to change.
6143 	 */
6144 	for (i = 0; i < page_index->page_len; i++) {
6145 		uint8_t *user_byte, *change_mask, *current_byte;
6146 		int bad_bit;
6147 		int j;
6148 
6149 		user_byte = (uint8_t *)page_header + i;
6150 		change_mask = page_index->page_data +
6151 			      (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6152 		current_byte = page_index->page_data +
6153 			       (page_index->page_len * CTL_PAGE_CURRENT) + i;
6154 
6155 		/*
6156 		 * Check to see whether the user set any bits in this byte
6157 		 * that he is not allowed to set.
6158 		 */
6159 		if ((*user_byte & ~(*change_mask)) ==
6160 		    (*current_byte & ~(*change_mask)))
6161 			continue;
6162 
6163 		/*
6164 		 * Go through bit by bit to determine which one is illegal.
6165 		 */
6166 		bad_bit = 0;
6167 		for (j = 7; j >= 0; j--) {
6168 			if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6169 			    (((1 << i) & ~(*change_mask)) & *current_byte)) {
6170 				bad_bit = i;
6171 				break;
6172 			}
6173 		}
6174 		ctl_set_invalid_field(ctsio,
6175 				      /*sks_valid*/ 1,
6176 				      /*command*/ 0,
6177 				      /*field*/ *len_used + i,
6178 				      /*bit_valid*/ 1,
6179 				      /*bit*/ bad_bit);
6180 		free(ctsio->kern_data_ptr, M_CTL);
6181 		ctl_done((union ctl_io *)ctsio);
6182 		return (CTL_RETVAL_COMPLETE);
6183 	}
6184 
6185 	/*
6186 	 * Decrement these before we call the page handler, since we may
6187 	 * end up getting called back one way or another before the handler
6188 	 * returns to this context.
6189 	 */
6190 	*len_left -= page_index->page_len;
6191 	*len_used += page_index->page_len;
6192 
6193 	retval = page_index->select_handler(ctsio, page_index,
6194 					    (uint8_t *)page_header);
6195 
6196 	/*
6197 	 * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6198 	 * wait until this queued command completes to finish processing
6199 	 * the mode page.  If it returns anything other than
6200 	 * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6201 	 * already set the sense information, freed the data pointer, and
6202 	 * completed the io for us.
6203 	 */
6204 	if (retval != CTL_RETVAL_COMPLETE)
6205 		goto bailout_no_done;
6206 
6207 	/*
6208 	 * If the initiator sent us more than one page, parse the next one.
6209 	 */
6210 	if (*len_left > 0)
6211 		goto do_next_page;
6212 
6213 	ctl_set_success(ctsio);
6214 	free(ctsio->kern_data_ptr, M_CTL);
6215 	ctl_done((union ctl_io *)ctsio);
6216 
6217 bailout_no_done:
6218 
6219 	return (CTL_RETVAL_COMPLETE);
6220 
6221 }
6222 
6223 int
6224 ctl_mode_select(struct ctl_scsiio *ctsio)
6225 {
6226 	struct ctl_lun *lun = CTL_LUN(ctsio);
6227 	union ctl_modepage_info *modepage_info;
6228 	int bd_len, i, header_size, param_len, rtd;
6229 	uint32_t initidx;
6230 
6231 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6232 	switch (ctsio->cdb[0]) {
6233 	case MODE_SELECT_6: {
6234 		struct scsi_mode_select_6 *cdb;
6235 
6236 		cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6237 
6238 		rtd = (cdb->byte2 & SMS_RTD) ? 1 : 0;
6239 		param_len = cdb->length;
6240 		header_size = sizeof(struct scsi_mode_header_6);
6241 		break;
6242 	}
6243 	case MODE_SELECT_10: {
6244 		struct scsi_mode_select_10 *cdb;
6245 
6246 		cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6247 
6248 		rtd = (cdb->byte2 & SMS_RTD) ? 1 : 0;
6249 		param_len = scsi_2btoul(cdb->length);
6250 		header_size = sizeof(struct scsi_mode_header_10);
6251 		break;
6252 	}
6253 	default:
6254 		ctl_set_invalid_opcode(ctsio);
6255 		ctl_done((union ctl_io *)ctsio);
6256 		return (CTL_RETVAL_COMPLETE);
6257 	}
6258 
6259 	if (rtd) {
6260 		if (param_len != 0) {
6261 			ctl_set_invalid_field(ctsio, /*sks_valid*/ 0,
6262 			    /*command*/ 1, /*field*/ 0,
6263 			    /*bit_valid*/ 0, /*bit*/ 0);
6264 			ctl_done((union ctl_io *)ctsio);
6265 			return (CTL_RETVAL_COMPLETE);
6266 		}
6267 
6268 		/* Revert to defaults. */
6269 		ctl_init_page_index(lun);
6270 		mtx_lock(&lun->lun_lock);
6271 		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
6272 		mtx_unlock(&lun->lun_lock);
6273 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6274 			ctl_isc_announce_mode(lun, -1,
6275 			    lun->mode_pages.index[i].page_code & SMPH_PC_MASK,
6276 			    lun->mode_pages.index[i].subpage);
6277 		}
6278 		ctl_set_success(ctsio);
6279 		ctl_done((union ctl_io *)ctsio);
6280 		return (CTL_RETVAL_COMPLETE);
6281 	}
6282 
6283 	/*
6284 	 * From SPC-3:
6285 	 * "A parameter list length of zero indicates that the Data-Out Buffer
6286 	 * shall be empty. This condition shall not be considered as an error."
6287 	 */
6288 	if (param_len == 0) {
6289 		ctl_set_success(ctsio);
6290 		ctl_done((union ctl_io *)ctsio);
6291 		return (CTL_RETVAL_COMPLETE);
6292 	}
6293 
6294 	/*
6295 	 * Since we'll hit this the first time through, prior to
6296 	 * allocation, we don't need to free a data buffer here.
6297 	 */
6298 	if (param_len < header_size) {
6299 		ctl_set_param_len_error(ctsio);
6300 		ctl_done((union ctl_io *)ctsio);
6301 		return (CTL_RETVAL_COMPLETE);
6302 	}
6303 
6304 	/*
6305 	 * Allocate the data buffer and grab the user's data.  In theory,
6306 	 * we shouldn't have to sanity check the parameter list length here
6307 	 * because the maximum size is 64K.  We should be able to malloc
6308 	 * that much without too many problems.
6309 	 */
6310 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6311 		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6312 		ctsio->kern_data_len = param_len;
6313 		ctsio->kern_total_len = param_len;
6314 		ctsio->kern_rel_offset = 0;
6315 		ctsio->kern_sg_entries = 0;
6316 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6317 		ctsio->be_move_done = ctl_config_move_done;
6318 		ctl_datamove((union ctl_io *)ctsio);
6319 
6320 		return (CTL_RETVAL_COMPLETE);
6321 	}
6322 
6323 	switch (ctsio->cdb[0]) {
6324 	case MODE_SELECT_6: {
6325 		struct scsi_mode_header_6 *mh6;
6326 
6327 		mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6328 		bd_len = mh6->blk_desc_len;
6329 		break;
6330 	}
6331 	case MODE_SELECT_10: {
6332 		struct scsi_mode_header_10 *mh10;
6333 
6334 		mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6335 		bd_len = scsi_2btoul(mh10->blk_desc_len);
6336 		break;
6337 	}
6338 	default:
6339 		panic("%s: Invalid CDB type %#x", __func__, ctsio->cdb[0]);
6340 	}
6341 
6342 	if (param_len < (header_size + bd_len)) {
6343 		free(ctsio->kern_data_ptr, M_CTL);
6344 		ctl_set_param_len_error(ctsio);
6345 		ctl_done((union ctl_io *)ctsio);
6346 		return (CTL_RETVAL_COMPLETE);
6347 	}
6348 
6349 	/*
6350 	 * Set the IO_CONT flag, so that if this I/O gets passed to
6351 	 * ctl_config_write_done(), it'll get passed back to
6352 	 * ctl_do_mode_select() for further processing, or completion if
6353 	 * we're all done.
6354 	 */
6355 	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6356 	ctsio->io_cont = ctl_do_mode_select;
6357 
6358 	modepage_info = (union ctl_modepage_info *)
6359 		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6360 	memset(modepage_info, 0, sizeof(*modepage_info));
6361 	modepage_info->header.len_left = param_len - header_size - bd_len;
6362 	modepage_info->header.len_used = header_size + bd_len;
6363 
6364 	return (ctl_do_mode_select((union ctl_io *)ctsio));
6365 }
6366 
6367 int
6368 ctl_mode_sense(struct ctl_scsiio *ctsio)
6369 {
6370 	struct ctl_lun *lun = CTL_LUN(ctsio);
6371 	int pc, page_code, llba, subpage;
6372 	int alloc_len, page_len, header_len, bd_len, total_len;
6373 	void *block_desc;
6374 	struct ctl_page_index *page_index;
6375 
6376 	llba = 0;
6377 
6378 	CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6379 
6380 	switch (ctsio->cdb[0]) {
6381 	case MODE_SENSE_6: {
6382 		struct scsi_mode_sense_6 *cdb;
6383 
6384 		cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6385 
6386 		header_len = sizeof(struct scsi_mode_hdr_6);
6387 		if (cdb->byte2 & SMS_DBD)
6388 			bd_len = 0;
6389 		else
6390 			bd_len = sizeof(struct scsi_mode_block_descr);
6391 		header_len += bd_len;
6392 
6393 		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6394 		page_code = cdb->page & SMS_PAGE_CODE;
6395 		subpage = cdb->subpage;
6396 		alloc_len = cdb->length;
6397 		break;
6398 	}
6399 	case MODE_SENSE_10: {
6400 		struct scsi_mode_sense_10 *cdb;
6401 
6402 		cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6403 
6404 		header_len = sizeof(struct scsi_mode_hdr_10);
6405 		if (cdb->byte2 & SMS_DBD) {
6406 			bd_len = 0;
6407 		} else if (lun->be_lun->lun_type == T_DIRECT) {
6408 			if (cdb->byte2 & SMS10_LLBAA) {
6409 				llba = 1;
6410 				bd_len = sizeof(struct scsi_mode_block_descr_dlong);
6411 			} else
6412 				bd_len = sizeof(struct scsi_mode_block_descr_dshort);
6413 		} else
6414 			bd_len = sizeof(struct scsi_mode_block_descr);
6415 		header_len += bd_len;
6416 
6417 		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6418 		page_code = cdb->page & SMS_PAGE_CODE;
6419 		subpage = cdb->subpage;
6420 		alloc_len = scsi_2btoul(cdb->length);
6421 		break;
6422 	}
6423 	default:
6424 		ctl_set_invalid_opcode(ctsio);
6425 		ctl_done((union ctl_io *)ctsio);
6426 		return (CTL_RETVAL_COMPLETE);
6427 		break; /* NOTREACHED */
6428 	}
6429 
6430 	/*
6431 	 * We have to make a first pass through to calculate the size of
6432 	 * the pages that match the user's query.  Then we allocate enough
6433 	 * memory to hold it, and actually copy the data into the buffer.
6434 	 */
6435 	switch (page_code) {
6436 	case SMS_ALL_PAGES_PAGE: {
6437 		u_int i;
6438 
6439 		page_len = 0;
6440 
6441 		/*
6442 		 * At the moment, values other than 0 and 0xff here are
6443 		 * reserved according to SPC-3.
6444 		 */
6445 		if ((subpage != SMS_SUBPAGE_PAGE_0)
6446 		 && (subpage != SMS_SUBPAGE_ALL)) {
6447 			ctl_set_invalid_field(ctsio,
6448 					      /*sks_valid*/ 1,
6449 					      /*command*/ 1,
6450 					      /*field*/ 3,
6451 					      /*bit_valid*/ 0,
6452 					      /*bit*/ 0);
6453 			ctl_done((union ctl_io *)ctsio);
6454 			return (CTL_RETVAL_COMPLETE);
6455 		}
6456 
6457 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6458 			page_index = &lun->mode_pages.index[i];
6459 
6460 			/* Make sure the page is supported for this dev type */
6461 			if (lun->be_lun->lun_type == T_DIRECT &&
6462 			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6463 				continue;
6464 			if (lun->be_lun->lun_type == T_PROCESSOR &&
6465 			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6466 				continue;
6467 			if (lun->be_lun->lun_type == T_CDROM &&
6468 			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6469 				continue;
6470 
6471 			/*
6472 			 * We don't use this subpage if the user didn't
6473 			 * request all subpages.
6474 			 */
6475 			if ((page_index->subpage != 0)
6476 			 && (subpage == SMS_SUBPAGE_PAGE_0))
6477 				continue;
6478 
6479 			page_len += page_index->page_len;
6480 		}
6481 		break;
6482 	}
6483 	default: {
6484 		u_int i;
6485 
6486 		page_len = 0;
6487 
6488 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6489 			page_index = &lun->mode_pages.index[i];
6490 
6491 			/* Make sure the page is supported for this dev type */
6492 			if (lun->be_lun->lun_type == T_DIRECT &&
6493 			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6494 				continue;
6495 			if (lun->be_lun->lun_type == T_PROCESSOR &&
6496 			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6497 				continue;
6498 			if (lun->be_lun->lun_type == T_CDROM &&
6499 			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6500 				continue;
6501 
6502 			/* Look for the right page code */
6503 			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6504 				continue;
6505 
6506 			/* Look for the right subpage or the subpage wildcard*/
6507 			if ((page_index->subpage != subpage)
6508 			 && (subpage != SMS_SUBPAGE_ALL))
6509 				continue;
6510 
6511 			page_len += page_index->page_len;
6512 		}
6513 
6514 		if (page_len == 0) {
6515 			ctl_set_invalid_field(ctsio,
6516 					      /*sks_valid*/ 1,
6517 					      /*command*/ 1,
6518 					      /*field*/ 2,
6519 					      /*bit_valid*/ 1,
6520 					      /*bit*/ 5);
6521 			ctl_done((union ctl_io *)ctsio);
6522 			return (CTL_RETVAL_COMPLETE);
6523 		}
6524 		break;
6525 	}
6526 	}
6527 
6528 	total_len = header_len + page_len;
6529 
6530 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6531 	ctsio->kern_sg_entries = 0;
6532 	ctsio->kern_rel_offset = 0;
6533 	ctsio->kern_data_len = min(total_len, alloc_len);
6534 	ctsio->kern_total_len = ctsio->kern_data_len;
6535 
6536 	switch (ctsio->cdb[0]) {
6537 	case MODE_SENSE_6: {
6538 		struct scsi_mode_hdr_6 *header;
6539 
6540 		header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6541 
6542 		header->datalen = MIN(total_len - 1, 254);
6543 		if (lun->be_lun->lun_type == T_DIRECT) {
6544 			header->dev_specific = 0x10; /* DPOFUA */
6545 			if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6546 			    (lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0)
6547 				header->dev_specific |= 0x80; /* WP */
6548 		}
6549 		header->block_descr_len = bd_len;
6550 		block_desc = &header[1];
6551 		break;
6552 	}
6553 	case MODE_SENSE_10: {
6554 		struct scsi_mode_hdr_10 *header;
6555 		int datalen;
6556 
6557 		header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6558 
6559 		datalen = MIN(total_len - 2, 65533);
6560 		scsi_ulto2b(datalen, header->datalen);
6561 		if (lun->be_lun->lun_type == T_DIRECT) {
6562 			header->dev_specific = 0x10; /* DPOFUA */
6563 			if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6564 			    (lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0)
6565 				header->dev_specific |= 0x80; /* WP */
6566 		}
6567 		if (llba)
6568 			header->flags |= SMH_LONGLBA;
6569 		scsi_ulto2b(bd_len, header->block_descr_len);
6570 		block_desc = &header[1];
6571 		break;
6572 	}
6573 	default:
6574 		panic("%s: Invalid CDB type %#x", __func__, ctsio->cdb[0]);
6575 	}
6576 
6577 	/*
6578 	 * If we've got a disk, use its blocksize in the block
6579 	 * descriptor.  Otherwise, just set it to 0.
6580 	 */
6581 	if (bd_len > 0) {
6582 		if (lun->be_lun->lun_type == T_DIRECT) {
6583 			if (llba) {
6584 				struct scsi_mode_block_descr_dlong *bd = block_desc;
6585 				if (lun->be_lun->maxlba != 0)
6586 					scsi_u64to8b(lun->be_lun->maxlba + 1,
6587 					    bd->num_blocks);
6588 				scsi_ulto4b(lun->be_lun->blocksize,
6589 				    bd->block_len);
6590 			} else {
6591 				struct scsi_mode_block_descr_dshort *bd = block_desc;
6592 				if (lun->be_lun->maxlba != 0)
6593 					scsi_ulto4b(MIN(lun->be_lun->maxlba+1,
6594 					    UINT32_MAX), bd->num_blocks);
6595 				scsi_ulto3b(lun->be_lun->blocksize,
6596 				    bd->block_len);
6597 			}
6598 		} else {
6599 			struct scsi_mode_block_descr *bd = block_desc;
6600 			scsi_ulto3b(0, bd->block_len);
6601 		}
6602 	}
6603 
6604 	switch (page_code) {
6605 	case SMS_ALL_PAGES_PAGE: {
6606 		int i, data_used;
6607 
6608 		data_used = header_len;
6609 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6610 			struct ctl_page_index *page_index;
6611 
6612 			page_index = &lun->mode_pages.index[i];
6613 			if (lun->be_lun->lun_type == T_DIRECT &&
6614 			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6615 				continue;
6616 			if (lun->be_lun->lun_type == T_PROCESSOR &&
6617 			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6618 				continue;
6619 			if (lun->be_lun->lun_type == T_CDROM &&
6620 			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6621 				continue;
6622 
6623 			/*
6624 			 * We don't use this subpage if the user didn't
6625 			 * request all subpages.  We already checked (above)
6626 			 * to make sure the user only specified a subpage
6627 			 * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
6628 			 */
6629 			if ((page_index->subpage != 0)
6630 			 && (subpage == SMS_SUBPAGE_PAGE_0))
6631 				continue;
6632 
6633 			/*
6634 			 * Call the handler, if it exists, to update the
6635 			 * page to the latest values.
6636 			 */
6637 			if (page_index->sense_handler != NULL)
6638 				page_index->sense_handler(ctsio, page_index,pc);
6639 
6640 			memcpy(ctsio->kern_data_ptr + data_used,
6641 			       page_index->page_data +
6642 			       (page_index->page_len * pc),
6643 			       page_index->page_len);
6644 			data_used += page_index->page_len;
6645 		}
6646 		break;
6647 	}
6648 	default: {
6649 		int i, data_used;
6650 
6651 		data_used = header_len;
6652 
6653 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6654 			struct ctl_page_index *page_index;
6655 
6656 			page_index = &lun->mode_pages.index[i];
6657 
6658 			/* Look for the right page code */
6659 			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6660 				continue;
6661 
6662 			/* Look for the right subpage or the subpage wildcard*/
6663 			if ((page_index->subpage != subpage)
6664 			 && (subpage != SMS_SUBPAGE_ALL))
6665 				continue;
6666 
6667 			/* Make sure the page is supported for this dev type */
6668 			if (lun->be_lun->lun_type == T_DIRECT &&
6669 			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6670 				continue;
6671 			if (lun->be_lun->lun_type == T_PROCESSOR &&
6672 			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6673 				continue;
6674 			if (lun->be_lun->lun_type == T_CDROM &&
6675 			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6676 				continue;
6677 
6678 			/*
6679 			 * Call the handler, if it exists, to update the
6680 			 * page to the latest values.
6681 			 */
6682 			if (page_index->sense_handler != NULL)
6683 				page_index->sense_handler(ctsio, page_index,pc);
6684 
6685 			memcpy(ctsio->kern_data_ptr + data_used,
6686 			       page_index->page_data +
6687 			       (page_index->page_len * pc),
6688 			       page_index->page_len);
6689 			data_used += page_index->page_len;
6690 		}
6691 		break;
6692 	}
6693 	}
6694 
6695 	ctl_set_success(ctsio);
6696 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6697 	ctsio->be_move_done = ctl_config_move_done;
6698 	ctl_datamove((union ctl_io *)ctsio);
6699 	return (CTL_RETVAL_COMPLETE);
6700 }
6701 
6702 int
6703 ctl_temp_log_sense_handler(struct ctl_scsiio *ctsio,
6704 			       struct ctl_page_index *page_index,
6705 			       int pc)
6706 {
6707 	struct ctl_lun *lun = CTL_LUN(ctsio);
6708 	struct scsi_log_temperature *data;
6709 	const char *value;
6710 
6711 	data = (struct scsi_log_temperature *)page_index->page_data;
6712 
6713 	scsi_ulto2b(SLP_TEMPERATURE, data->hdr.param_code);
6714 	data->hdr.param_control = SLP_LBIN;
6715 	data->hdr.param_len = sizeof(struct scsi_log_temperature) -
6716 	    sizeof(struct scsi_log_param_header);
6717 	if ((value = dnvlist_get_string(lun->be_lun->options, "temperature",
6718 	    NULL)) != NULL)
6719 		data->temperature = strtol(value, NULL, 0);
6720 	else
6721 		data->temperature = 0xff;
6722 	data++;
6723 
6724 	scsi_ulto2b(SLP_REFTEMPERATURE, data->hdr.param_code);
6725 	data->hdr.param_control = SLP_LBIN;
6726 	data->hdr.param_len = sizeof(struct scsi_log_temperature) -
6727 	    sizeof(struct scsi_log_param_header);
6728 	if ((value = dnvlist_get_string(lun->be_lun->options, "reftemperature",
6729 	    NULL)) != NULL)
6730 		data->temperature = strtol(value, NULL, 0);
6731 	else
6732 		data->temperature = 0xff;
6733 	return (0);
6734 }
6735 
6736 int
6737 ctl_lbp_log_sense_handler(struct ctl_scsiio *ctsio,
6738 			       struct ctl_page_index *page_index,
6739 			       int pc)
6740 {
6741 	struct ctl_lun *lun = CTL_LUN(ctsio);
6742 	struct scsi_log_param_header *phdr;
6743 	uint8_t *data;
6744 	uint64_t val;
6745 
6746 	data = page_index->page_data;
6747 
6748 	if (lun->backend->lun_attr != NULL &&
6749 	    (val = lun->backend->lun_attr(lun->be_lun, "blocksavail"))
6750 	     != UINT64_MAX) {
6751 		phdr = (struct scsi_log_param_header *)data;
6752 		scsi_ulto2b(0x0001, phdr->param_code);
6753 		phdr->param_control = SLP_LBIN | SLP_LP;
6754 		phdr->param_len = 8;
6755 		data = (uint8_t *)(phdr + 1);
6756 		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6757 		data[4] = 0x02; /* per-pool */
6758 		data += phdr->param_len;
6759 	}
6760 
6761 	if (lun->backend->lun_attr != NULL &&
6762 	    (val = lun->backend->lun_attr(lun->be_lun, "blocksused"))
6763 	     != UINT64_MAX) {
6764 		phdr = (struct scsi_log_param_header *)data;
6765 		scsi_ulto2b(0x0002, phdr->param_code);
6766 		phdr->param_control = SLP_LBIN | SLP_LP;
6767 		phdr->param_len = 8;
6768 		data = (uint8_t *)(phdr + 1);
6769 		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6770 		data[4] = 0x01; /* per-LUN */
6771 		data += phdr->param_len;
6772 	}
6773 
6774 	if (lun->backend->lun_attr != NULL &&
6775 	    (val = lun->backend->lun_attr(lun->be_lun, "poolblocksavail"))
6776 	     != UINT64_MAX) {
6777 		phdr = (struct scsi_log_param_header *)data;
6778 		scsi_ulto2b(0x00f1, phdr->param_code);
6779 		phdr->param_control = SLP_LBIN | SLP_LP;
6780 		phdr->param_len = 8;
6781 		data = (uint8_t *)(phdr + 1);
6782 		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6783 		data[4] = 0x02; /* per-pool */
6784 		data += phdr->param_len;
6785 	}
6786 
6787 	if (lun->backend->lun_attr != NULL &&
6788 	    (val = lun->backend->lun_attr(lun->be_lun, "poolblocksused"))
6789 	     != UINT64_MAX) {
6790 		phdr = (struct scsi_log_param_header *)data;
6791 		scsi_ulto2b(0x00f2, phdr->param_code);
6792 		phdr->param_control = SLP_LBIN | SLP_LP;
6793 		phdr->param_len = 8;
6794 		data = (uint8_t *)(phdr + 1);
6795 		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6796 		data[4] = 0x02; /* per-pool */
6797 		data += phdr->param_len;
6798 	}
6799 
6800 	page_index->page_len = data - page_index->page_data;
6801 	return (0);
6802 }
6803 
6804 int
6805 ctl_sap_log_sense_handler(struct ctl_scsiio *ctsio,
6806 			       struct ctl_page_index *page_index,
6807 			       int pc)
6808 {
6809 	struct ctl_lun *lun = CTL_LUN(ctsio);
6810 	struct stat_page *data;
6811 	struct bintime *t;
6812 
6813 	data = (struct stat_page *)page_index->page_data;
6814 
6815 	scsi_ulto2b(SLP_SAP, data->sap.hdr.param_code);
6816 	data->sap.hdr.param_control = SLP_LBIN;
6817 	data->sap.hdr.param_len = sizeof(struct scsi_log_stat_and_perf) -
6818 	    sizeof(struct scsi_log_param_header);
6819 	scsi_u64to8b(lun->stats.operations[CTL_STATS_READ],
6820 	    data->sap.read_num);
6821 	scsi_u64to8b(lun->stats.operations[CTL_STATS_WRITE],
6822 	    data->sap.write_num);
6823 	if (lun->be_lun->blocksize > 0) {
6824 		scsi_u64to8b(lun->stats.bytes[CTL_STATS_WRITE] /
6825 		    lun->be_lun->blocksize, data->sap.recvieved_lba);
6826 		scsi_u64to8b(lun->stats.bytes[CTL_STATS_READ] /
6827 		    lun->be_lun->blocksize, data->sap.transmitted_lba);
6828 	}
6829 	t = &lun->stats.time[CTL_STATS_READ];
6830 	scsi_u64to8b((uint64_t)t->sec * 1000 + t->frac / (UINT64_MAX / 1000),
6831 	    data->sap.read_int);
6832 	t = &lun->stats.time[CTL_STATS_WRITE];
6833 	scsi_u64to8b((uint64_t)t->sec * 1000 + t->frac / (UINT64_MAX / 1000),
6834 	    data->sap.write_int);
6835 	scsi_u64to8b(0, data->sap.weighted_num);
6836 	scsi_u64to8b(0, data->sap.weighted_int);
6837 	scsi_ulto2b(SLP_IT, data->it.hdr.param_code);
6838 	data->it.hdr.param_control = SLP_LBIN;
6839 	data->it.hdr.param_len = sizeof(struct scsi_log_idle_time) -
6840 	    sizeof(struct scsi_log_param_header);
6841 #ifdef CTL_TIME_IO
6842 	scsi_u64to8b(lun->idle_time / SBT_1MS, data->it.idle_int);
6843 #endif
6844 	scsi_ulto2b(SLP_TI, data->ti.hdr.param_code);
6845 	data->it.hdr.param_control = SLP_LBIN;
6846 	data->ti.hdr.param_len = sizeof(struct scsi_log_time_interval) -
6847 	    sizeof(struct scsi_log_param_header);
6848 	scsi_ulto4b(3, data->ti.exponent);
6849 	scsi_ulto4b(1, data->ti.integer);
6850 	return (0);
6851 }
6852 
6853 int
6854 ctl_ie_log_sense_handler(struct ctl_scsiio *ctsio,
6855 			       struct ctl_page_index *page_index,
6856 			       int pc)
6857 {
6858 	struct ctl_lun *lun = CTL_LUN(ctsio);
6859 	struct scsi_log_informational_exceptions *data;
6860 	const char *value;
6861 
6862 	data = (struct scsi_log_informational_exceptions *)page_index->page_data;
6863 
6864 	scsi_ulto2b(SLP_IE_GEN, data->hdr.param_code);
6865 	data->hdr.param_control = SLP_LBIN;
6866 	data->hdr.param_len = sizeof(struct scsi_log_informational_exceptions) -
6867 	    sizeof(struct scsi_log_param_header);
6868 	data->ie_asc = lun->ie_asc;
6869 	data->ie_ascq = lun->ie_ascq;
6870 	if ((value = dnvlist_get_string(lun->be_lun->options, "temperature",
6871 	    NULL)) != NULL)
6872 		data->temperature = strtol(value, NULL, 0);
6873 	else
6874 		data->temperature = 0xff;
6875 	return (0);
6876 }
6877 
6878 int
6879 ctl_log_sense(struct ctl_scsiio *ctsio)
6880 {
6881 	struct ctl_lun *lun = CTL_LUN(ctsio);
6882 	int i, pc, page_code, subpage;
6883 	int alloc_len, total_len;
6884 	struct ctl_page_index *page_index;
6885 	struct scsi_log_sense *cdb;
6886 	struct scsi_log_header *header;
6887 
6888 	CTL_DEBUG_PRINT(("ctl_log_sense\n"));
6889 
6890 	cdb = (struct scsi_log_sense *)ctsio->cdb;
6891 	pc = (cdb->page & SLS_PAGE_CTRL_MASK) >> 6;
6892 	page_code = cdb->page & SLS_PAGE_CODE;
6893 	subpage = cdb->subpage;
6894 	alloc_len = scsi_2btoul(cdb->length);
6895 
6896 	page_index = NULL;
6897 	for (i = 0; i < CTL_NUM_LOG_PAGES; i++) {
6898 		page_index = &lun->log_pages.index[i];
6899 
6900 		/* Look for the right page code */
6901 		if ((page_index->page_code & SL_PAGE_CODE) != page_code)
6902 			continue;
6903 
6904 		/* Look for the right subpage or the subpage wildcard*/
6905 		if (page_index->subpage != subpage)
6906 			continue;
6907 
6908 		break;
6909 	}
6910 	if (i >= CTL_NUM_LOG_PAGES) {
6911 		ctl_set_invalid_field(ctsio,
6912 				      /*sks_valid*/ 1,
6913 				      /*command*/ 1,
6914 				      /*field*/ 2,
6915 				      /*bit_valid*/ 0,
6916 				      /*bit*/ 0);
6917 		ctl_done((union ctl_io *)ctsio);
6918 		return (CTL_RETVAL_COMPLETE);
6919 	}
6920 
6921 	total_len = sizeof(struct scsi_log_header) + page_index->page_len;
6922 
6923 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6924 	ctsio->kern_sg_entries = 0;
6925 	ctsio->kern_rel_offset = 0;
6926 	ctsio->kern_data_len = min(total_len, alloc_len);
6927 	ctsio->kern_total_len = ctsio->kern_data_len;
6928 
6929 	header = (struct scsi_log_header *)ctsio->kern_data_ptr;
6930 	header->page = page_index->page_code;
6931 	if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING)
6932 		header->page |= SL_DS;
6933 	if (page_index->subpage) {
6934 		header->page |= SL_SPF;
6935 		header->subpage = page_index->subpage;
6936 	}
6937 	scsi_ulto2b(page_index->page_len, header->datalen);
6938 
6939 	/*
6940 	 * Call the handler, if it exists, to update the
6941 	 * page to the latest values.
6942 	 */
6943 	if (page_index->sense_handler != NULL)
6944 		page_index->sense_handler(ctsio, page_index, pc);
6945 
6946 	memcpy(header + 1, page_index->page_data, page_index->page_len);
6947 
6948 	ctl_set_success(ctsio);
6949 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6950 	ctsio->be_move_done = ctl_config_move_done;
6951 	ctl_datamove((union ctl_io *)ctsio);
6952 	return (CTL_RETVAL_COMPLETE);
6953 }
6954 
6955 int
6956 ctl_read_capacity(struct ctl_scsiio *ctsio)
6957 {
6958 	struct ctl_lun *lun = CTL_LUN(ctsio);
6959 	struct scsi_read_capacity *cdb;
6960 	struct scsi_read_capacity_data *data;
6961 	uint32_t lba;
6962 
6963 	CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
6964 
6965 	cdb = (struct scsi_read_capacity *)ctsio->cdb;
6966 
6967 	lba = scsi_4btoul(cdb->addr);
6968 	if (((cdb->pmi & SRC_PMI) == 0)
6969 	 && (lba != 0)) {
6970 		ctl_set_invalid_field(/*ctsio*/ ctsio,
6971 				      /*sks_valid*/ 1,
6972 				      /*command*/ 1,
6973 				      /*field*/ 2,
6974 				      /*bit_valid*/ 0,
6975 				      /*bit*/ 0);
6976 		ctl_done((union ctl_io *)ctsio);
6977 		return (CTL_RETVAL_COMPLETE);
6978 	}
6979 
6980 	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
6981 	data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
6982 	ctsio->kern_data_len = sizeof(*data);
6983 	ctsio->kern_total_len = sizeof(*data);
6984 	ctsio->kern_rel_offset = 0;
6985 	ctsio->kern_sg_entries = 0;
6986 
6987 	/*
6988 	 * If the maximum LBA is greater than 0xfffffffe, the user must
6989 	 * issue a SERVICE ACTION IN (16) command, with the read capacity
6990 	 * serivce action set.
6991 	 */
6992 	if (lun->be_lun->maxlba > 0xfffffffe)
6993 		scsi_ulto4b(0xffffffff, data->addr);
6994 	else
6995 		scsi_ulto4b(lun->be_lun->maxlba, data->addr);
6996 
6997 	/*
6998 	 * XXX KDM this may not be 512 bytes...
6999 	 */
7000 	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7001 
7002 	ctl_set_success(ctsio);
7003 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7004 	ctsio->be_move_done = ctl_config_move_done;
7005 	ctl_datamove((union ctl_io *)ctsio);
7006 	return (CTL_RETVAL_COMPLETE);
7007 }
7008 
7009 int
7010 ctl_read_capacity_16(struct ctl_scsiio *ctsio)
7011 {
7012 	struct ctl_lun *lun = CTL_LUN(ctsio);
7013 	struct scsi_read_capacity_16 *cdb;
7014 	struct scsi_read_capacity_data_long *data;
7015 	uint64_t lba;
7016 	uint32_t alloc_len;
7017 
7018 	CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
7019 
7020 	cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
7021 
7022 	alloc_len = scsi_4btoul(cdb->alloc_len);
7023 	lba = scsi_8btou64(cdb->addr);
7024 
7025 	if ((cdb->reladr & SRC16_PMI)
7026 	 && (lba != 0)) {
7027 		ctl_set_invalid_field(/*ctsio*/ ctsio,
7028 				      /*sks_valid*/ 1,
7029 				      /*command*/ 1,
7030 				      /*field*/ 2,
7031 				      /*bit_valid*/ 0,
7032 				      /*bit*/ 0);
7033 		ctl_done((union ctl_io *)ctsio);
7034 		return (CTL_RETVAL_COMPLETE);
7035 	}
7036 
7037 	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7038 	data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
7039 	ctsio->kern_rel_offset = 0;
7040 	ctsio->kern_sg_entries = 0;
7041 	ctsio->kern_data_len = min(sizeof(*data), alloc_len);
7042 	ctsio->kern_total_len = ctsio->kern_data_len;
7043 
7044 	scsi_u64to8b(lun->be_lun->maxlba, data->addr);
7045 	/* XXX KDM this may not be 512 bytes... */
7046 	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7047 	data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
7048 	scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
7049 	if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
7050 		data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
7051 
7052 	ctl_set_success(ctsio);
7053 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7054 	ctsio->be_move_done = ctl_config_move_done;
7055 	ctl_datamove((union ctl_io *)ctsio);
7056 	return (CTL_RETVAL_COMPLETE);
7057 }
7058 
7059 int
7060 ctl_get_lba_status(struct ctl_scsiio *ctsio)
7061 {
7062 	struct ctl_lun *lun = CTL_LUN(ctsio);
7063 	struct scsi_get_lba_status *cdb;
7064 	struct scsi_get_lba_status_data *data;
7065 	struct ctl_lba_len_flags *lbalen;
7066 	uint64_t lba;
7067 	uint32_t alloc_len, total_len;
7068 	int retval;
7069 
7070 	CTL_DEBUG_PRINT(("ctl_get_lba_status\n"));
7071 
7072 	cdb = (struct scsi_get_lba_status *)ctsio->cdb;
7073 	lba = scsi_8btou64(cdb->addr);
7074 	alloc_len = scsi_4btoul(cdb->alloc_len);
7075 
7076 	if (lba > lun->be_lun->maxlba) {
7077 		ctl_set_lba_out_of_range(ctsio, lba);
7078 		ctl_done((union ctl_io *)ctsio);
7079 		return (CTL_RETVAL_COMPLETE);
7080 	}
7081 
7082 	total_len = sizeof(*data) + sizeof(data->descr[0]);
7083 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7084 	data = (struct scsi_get_lba_status_data *)ctsio->kern_data_ptr;
7085 	ctsio->kern_rel_offset = 0;
7086 	ctsio->kern_sg_entries = 0;
7087 	ctsio->kern_data_len = min(total_len, alloc_len);
7088 	ctsio->kern_total_len = ctsio->kern_data_len;
7089 
7090 	/* Fill dummy data in case backend can't tell anything. */
7091 	scsi_ulto4b(4 + sizeof(data->descr[0]), data->length);
7092 	scsi_u64to8b(lba, data->descr[0].addr);
7093 	scsi_ulto4b(MIN(UINT32_MAX, lun->be_lun->maxlba + 1 - lba),
7094 	    data->descr[0].length);
7095 	data->descr[0].status = 0; /* Mapped or unknown. */
7096 
7097 	ctl_set_success(ctsio);
7098 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7099 	ctsio->be_move_done = ctl_config_move_done;
7100 
7101 	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
7102 	lbalen->lba = lba;
7103 	lbalen->len = total_len;
7104 	lbalen->flags = 0;
7105 	retval = lun->backend->config_read((union ctl_io *)ctsio);
7106 	return (retval);
7107 }
7108 
7109 int
7110 ctl_read_defect(struct ctl_scsiio *ctsio)
7111 {
7112 	struct scsi_read_defect_data_10 *ccb10;
7113 	struct scsi_read_defect_data_12 *ccb12;
7114 	struct scsi_read_defect_data_hdr_10 *data10;
7115 	struct scsi_read_defect_data_hdr_12 *data12;
7116 	uint32_t alloc_len, data_len;
7117 	uint8_t format;
7118 
7119 	CTL_DEBUG_PRINT(("ctl_read_defect\n"));
7120 
7121 	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7122 		ccb10 = (struct scsi_read_defect_data_10 *)&ctsio->cdb;
7123 		format = ccb10->format;
7124 		alloc_len = scsi_2btoul(ccb10->alloc_length);
7125 		data_len = sizeof(*data10);
7126 	} else {
7127 		ccb12 = (struct scsi_read_defect_data_12 *)&ctsio->cdb;
7128 		format = ccb12->format;
7129 		alloc_len = scsi_4btoul(ccb12->alloc_length);
7130 		data_len = sizeof(*data12);
7131 	}
7132 	if (alloc_len == 0) {
7133 		ctl_set_success(ctsio);
7134 		ctl_done((union ctl_io *)ctsio);
7135 		return (CTL_RETVAL_COMPLETE);
7136 	}
7137 
7138 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
7139 	ctsio->kern_rel_offset = 0;
7140 	ctsio->kern_sg_entries = 0;
7141 	ctsio->kern_data_len = min(data_len, alloc_len);
7142 	ctsio->kern_total_len = ctsio->kern_data_len;
7143 
7144 	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7145 		data10 = (struct scsi_read_defect_data_hdr_10 *)
7146 		    ctsio->kern_data_ptr;
7147 		data10->format = format;
7148 		scsi_ulto2b(0, data10->length);
7149 	} else {
7150 		data12 = (struct scsi_read_defect_data_hdr_12 *)
7151 		    ctsio->kern_data_ptr;
7152 		data12->format = format;
7153 		scsi_ulto2b(0, data12->generation);
7154 		scsi_ulto4b(0, data12->length);
7155 	}
7156 
7157 	ctl_set_success(ctsio);
7158 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7159 	ctsio->be_move_done = ctl_config_move_done;
7160 	ctl_datamove((union ctl_io *)ctsio);
7161 	return (CTL_RETVAL_COMPLETE);
7162 }
7163 
7164 int
7165 ctl_report_ident_info(struct ctl_scsiio *ctsio)
7166 {
7167 	struct ctl_lun *lun = CTL_LUN(ctsio);
7168 	struct scsi_report_ident_info *cdb;
7169 	struct scsi_report_ident_info_data *rii_ptr;
7170 	struct scsi_report_ident_info_descr *riid_ptr;
7171 	const char *oii, *otii;
7172 	int retval, alloc_len, total_len = 0, len = 0;
7173 
7174 	CTL_DEBUG_PRINT(("ctl_report_ident_info\n"));
7175 
7176 	cdb = (struct scsi_report_ident_info *)ctsio->cdb;
7177 	retval = CTL_RETVAL_COMPLETE;
7178 
7179 	total_len = sizeof(struct scsi_report_ident_info_data);
7180 	switch (cdb->type) {
7181 	case RII_LUII:
7182 		oii = dnvlist_get_string(lun->be_lun->options,
7183 		    "ident_info", NULL);
7184 		if (oii)
7185 			len = strlen(oii);	/* Approximately */
7186 		break;
7187 	case RII_LUTII:
7188 		otii = dnvlist_get_string(lun->be_lun->options,
7189 		    "text_ident_info", NULL);
7190 		if (otii)
7191 			len = strlen(otii) + 1;	/* NULL-terminated */
7192 		break;
7193 	case RII_IIS:
7194 		len = 2 * sizeof(struct scsi_report_ident_info_descr);
7195 		break;
7196 	default:
7197 		ctl_set_invalid_field(/*ctsio*/ ctsio,
7198 				      /*sks_valid*/ 1,
7199 				      /*command*/ 1,
7200 				      /*field*/ 11,
7201 				      /*bit_valid*/ 1,
7202 				      /*bit*/ 2);
7203 		ctl_done((union ctl_io *)ctsio);
7204 		return(retval);
7205 	}
7206 	total_len += len;
7207 	alloc_len = scsi_4btoul(cdb->length);
7208 
7209 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7210 	ctsio->kern_sg_entries = 0;
7211 	ctsio->kern_rel_offset = 0;
7212 	ctsio->kern_data_len = min(total_len, alloc_len);
7213 	ctsio->kern_total_len = ctsio->kern_data_len;
7214 
7215 	rii_ptr = (struct scsi_report_ident_info_data *)ctsio->kern_data_ptr;
7216 	switch (cdb->type) {
7217 	case RII_LUII:
7218 		if (oii) {
7219 			if (oii[0] == '0' && oii[1] == 'x')
7220 				len = hex2bin(oii, (uint8_t *)(rii_ptr + 1), len);
7221 			else
7222 				strncpy((uint8_t *)(rii_ptr + 1), oii, len);
7223 		}
7224 		break;
7225 	case RII_LUTII:
7226 		if (otii)
7227 			strlcpy((uint8_t *)(rii_ptr + 1), otii, len);
7228 		break;
7229 	case RII_IIS:
7230 		riid_ptr = (struct scsi_report_ident_info_descr *)(rii_ptr + 1);
7231 		riid_ptr->type = RII_LUII;
7232 		scsi_ulto2b(0xffff, riid_ptr->length);
7233 		riid_ptr++;
7234 		riid_ptr->type = RII_LUTII;
7235 		scsi_ulto2b(0xffff, riid_ptr->length);
7236 	}
7237 	scsi_ulto2b(len, rii_ptr->length);
7238 
7239 	ctl_set_success(ctsio);
7240 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7241 	ctsio->be_move_done = ctl_config_move_done;
7242 	ctl_datamove((union ctl_io *)ctsio);
7243 	return(retval);
7244 }
7245 
7246 int
7247 ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7248 {
7249 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
7250 	struct ctl_lun *lun = CTL_LUN(ctsio);
7251 	struct scsi_maintenance_in *cdb;
7252 	int retval;
7253 	int alloc_len, ext, total_len = 0, g, pc, pg, ts, os;
7254 	int num_ha_groups, num_target_ports, shared_group;
7255 	struct ctl_port *port;
7256 	struct scsi_target_group_data *rtg_ptr;
7257 	struct scsi_target_group_data_extended *rtg_ext_ptr;
7258 	struct scsi_target_port_group_descriptor *tpg_desc;
7259 
7260 	CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7261 
7262 	cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7263 	retval = CTL_RETVAL_COMPLETE;
7264 
7265 	switch (cdb->byte2 & STG_PDF_MASK) {
7266 	case STG_PDF_LENGTH:
7267 		ext = 0;
7268 		break;
7269 	case STG_PDF_EXTENDED:
7270 		ext = 1;
7271 		break;
7272 	default:
7273 		ctl_set_invalid_field(/*ctsio*/ ctsio,
7274 				      /*sks_valid*/ 1,
7275 				      /*command*/ 1,
7276 				      /*field*/ 2,
7277 				      /*bit_valid*/ 1,
7278 				      /*bit*/ 5);
7279 		ctl_done((union ctl_io *)ctsio);
7280 		return(retval);
7281 	}
7282 
7283 	num_target_ports = 0;
7284 	shared_group = (softc->is_single != 0);
7285 	mtx_lock(&softc->ctl_lock);
7286 	STAILQ_FOREACH(port, &softc->port_list, links) {
7287 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7288 			continue;
7289 		if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7290 			continue;
7291 		num_target_ports++;
7292 		if (port->status & CTL_PORT_STATUS_HA_SHARED)
7293 			shared_group = 1;
7294 	}
7295 	mtx_unlock(&softc->ctl_lock);
7296 	num_ha_groups = (softc->is_single) ? 0 : NUM_HA_SHELVES;
7297 
7298 	if (ext)
7299 		total_len = sizeof(struct scsi_target_group_data_extended);
7300 	else
7301 		total_len = sizeof(struct scsi_target_group_data);
7302 	total_len += sizeof(struct scsi_target_port_group_descriptor) *
7303 		(shared_group + num_ha_groups) +
7304 	    sizeof(struct scsi_target_port_descriptor) * num_target_ports;
7305 
7306 	alloc_len = scsi_4btoul(cdb->length);
7307 
7308 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7309 	ctsio->kern_sg_entries = 0;
7310 	ctsio->kern_rel_offset = 0;
7311 	ctsio->kern_data_len = min(total_len, alloc_len);
7312 	ctsio->kern_total_len = ctsio->kern_data_len;
7313 
7314 	if (ext) {
7315 		rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7316 		    ctsio->kern_data_ptr;
7317 		scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7318 		rtg_ext_ptr->format_type = 0x10;
7319 		rtg_ext_ptr->implicit_transition_time = 0;
7320 		tpg_desc = &rtg_ext_ptr->groups[0];
7321 	} else {
7322 		rtg_ptr = (struct scsi_target_group_data *)
7323 		    ctsio->kern_data_ptr;
7324 		scsi_ulto4b(total_len - 4, rtg_ptr->length);
7325 		tpg_desc = &rtg_ptr->groups[0];
7326 	}
7327 
7328 	mtx_lock(&softc->ctl_lock);
7329 	pg = softc->port_min / softc->port_cnt;
7330 	if (lun->flags & (CTL_LUN_PRIMARY_SC | CTL_LUN_PEER_SC_PRIMARY)) {
7331 		/* Some shelf is known to be primary. */
7332 		if (softc->ha_link == CTL_HA_LINK_OFFLINE)
7333 			os = TPG_ASYMMETRIC_ACCESS_UNAVAILABLE;
7334 		else if (softc->ha_link == CTL_HA_LINK_UNKNOWN)
7335 			os = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7336 		else if (softc->ha_mode == CTL_HA_MODE_ACT_STBY)
7337 			os = TPG_ASYMMETRIC_ACCESS_STANDBY;
7338 		else
7339 			os = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7340 		if (lun->flags & CTL_LUN_PRIMARY_SC) {
7341 			ts = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7342 		} else {
7343 			ts = os;
7344 			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7345 		}
7346 	} else {
7347 		/* No known primary shelf. */
7348 		if (softc->ha_link == CTL_HA_LINK_OFFLINE) {
7349 			ts = TPG_ASYMMETRIC_ACCESS_UNAVAILABLE;
7350 			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7351 		} else if (softc->ha_link == CTL_HA_LINK_UNKNOWN) {
7352 			ts = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7353 			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7354 		} else {
7355 			ts = os = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7356 		}
7357 	}
7358 	if (shared_group) {
7359 		tpg_desc->pref_state = ts;
7360 		tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP |
7361 		    TPG_U_SUP | TPG_T_SUP;
7362 		scsi_ulto2b(1, tpg_desc->target_port_group);
7363 		tpg_desc->status = TPG_IMPLICIT;
7364 		pc = 0;
7365 		STAILQ_FOREACH(port, &softc->port_list, links) {
7366 			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7367 				continue;
7368 			if (!softc->is_single &&
7369 			    (port->status & CTL_PORT_STATUS_HA_SHARED) == 0)
7370 				continue;
7371 			if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7372 				continue;
7373 			scsi_ulto2b(port->targ_port, tpg_desc->descriptors[pc].
7374 			    relative_target_port_identifier);
7375 			pc++;
7376 		}
7377 		tpg_desc->target_port_count = pc;
7378 		tpg_desc = (struct scsi_target_port_group_descriptor *)
7379 		    &tpg_desc->descriptors[pc];
7380 	}
7381 	for (g = 0; g < num_ha_groups; g++) {
7382 		tpg_desc->pref_state = (g == pg) ? ts : os;
7383 		tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP |
7384 		    TPG_U_SUP | TPG_T_SUP;
7385 		scsi_ulto2b(2 + g, tpg_desc->target_port_group);
7386 		tpg_desc->status = TPG_IMPLICIT;
7387 		pc = 0;
7388 		STAILQ_FOREACH(port, &softc->port_list, links) {
7389 			if (port->targ_port < g * softc->port_cnt ||
7390 			    port->targ_port >= (g + 1) * softc->port_cnt)
7391 				continue;
7392 			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7393 				continue;
7394 			if (port->status & CTL_PORT_STATUS_HA_SHARED)
7395 				continue;
7396 			if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7397 				continue;
7398 			scsi_ulto2b(port->targ_port, tpg_desc->descriptors[pc].
7399 			    relative_target_port_identifier);
7400 			pc++;
7401 		}
7402 		tpg_desc->target_port_count = pc;
7403 		tpg_desc = (struct scsi_target_port_group_descriptor *)
7404 		    &tpg_desc->descriptors[pc];
7405 	}
7406 	mtx_unlock(&softc->ctl_lock);
7407 
7408 	ctl_set_success(ctsio);
7409 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7410 	ctsio->be_move_done = ctl_config_move_done;
7411 	ctl_datamove((union ctl_io *)ctsio);
7412 	return(retval);
7413 }
7414 
7415 int
7416 ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7417 {
7418 	struct ctl_lun *lun = CTL_LUN(ctsio);
7419 	struct scsi_report_supported_opcodes *cdb;
7420 	const struct ctl_cmd_entry *entry, *sentry;
7421 	struct scsi_report_supported_opcodes_all *all;
7422 	struct scsi_report_supported_opcodes_descr *descr;
7423 	struct scsi_report_supported_opcodes_one *one;
7424 	int retval;
7425 	int alloc_len, total_len;
7426 	int opcode, service_action, i, j, num;
7427 
7428 	CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7429 
7430 	cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7431 	retval = CTL_RETVAL_COMPLETE;
7432 
7433 	opcode = cdb->requested_opcode;
7434 	service_action = scsi_2btoul(cdb->requested_service_action);
7435 	switch (cdb->options & RSO_OPTIONS_MASK) {
7436 	case RSO_OPTIONS_ALL:
7437 		num = 0;
7438 		for (i = 0; i < 256; i++) {
7439 			entry = &ctl_cmd_table[i];
7440 			if (entry->flags & CTL_CMD_FLAG_SA5) {
7441 				for (j = 0; j < 32; j++) {
7442 					sentry = &((const struct ctl_cmd_entry *)
7443 					    entry->execute)[j];
7444 					if (ctl_cmd_applicable(
7445 					    lun->be_lun->lun_type, sentry))
7446 						num++;
7447 				}
7448 			} else {
7449 				if (ctl_cmd_applicable(lun->be_lun->lun_type,
7450 				    entry))
7451 					num++;
7452 			}
7453 		}
7454 		total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7455 		    num * sizeof(struct scsi_report_supported_opcodes_descr);
7456 		break;
7457 	case RSO_OPTIONS_OC:
7458 		if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7459 			ctl_set_invalid_field(/*ctsio*/ ctsio,
7460 					      /*sks_valid*/ 1,
7461 					      /*command*/ 1,
7462 					      /*field*/ 2,
7463 					      /*bit_valid*/ 1,
7464 					      /*bit*/ 2);
7465 			ctl_done((union ctl_io *)ctsio);
7466 			return (CTL_RETVAL_COMPLETE);
7467 		}
7468 		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7469 		break;
7470 	case RSO_OPTIONS_OC_SA:
7471 		if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7472 		    service_action >= 32) {
7473 			goto invalid;
7474 		}
7475 		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7476 		break;
7477 	case RSO_OPTIONS_OC_ASA:
7478 		if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) != 0 &&
7479 		    service_action >= 32) {
7480 			goto invalid;
7481 		}
7482 		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7483 		break;
7484 	default:
7485 invalid:
7486 		ctl_set_invalid_field(/*ctsio*/ ctsio,
7487 				      /*sks_valid*/ 1,
7488 				      /*command*/ 1,
7489 				      /*field*/ 2,
7490 				      /*bit_valid*/ 1,
7491 				      /*bit*/ 2);
7492 		ctl_done((union ctl_io *)ctsio);
7493 		return (CTL_RETVAL_COMPLETE);
7494 	}
7495 
7496 	alloc_len = scsi_4btoul(cdb->length);
7497 
7498 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7499 	ctsio->kern_sg_entries = 0;
7500 	ctsio->kern_rel_offset = 0;
7501 	ctsio->kern_data_len = min(total_len, alloc_len);
7502 	ctsio->kern_total_len = ctsio->kern_data_len;
7503 
7504 	switch (cdb->options & RSO_OPTIONS_MASK) {
7505 	case RSO_OPTIONS_ALL:
7506 		all = (struct scsi_report_supported_opcodes_all *)
7507 		    ctsio->kern_data_ptr;
7508 		num = 0;
7509 		for (i = 0; i < 256; i++) {
7510 			entry = &ctl_cmd_table[i];
7511 			if (entry->flags & CTL_CMD_FLAG_SA5) {
7512 				for (j = 0; j < 32; j++) {
7513 					sentry = &((const struct ctl_cmd_entry *)
7514 					    entry->execute)[j];
7515 					if (!ctl_cmd_applicable(
7516 					    lun->be_lun->lun_type, sentry))
7517 						continue;
7518 					descr = &all->descr[num++];
7519 					descr->opcode = i;
7520 					scsi_ulto2b(j, descr->service_action);
7521 					descr->flags = RSO_SERVACTV;
7522 					scsi_ulto2b(sentry->length,
7523 					    descr->cdb_length);
7524 				}
7525 			} else {
7526 				if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7527 				    entry))
7528 					continue;
7529 				descr = &all->descr[num++];
7530 				descr->opcode = i;
7531 				scsi_ulto2b(0, descr->service_action);
7532 				descr->flags = 0;
7533 				scsi_ulto2b(entry->length, descr->cdb_length);
7534 			}
7535 		}
7536 		scsi_ulto4b(
7537 		    num * sizeof(struct scsi_report_supported_opcodes_descr),
7538 		    all->length);
7539 		break;
7540 	case RSO_OPTIONS_OC:
7541 		one = (struct scsi_report_supported_opcodes_one *)
7542 		    ctsio->kern_data_ptr;
7543 		entry = &ctl_cmd_table[opcode];
7544 		goto fill_one;
7545 	case RSO_OPTIONS_OC_SA:
7546 		one = (struct scsi_report_supported_opcodes_one *)
7547 		    ctsio->kern_data_ptr;
7548 		entry = &ctl_cmd_table[opcode];
7549 		entry = &((const struct ctl_cmd_entry *)
7550 		    entry->execute)[service_action];
7551 fill_one:
7552 		if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7553 			one->support = 3;
7554 			scsi_ulto2b(entry->length, one->cdb_length);
7555 			one->cdb_usage[0] = opcode;
7556 			memcpy(&one->cdb_usage[1], entry->usage,
7557 			    entry->length - 1);
7558 		} else
7559 			one->support = 1;
7560 		break;
7561 	case RSO_OPTIONS_OC_ASA:
7562 		one = (struct scsi_report_supported_opcodes_one *)
7563 		    ctsio->kern_data_ptr;
7564 		entry = &ctl_cmd_table[opcode];
7565 		if (entry->flags & CTL_CMD_FLAG_SA5) {
7566 			entry = &((const struct ctl_cmd_entry *)
7567 			    entry->execute)[service_action];
7568 		} else if (service_action != 0) {
7569 			one->support = 1;
7570 			break;
7571 		}
7572 		goto fill_one;
7573 	}
7574 
7575 	ctl_set_success(ctsio);
7576 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7577 	ctsio->be_move_done = ctl_config_move_done;
7578 	ctl_datamove((union ctl_io *)ctsio);
7579 	return(retval);
7580 }
7581 
7582 int
7583 ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7584 {
7585 	struct scsi_report_supported_tmf *cdb;
7586 	struct scsi_report_supported_tmf_ext_data *data;
7587 	int retval;
7588 	int alloc_len, total_len;
7589 
7590 	CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7591 
7592 	cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7593 
7594 	retval = CTL_RETVAL_COMPLETE;
7595 
7596 	if (cdb->options & RST_REPD)
7597 		total_len = sizeof(struct scsi_report_supported_tmf_ext_data);
7598 	else
7599 		total_len = sizeof(struct scsi_report_supported_tmf_data);
7600 	alloc_len = scsi_4btoul(cdb->length);
7601 
7602 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7603 	ctsio->kern_sg_entries = 0;
7604 	ctsio->kern_rel_offset = 0;
7605 	ctsio->kern_data_len = min(total_len, alloc_len);
7606 	ctsio->kern_total_len = ctsio->kern_data_len;
7607 
7608 	data = (struct scsi_report_supported_tmf_ext_data *)ctsio->kern_data_ptr;
7609 	data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_QTS |
7610 	    RST_TRS;
7611 	data->byte2 |= RST_QAES | RST_QTSS | RST_ITNRS;
7612 	data->length = total_len - 4;
7613 
7614 	ctl_set_success(ctsio);
7615 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7616 	ctsio->be_move_done = ctl_config_move_done;
7617 	ctl_datamove((union ctl_io *)ctsio);
7618 	return (retval);
7619 }
7620 
7621 int
7622 ctl_report_timestamp(struct ctl_scsiio *ctsio)
7623 {
7624 	struct scsi_report_timestamp *cdb;
7625 	struct scsi_report_timestamp_data *data;
7626 	struct timeval tv;
7627 	int64_t timestamp;
7628 	int retval;
7629 	int alloc_len, total_len;
7630 
7631 	CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7632 
7633 	cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7634 
7635 	retval = CTL_RETVAL_COMPLETE;
7636 
7637 	total_len = sizeof(struct scsi_report_timestamp_data);
7638 	alloc_len = scsi_4btoul(cdb->length);
7639 
7640 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7641 	ctsio->kern_sg_entries = 0;
7642 	ctsio->kern_rel_offset = 0;
7643 	ctsio->kern_data_len = min(total_len, alloc_len);
7644 	ctsio->kern_total_len = ctsio->kern_data_len;
7645 
7646 	data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7647 	scsi_ulto2b(sizeof(*data) - 2, data->length);
7648 	data->origin = RTS_ORIG_OUTSIDE;
7649 	getmicrotime(&tv);
7650 	timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7651 	scsi_ulto4b(timestamp >> 16, data->timestamp);
7652 	scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7653 
7654 	ctl_set_success(ctsio);
7655 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7656 	ctsio->be_move_done = ctl_config_move_done;
7657 	ctl_datamove((union ctl_io *)ctsio);
7658 	return (retval);
7659 }
7660 
7661 int
7662 ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7663 {
7664 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
7665 	struct ctl_lun *lun = CTL_LUN(ctsio);
7666 	struct scsi_per_res_in *cdb;
7667 	int alloc_len, total_len = 0;
7668 	/* struct scsi_per_res_in_rsrv in_data; */
7669 	uint64_t key;
7670 
7671 	CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7672 
7673 	cdb = (struct scsi_per_res_in *)ctsio->cdb;
7674 
7675 	alloc_len = scsi_2btoul(cdb->length);
7676 
7677 retry:
7678 	mtx_lock(&lun->lun_lock);
7679 	switch (cdb->action) {
7680 	case SPRI_RK: /* read keys */
7681 		total_len = sizeof(struct scsi_per_res_in_keys) +
7682 			lun->pr_key_count *
7683 			sizeof(struct scsi_per_res_key);
7684 		break;
7685 	case SPRI_RR: /* read reservation */
7686 		if (lun->flags & CTL_LUN_PR_RESERVED)
7687 			total_len = sizeof(struct scsi_per_res_in_rsrv);
7688 		else
7689 			total_len = sizeof(struct scsi_per_res_in_header);
7690 		break;
7691 	case SPRI_RC: /* report capabilities */
7692 		total_len = sizeof(struct scsi_per_res_cap);
7693 		break;
7694 	case SPRI_RS: /* read full status */
7695 		total_len = sizeof(struct scsi_per_res_in_header) +
7696 		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7697 		    lun->pr_key_count;
7698 		break;
7699 	default:
7700 		panic("%s: Invalid PR type %#x", __func__, cdb->action);
7701 	}
7702 	mtx_unlock(&lun->lun_lock);
7703 
7704 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7705 	ctsio->kern_rel_offset = 0;
7706 	ctsio->kern_sg_entries = 0;
7707 	ctsio->kern_data_len = min(total_len, alloc_len);
7708 	ctsio->kern_total_len = ctsio->kern_data_len;
7709 
7710 	mtx_lock(&lun->lun_lock);
7711 	switch (cdb->action) {
7712 	case SPRI_RK: { // read keys
7713         struct scsi_per_res_in_keys *res_keys;
7714 		int i, key_count;
7715 
7716 		res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7717 
7718 		/*
7719 		 * We had to drop the lock to allocate our buffer, which
7720 		 * leaves time for someone to come in with another
7721 		 * persistent reservation.  (That is unlikely, though,
7722 		 * since this should be the only persistent reservation
7723 		 * command active right now.)
7724 		 */
7725 		if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7726 		    (lun->pr_key_count *
7727 		     sizeof(struct scsi_per_res_key)))){
7728 			mtx_unlock(&lun->lun_lock);
7729 			free(ctsio->kern_data_ptr, M_CTL);
7730 			printf("%s: reservation length changed, retrying\n",
7731 			       __func__);
7732 			goto retry;
7733 		}
7734 
7735 		scsi_ulto4b(lun->pr_generation, res_keys->header.generation);
7736 
7737 		scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7738 			     lun->pr_key_count, res_keys->header.length);
7739 
7740 		for (i = 0, key_count = 0; i < CTL_MAX_INITIATORS; i++) {
7741 			if ((key = ctl_get_prkey(lun, i)) == 0)
7742 				continue;
7743 
7744 			/*
7745 			 * We used lun->pr_key_count to calculate the
7746 			 * size to allocate.  If it turns out the number of
7747 			 * initiators with the registered flag set is
7748 			 * larger than that (i.e. they haven't been kept in
7749 			 * sync), we've got a problem.
7750 			 */
7751 			if (key_count >= lun->pr_key_count) {
7752 				key_count++;
7753 				continue;
7754 			}
7755 			scsi_u64to8b(key, res_keys->keys[key_count].key);
7756 			key_count++;
7757 		}
7758 		break;
7759 	}
7760 	case SPRI_RR: { // read reservation
7761 		struct scsi_per_res_in_rsrv *res;
7762 		int tmp_len, header_only;
7763 
7764 		res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7765 
7766 		scsi_ulto4b(lun->pr_generation, res->header.generation);
7767 
7768 		if (lun->flags & CTL_LUN_PR_RESERVED)
7769 		{
7770 			tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7771 			scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7772 				    res->header.length);
7773 			header_only = 0;
7774 		} else {
7775 			tmp_len = sizeof(struct scsi_per_res_in_header);
7776 			scsi_ulto4b(0, res->header.length);
7777 			header_only = 1;
7778 		}
7779 
7780 		/*
7781 		 * We had to drop the lock to allocate our buffer, which
7782 		 * leaves time for someone to come in with another
7783 		 * persistent reservation.  (That is unlikely, though,
7784 		 * since this should be the only persistent reservation
7785 		 * command active right now.)
7786 		 */
7787 		if (tmp_len != total_len) {
7788 			mtx_unlock(&lun->lun_lock);
7789 			free(ctsio->kern_data_ptr, M_CTL);
7790 			printf("%s: reservation status changed, retrying\n",
7791 			       __func__);
7792 			goto retry;
7793 		}
7794 
7795 		/*
7796 		 * No reservation held, so we're done.
7797 		 */
7798 		if (header_only != 0)
7799 			break;
7800 
7801 		/*
7802 		 * If the registration is an All Registrants type, the key
7803 		 * is 0, since it doesn't really matter.
7804 		 */
7805 		if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7806 			scsi_u64to8b(ctl_get_prkey(lun, lun->pr_res_idx),
7807 			    res->data.reservation);
7808 		}
7809 		res->data.scopetype = lun->pr_res_type;
7810 		break;
7811 	}
7812 	case SPRI_RC:     //report capabilities
7813 	{
7814 		struct scsi_per_res_cap *res_cap;
7815 		uint16_t type_mask;
7816 
7817 		res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7818 		scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7819 		res_cap->flags1 = SPRI_CRH;
7820 		res_cap->flags2 = SPRI_TMV | SPRI_ALLOW_5;
7821 		type_mask = SPRI_TM_WR_EX_AR |
7822 			    SPRI_TM_EX_AC_RO |
7823 			    SPRI_TM_WR_EX_RO |
7824 			    SPRI_TM_EX_AC |
7825 			    SPRI_TM_WR_EX |
7826 			    SPRI_TM_EX_AC_AR;
7827 		scsi_ulto2b(type_mask, res_cap->type_mask);
7828 		break;
7829 	}
7830 	case SPRI_RS: { // read full status
7831 		struct scsi_per_res_in_full *res_status;
7832 		struct scsi_per_res_in_full_desc *res_desc;
7833 		struct ctl_port *port;
7834 		int i, len;
7835 
7836 		res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7837 
7838 		/*
7839 		 * We had to drop the lock to allocate our buffer, which
7840 		 * leaves time for someone to come in with another
7841 		 * persistent reservation.  (That is unlikely, though,
7842 		 * since this should be the only persistent reservation
7843 		 * command active right now.)
7844 		 */
7845 		if (total_len < (sizeof(struct scsi_per_res_in_header) +
7846 		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7847 		     lun->pr_key_count)){
7848 			mtx_unlock(&lun->lun_lock);
7849 			free(ctsio->kern_data_ptr, M_CTL);
7850 			printf("%s: reservation length changed, retrying\n",
7851 			       __func__);
7852 			goto retry;
7853 		}
7854 
7855 		scsi_ulto4b(lun->pr_generation, res_status->header.generation);
7856 
7857 		res_desc = &res_status->desc[0];
7858 		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7859 			if ((key = ctl_get_prkey(lun, i)) == 0)
7860 				continue;
7861 
7862 			scsi_u64to8b(key, res_desc->res_key.key);
7863 			if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7864 			    (lun->pr_res_idx == i ||
7865 			     lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7866 				res_desc->flags = SPRI_FULL_R_HOLDER;
7867 				res_desc->scopetype = lun->pr_res_type;
7868 			}
7869 			scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7870 			    res_desc->rel_trgt_port_id);
7871 			len = 0;
7872 			port = softc->ctl_ports[i / CTL_MAX_INIT_PER_PORT];
7873 			if (port != NULL)
7874 				len = ctl_create_iid(port,
7875 				    i % CTL_MAX_INIT_PER_PORT,
7876 				    res_desc->transport_id);
7877 			scsi_ulto4b(len, res_desc->additional_length);
7878 			res_desc = (struct scsi_per_res_in_full_desc *)
7879 			    &res_desc->transport_id[len];
7880 		}
7881 		scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7882 		    res_status->header.length);
7883 		break;
7884 	}
7885 	default:
7886 		panic("%s: Invalid PR type %#x", __func__, cdb->action);
7887 	}
7888 	mtx_unlock(&lun->lun_lock);
7889 
7890 	ctl_set_success(ctsio);
7891 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7892 	ctsio->be_move_done = ctl_config_move_done;
7893 	ctl_datamove((union ctl_io *)ctsio);
7894 	return (CTL_RETVAL_COMPLETE);
7895 }
7896 
7897 /*
7898  * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
7899  * it should return.
7900  */
7901 static int
7902 ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
7903 		uint64_t sa_res_key, uint8_t type, uint32_t residx,
7904 		struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
7905 		struct scsi_per_res_out_parms* param)
7906 {
7907 	union ctl_ha_msg persis_io;
7908 	int i;
7909 
7910 	mtx_lock(&lun->lun_lock);
7911 	if (sa_res_key == 0) {
7912 		if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
7913 			/* validate scope and type */
7914 			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7915 			     SPR_LU_SCOPE) {
7916 				mtx_unlock(&lun->lun_lock);
7917 				ctl_set_invalid_field(/*ctsio*/ ctsio,
7918 						      /*sks_valid*/ 1,
7919 						      /*command*/ 1,
7920 						      /*field*/ 2,
7921 						      /*bit_valid*/ 1,
7922 						      /*bit*/ 4);
7923 				ctl_done((union ctl_io *)ctsio);
7924 				return (1);
7925 			}
7926 
7927 		        if (type>8 || type==2 || type==4 || type==0) {
7928 				mtx_unlock(&lun->lun_lock);
7929 				ctl_set_invalid_field(/*ctsio*/ ctsio,
7930        	           				      /*sks_valid*/ 1,
7931 						      /*command*/ 1,
7932 						      /*field*/ 2,
7933 						      /*bit_valid*/ 1,
7934 						      /*bit*/ 0);
7935 				ctl_done((union ctl_io *)ctsio);
7936 				return (1);
7937 		        }
7938 
7939 			/*
7940 			 * Unregister everybody else and build UA for
7941 			 * them
7942 			 */
7943 			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
7944 				if (i == residx || ctl_get_prkey(lun, i) == 0)
7945 					continue;
7946 
7947 				ctl_clr_prkey(lun, i);
7948 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7949 			}
7950 			lun->pr_key_count = 1;
7951 			lun->pr_res_type = type;
7952 			if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
7953 			    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
7954 				lun->pr_res_idx = residx;
7955 			lun->pr_generation++;
7956 			mtx_unlock(&lun->lun_lock);
7957 
7958 			/* send msg to other side */
7959 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7960 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7961 			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7962 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
7963 			persis_io.pr.pr_info.res_type = type;
7964 			memcpy(persis_io.pr.pr_info.sa_res_key,
7965 			       param->serv_act_res_key,
7966 			       sizeof(param->serv_act_res_key));
7967 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7968 			    sizeof(persis_io.pr), M_WAITOK);
7969 		} else {
7970 			/* not all registrants */
7971 			mtx_unlock(&lun->lun_lock);
7972 			free(ctsio->kern_data_ptr, M_CTL);
7973 			ctl_set_invalid_field(ctsio,
7974 					      /*sks_valid*/ 1,
7975 					      /*command*/ 0,
7976 					      /*field*/ 8,
7977 					      /*bit_valid*/ 0,
7978 					      /*bit*/ 0);
7979 			ctl_done((union ctl_io *)ctsio);
7980 			return (1);
7981 		}
7982 	} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
7983 		|| !(lun->flags & CTL_LUN_PR_RESERVED)) {
7984 		int found = 0;
7985 
7986 		if (res_key == sa_res_key) {
7987 			/* special case */
7988 			/*
7989 			 * The spec implies this is not good but doesn't
7990 			 * say what to do. There are two choices either
7991 			 * generate a res conflict or check condition
7992 			 * with illegal field in parameter data. Since
7993 			 * that is what is done when the sa_res_key is
7994 			 * zero I'll take that approach since this has
7995 			 * to do with the sa_res_key.
7996 			 */
7997 			mtx_unlock(&lun->lun_lock);
7998 			free(ctsio->kern_data_ptr, M_CTL);
7999 			ctl_set_invalid_field(ctsio,
8000 					      /*sks_valid*/ 1,
8001 					      /*command*/ 0,
8002 					      /*field*/ 8,
8003 					      /*bit_valid*/ 0,
8004 					      /*bit*/ 0);
8005 			ctl_done((union ctl_io *)ctsio);
8006 			return (1);
8007 		}
8008 
8009 		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8010 			if (ctl_get_prkey(lun, i) != sa_res_key)
8011 				continue;
8012 
8013 			found = 1;
8014 			ctl_clr_prkey(lun, i);
8015 			lun->pr_key_count--;
8016 			ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8017 		}
8018 		if (!found) {
8019 			mtx_unlock(&lun->lun_lock);
8020 			free(ctsio->kern_data_ptr, M_CTL);
8021 			ctl_set_reservation_conflict(ctsio);
8022 			ctl_done((union ctl_io *)ctsio);
8023 			return (CTL_RETVAL_COMPLETE);
8024 		}
8025 		lun->pr_generation++;
8026 		mtx_unlock(&lun->lun_lock);
8027 
8028 		/* send msg to other side */
8029 		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8030 		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8031 		persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8032 		persis_io.pr.pr_info.residx = lun->pr_res_idx;
8033 		persis_io.pr.pr_info.res_type = type;
8034 		memcpy(persis_io.pr.pr_info.sa_res_key,
8035 		       param->serv_act_res_key,
8036 		       sizeof(param->serv_act_res_key));
8037 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8038 		    sizeof(persis_io.pr), M_WAITOK);
8039 	} else {
8040 		/* Reserved but not all registrants */
8041 		/* sa_res_key is res holder */
8042 		if (sa_res_key == ctl_get_prkey(lun, lun->pr_res_idx)) {
8043 			/* validate scope and type */
8044 			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8045 			     SPR_LU_SCOPE) {
8046 				mtx_unlock(&lun->lun_lock);
8047 				ctl_set_invalid_field(/*ctsio*/ ctsio,
8048 						      /*sks_valid*/ 1,
8049 						      /*command*/ 1,
8050 						      /*field*/ 2,
8051 						      /*bit_valid*/ 1,
8052 						      /*bit*/ 4);
8053 				ctl_done((union ctl_io *)ctsio);
8054 				return (1);
8055 			}
8056 
8057 			if (type>8 || type==2 || type==4 || type==0) {
8058 				mtx_unlock(&lun->lun_lock);
8059 				ctl_set_invalid_field(/*ctsio*/ ctsio,
8060 						      /*sks_valid*/ 1,
8061 						      /*command*/ 1,
8062 						      /*field*/ 2,
8063 						      /*bit_valid*/ 1,
8064 						      /*bit*/ 0);
8065 				ctl_done((union ctl_io *)ctsio);
8066 				return (1);
8067 			}
8068 
8069 			/*
8070 			 * Do the following:
8071 			 * if sa_res_key != res_key remove all
8072 			 * registrants w/sa_res_key and generate UA
8073 			 * for these registrants(Registrations
8074 			 * Preempted) if it wasn't an exclusive
8075 			 * reservation generate UA(Reservations
8076 			 * Preempted) for all other registered nexuses
8077 			 * if the type has changed. Establish the new
8078 			 * reservation and holder. If res_key and
8079 			 * sa_res_key are the same do the above
8080 			 * except don't unregister the res holder.
8081 			 */
8082 
8083 			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
8084 				if (i == residx || ctl_get_prkey(lun, i) == 0)
8085 					continue;
8086 
8087 				if (sa_res_key == ctl_get_prkey(lun, i)) {
8088 					ctl_clr_prkey(lun, i);
8089 					lun->pr_key_count--;
8090 					ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8091 				} else if (type != lun->pr_res_type &&
8092 				    (lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8093 				     lun->pr_res_type == SPR_TYPE_EX_AC_RO)) {
8094 					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8095 				}
8096 			}
8097 			lun->pr_res_type = type;
8098 			if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8099 			    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8100 				lun->pr_res_idx = residx;
8101 			else
8102 				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8103 			lun->pr_generation++;
8104 			mtx_unlock(&lun->lun_lock);
8105 
8106 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8107 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8108 			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8109 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8110 			persis_io.pr.pr_info.res_type = type;
8111 			memcpy(persis_io.pr.pr_info.sa_res_key,
8112 			       param->serv_act_res_key,
8113 			       sizeof(param->serv_act_res_key));
8114 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8115 			    sizeof(persis_io.pr), M_WAITOK);
8116 		} else {
8117 			/*
8118 			 * sa_res_key is not the res holder just
8119 			 * remove registrants
8120 			 */
8121 			int found=0;
8122 
8123 			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8124 				if (sa_res_key != ctl_get_prkey(lun, i))
8125 					continue;
8126 
8127 				found = 1;
8128 				ctl_clr_prkey(lun, i);
8129 				lun->pr_key_count--;
8130 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8131 			}
8132 
8133 			if (!found) {
8134 				mtx_unlock(&lun->lun_lock);
8135 				free(ctsio->kern_data_ptr, M_CTL);
8136 				ctl_set_reservation_conflict(ctsio);
8137 				ctl_done((union ctl_io *)ctsio);
8138 		        	return (1);
8139 			}
8140 			lun->pr_generation++;
8141 			mtx_unlock(&lun->lun_lock);
8142 
8143 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8144 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8145 			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8146 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8147 			persis_io.pr.pr_info.res_type = type;
8148 			memcpy(persis_io.pr.pr_info.sa_res_key,
8149 			       param->serv_act_res_key,
8150 			       sizeof(param->serv_act_res_key));
8151 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8152 			    sizeof(persis_io.pr), M_WAITOK);
8153 		}
8154 	}
8155 	return (0);
8156 }
8157 
8158 static void
8159 ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8160 {
8161 	uint64_t sa_res_key;
8162 	int i;
8163 
8164 	sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8165 
8166 	if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8167 	 || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8168 	 || sa_res_key != ctl_get_prkey(lun, lun->pr_res_idx)) {
8169 		if (sa_res_key == 0) {
8170 			/*
8171 			 * Unregister everybody else and build UA for
8172 			 * them
8173 			 */
8174 			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
8175 				if (i == msg->pr.pr_info.residx ||
8176 				    ctl_get_prkey(lun, i) == 0)
8177 					continue;
8178 
8179 				ctl_clr_prkey(lun, i);
8180 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8181 			}
8182 
8183 			lun->pr_key_count = 1;
8184 			lun->pr_res_type = msg->pr.pr_info.res_type;
8185 			if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8186 			    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8187 				lun->pr_res_idx = msg->pr.pr_info.residx;
8188 		} else {
8189 		        for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8190 				if (sa_res_key == ctl_get_prkey(lun, i))
8191 					continue;
8192 
8193 				ctl_clr_prkey(lun, i);
8194 				lun->pr_key_count--;
8195 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8196 			}
8197 		}
8198 	} else {
8199 		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8200 			if (i == msg->pr.pr_info.residx ||
8201 			    ctl_get_prkey(lun, i) == 0)
8202 				continue;
8203 
8204 			if (sa_res_key == ctl_get_prkey(lun, i)) {
8205 				ctl_clr_prkey(lun, i);
8206 				lun->pr_key_count--;
8207 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8208 			} else if (msg->pr.pr_info.res_type != lun->pr_res_type
8209 			    && (lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8210 			     lun->pr_res_type == SPR_TYPE_EX_AC_RO)) {
8211 				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8212 			}
8213 		}
8214 		lun->pr_res_type = msg->pr.pr_info.res_type;
8215 		if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8216 		    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8217 			lun->pr_res_idx = msg->pr.pr_info.residx;
8218 		else
8219 			lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8220 	}
8221 	lun->pr_generation++;
8222 
8223 }
8224 
8225 int
8226 ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8227 {
8228 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
8229 	struct ctl_lun *lun = CTL_LUN(ctsio);
8230 	int retval;
8231 	uint32_t param_len;
8232 	struct scsi_per_res_out *cdb;
8233 	struct scsi_per_res_out_parms* param;
8234 	uint32_t residx;
8235 	uint64_t res_key, sa_res_key, key;
8236 	uint8_t type;
8237 	union ctl_ha_msg persis_io;
8238 	int    i;
8239 
8240 	CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8241 
8242 	cdb = (struct scsi_per_res_out *)ctsio->cdb;
8243 	retval = CTL_RETVAL_COMPLETE;
8244 
8245 	/*
8246 	 * We only support whole-LUN scope.  The scope & type are ignored for
8247 	 * register, register and ignore existing key and clear.
8248 	 * We sometimes ignore scope and type on preempts too!!
8249 	 * Verify reservation type here as well.
8250 	 */
8251 	type = cdb->scope_type & SPR_TYPE_MASK;
8252 	if ((cdb->action == SPRO_RESERVE)
8253 	 || (cdb->action == SPRO_RELEASE)) {
8254 		if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8255 			ctl_set_invalid_field(/*ctsio*/ ctsio,
8256 					      /*sks_valid*/ 1,
8257 					      /*command*/ 1,
8258 					      /*field*/ 2,
8259 					      /*bit_valid*/ 1,
8260 					      /*bit*/ 4);
8261 			ctl_done((union ctl_io *)ctsio);
8262 			return (CTL_RETVAL_COMPLETE);
8263 		}
8264 
8265 		if (type>8 || type==2 || type==4 || type==0) {
8266 			ctl_set_invalid_field(/*ctsio*/ ctsio,
8267 					      /*sks_valid*/ 1,
8268 					      /*command*/ 1,
8269 					      /*field*/ 2,
8270 					      /*bit_valid*/ 1,
8271 					      /*bit*/ 0);
8272 			ctl_done((union ctl_io *)ctsio);
8273 			return (CTL_RETVAL_COMPLETE);
8274 		}
8275 	}
8276 
8277 	param_len = scsi_4btoul(cdb->length);
8278 
8279 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8280 		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8281 		ctsio->kern_data_len = param_len;
8282 		ctsio->kern_total_len = param_len;
8283 		ctsio->kern_rel_offset = 0;
8284 		ctsio->kern_sg_entries = 0;
8285 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8286 		ctsio->be_move_done = ctl_config_move_done;
8287 		ctl_datamove((union ctl_io *)ctsio);
8288 
8289 		return (CTL_RETVAL_COMPLETE);
8290 	}
8291 
8292 	param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8293 
8294 	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
8295 	res_key = scsi_8btou64(param->res_key.key);
8296 	sa_res_key = scsi_8btou64(param->serv_act_res_key);
8297 
8298 	/*
8299 	 * Validate the reservation key here except for SPRO_REG_IGNO
8300 	 * This must be done for all other service actions
8301 	 */
8302 	if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8303 		mtx_lock(&lun->lun_lock);
8304 		if ((key = ctl_get_prkey(lun, residx)) != 0) {
8305 			if (res_key != key) {
8306 				/*
8307 				 * The current key passed in doesn't match
8308 				 * the one the initiator previously
8309 				 * registered.
8310 				 */
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 		} else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8318 			/*
8319 			 * We are not registered
8320 			 */
8321 			mtx_unlock(&lun->lun_lock);
8322 			free(ctsio->kern_data_ptr, M_CTL);
8323 			ctl_set_reservation_conflict(ctsio);
8324 			ctl_done((union ctl_io *)ctsio);
8325 			return (CTL_RETVAL_COMPLETE);
8326 		} else if (res_key != 0) {
8327 			/*
8328 			 * We are not registered and trying to register but
8329 			 * the register key isn't zero.
8330 			 */
8331 			mtx_unlock(&lun->lun_lock);
8332 			free(ctsio->kern_data_ptr, M_CTL);
8333 			ctl_set_reservation_conflict(ctsio);
8334 			ctl_done((union ctl_io *)ctsio);
8335 			return (CTL_RETVAL_COMPLETE);
8336 		}
8337 		mtx_unlock(&lun->lun_lock);
8338 	}
8339 
8340 	switch (cdb->action & SPRO_ACTION_MASK) {
8341 	case SPRO_REGISTER:
8342 	case SPRO_REG_IGNO: {
8343 		/*
8344 		 * We don't support any of these options, as we report in
8345 		 * the read capabilities request (see
8346 		 * ctl_persistent_reserve_in(), above).
8347 		 */
8348 		if ((param->flags & SPR_SPEC_I_PT)
8349 		 || (param->flags & SPR_ALL_TG_PT)
8350 		 || (param->flags & SPR_APTPL)) {
8351 			int bit_ptr;
8352 
8353 			if (param->flags & SPR_APTPL)
8354 				bit_ptr = 0;
8355 			else if (param->flags & SPR_ALL_TG_PT)
8356 				bit_ptr = 2;
8357 			else /* SPR_SPEC_I_PT */
8358 				bit_ptr = 3;
8359 
8360 			free(ctsio->kern_data_ptr, M_CTL);
8361 			ctl_set_invalid_field(ctsio,
8362 					      /*sks_valid*/ 1,
8363 					      /*command*/ 0,
8364 					      /*field*/ 20,
8365 					      /*bit_valid*/ 1,
8366 					      /*bit*/ bit_ptr);
8367 			ctl_done((union ctl_io *)ctsio);
8368 			return (CTL_RETVAL_COMPLETE);
8369 		}
8370 
8371 		mtx_lock(&lun->lun_lock);
8372 
8373 		/*
8374 		 * The initiator wants to clear the
8375 		 * key/unregister.
8376 		 */
8377 		if (sa_res_key == 0) {
8378 			if ((res_key == 0
8379 			  && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8380 			 || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8381 			  && ctl_get_prkey(lun, residx) == 0)) {
8382 				mtx_unlock(&lun->lun_lock);
8383 				goto done;
8384 			}
8385 
8386 			ctl_clr_prkey(lun, residx);
8387 			lun->pr_key_count--;
8388 
8389 			if (residx == lun->pr_res_idx) {
8390 				lun->flags &= ~CTL_LUN_PR_RESERVED;
8391 				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8392 
8393 				if ((lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8394 				     lun->pr_res_type == SPR_TYPE_EX_AC_RO) &&
8395 				    lun->pr_key_count) {
8396 					/*
8397 					 * If the reservation is a registrants
8398 					 * only type we need to generate a UA
8399 					 * for other registered inits.  The
8400 					 * sense code should be RESERVATIONS
8401 					 * RELEASED
8402 					 */
8403 
8404 					for (i = softc->init_min; i < softc->init_max; i++){
8405 						if (ctl_get_prkey(lun, i) == 0)
8406 							continue;
8407 						ctl_est_ua(lun, i,
8408 						    CTL_UA_RES_RELEASE);
8409 					}
8410 				}
8411 				lun->pr_res_type = 0;
8412 			} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8413 				if (lun->pr_key_count==0) {
8414 					lun->flags &= ~CTL_LUN_PR_RESERVED;
8415 					lun->pr_res_type = 0;
8416 					lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8417 				}
8418 			}
8419 			lun->pr_generation++;
8420 			mtx_unlock(&lun->lun_lock);
8421 
8422 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8423 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8424 			persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8425 			persis_io.pr.pr_info.residx = residx;
8426 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8427 			    sizeof(persis_io.pr), M_WAITOK);
8428 		} else /* sa_res_key != 0 */ {
8429 			/*
8430 			 * If we aren't registered currently then increment
8431 			 * the key count and set the registered flag.
8432 			 */
8433 			ctl_alloc_prkey(lun, residx);
8434 			if (ctl_get_prkey(lun, residx) == 0)
8435 				lun->pr_key_count++;
8436 			ctl_set_prkey(lun, residx, sa_res_key);
8437 			lun->pr_generation++;
8438 			mtx_unlock(&lun->lun_lock);
8439 
8440 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8441 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8442 			persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8443 			persis_io.pr.pr_info.residx = residx;
8444 			memcpy(persis_io.pr.pr_info.sa_res_key,
8445 			       param->serv_act_res_key,
8446 			       sizeof(param->serv_act_res_key));
8447 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8448 			    sizeof(persis_io.pr), M_WAITOK);
8449 		}
8450 
8451 		break;
8452 	}
8453 	case SPRO_RESERVE:
8454 		mtx_lock(&lun->lun_lock);
8455 		if (lun->flags & CTL_LUN_PR_RESERVED) {
8456 			/*
8457 			 * if this isn't the reservation holder and it's
8458 			 * not a "all registrants" type or if the type is
8459 			 * different then we have a conflict
8460 			 */
8461 			if ((lun->pr_res_idx != residx
8462 			  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8463 			 || lun->pr_res_type != type) {
8464 				mtx_unlock(&lun->lun_lock);
8465 				free(ctsio->kern_data_ptr, M_CTL);
8466 				ctl_set_reservation_conflict(ctsio);
8467 				ctl_done((union ctl_io *)ctsio);
8468 				return (CTL_RETVAL_COMPLETE);
8469 			}
8470 			mtx_unlock(&lun->lun_lock);
8471 		} else /* create a reservation */ {
8472 			/*
8473 			 * If it's not an "all registrants" type record
8474 			 * reservation holder
8475 			 */
8476 			if (type != SPR_TYPE_WR_EX_AR
8477 			 && type != SPR_TYPE_EX_AC_AR)
8478 				lun->pr_res_idx = residx; /* Res holder */
8479 			else
8480 				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8481 
8482 			lun->flags |= CTL_LUN_PR_RESERVED;
8483 			lun->pr_res_type = type;
8484 
8485 			mtx_unlock(&lun->lun_lock);
8486 
8487 			/* send msg to other side */
8488 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8489 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8490 			persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8491 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8492 			persis_io.pr.pr_info.res_type = type;
8493 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8494 			    sizeof(persis_io.pr), M_WAITOK);
8495 		}
8496 		break;
8497 
8498 	case SPRO_RELEASE:
8499 		mtx_lock(&lun->lun_lock);
8500 		if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8501 			/* No reservation exists return good status */
8502 			mtx_unlock(&lun->lun_lock);
8503 			goto done;
8504 		}
8505 		/*
8506 		 * Is this nexus a reservation holder?
8507 		 */
8508 		if (lun->pr_res_idx != residx
8509 		 && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8510 			/*
8511 			 * not a res holder return good status but
8512 			 * do nothing
8513 			 */
8514 			mtx_unlock(&lun->lun_lock);
8515 			goto done;
8516 		}
8517 
8518 		if (lun->pr_res_type != type) {
8519 			mtx_unlock(&lun->lun_lock);
8520 			free(ctsio->kern_data_ptr, M_CTL);
8521 			ctl_set_illegal_pr_release(ctsio);
8522 			ctl_done((union ctl_io *)ctsio);
8523 			return (CTL_RETVAL_COMPLETE);
8524 		}
8525 
8526 		/* okay to release */
8527 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8528 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8529 		lun->pr_res_type = 0;
8530 
8531 		/*
8532 		 * If this isn't an exclusive access reservation and NUAR
8533 		 * is not set, generate UA for all other registrants.
8534 		 */
8535 		if (type != SPR_TYPE_EX_AC && type != SPR_TYPE_WR_EX &&
8536 		    (lun->MODE_CTRL.queue_flags & SCP_NUAR) == 0) {
8537 			for (i = softc->init_min; i < softc->init_max; i++) {
8538 				if (i == residx || ctl_get_prkey(lun, i) == 0)
8539 					continue;
8540 				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8541 			}
8542 		}
8543 		mtx_unlock(&lun->lun_lock);
8544 
8545 		/* Send msg to other side */
8546 		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8547 		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8548 		persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8549 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8550 		     sizeof(persis_io.pr), M_WAITOK);
8551 		break;
8552 
8553 	case SPRO_CLEAR:
8554 		/* send msg to other side */
8555 
8556 		mtx_lock(&lun->lun_lock);
8557 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8558 		lun->pr_res_type = 0;
8559 		lun->pr_key_count = 0;
8560 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8561 
8562 		ctl_clr_prkey(lun, residx);
8563 		for (i = 0; i < CTL_MAX_INITIATORS; i++)
8564 			if (ctl_get_prkey(lun, i) != 0) {
8565 				ctl_clr_prkey(lun, i);
8566 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8567 			}
8568 		lun->pr_generation++;
8569 		mtx_unlock(&lun->lun_lock);
8570 
8571 		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8572 		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8573 		persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8574 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8575 		     sizeof(persis_io.pr), M_WAITOK);
8576 		break;
8577 
8578 	case SPRO_PREEMPT:
8579 	case SPRO_PRE_ABO: {
8580 		int nretval;
8581 
8582 		nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8583 					  residx, ctsio, cdb, param);
8584 		if (nretval != 0)
8585 			return (CTL_RETVAL_COMPLETE);
8586 		break;
8587 	}
8588 	default:
8589 		panic("%s: Invalid PR type %#x", __func__, cdb->action);
8590 	}
8591 
8592 done:
8593 	free(ctsio->kern_data_ptr, M_CTL);
8594 	ctl_set_success(ctsio);
8595 	ctl_done((union ctl_io *)ctsio);
8596 
8597 	return (retval);
8598 }
8599 
8600 /*
8601  * This routine is for handling a message from the other SC pertaining to
8602  * persistent reserve out. All the error checking will have been done
8603  * so only performing the action need be done here to keep the two
8604  * in sync.
8605  */
8606 static void
8607 ctl_hndl_per_res_out_on_other_sc(union ctl_io *io)
8608 {
8609 	struct ctl_softc *softc = CTL_SOFTC(io);
8610 	union ctl_ha_msg *msg = (union ctl_ha_msg *)&io->presio.pr_msg;
8611 	struct ctl_lun *lun;
8612 	int i;
8613 	uint32_t residx, targ_lun;
8614 
8615 	targ_lun = msg->hdr.nexus.targ_mapped_lun;
8616 	mtx_lock(&softc->ctl_lock);
8617 	if (targ_lun >= ctl_max_luns ||
8618 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
8619 		mtx_unlock(&softc->ctl_lock);
8620 		return;
8621 	}
8622 	mtx_lock(&lun->lun_lock);
8623 	mtx_unlock(&softc->ctl_lock);
8624 	if (lun->flags & CTL_LUN_DISABLED) {
8625 		mtx_unlock(&lun->lun_lock);
8626 		return;
8627 	}
8628 	residx = ctl_get_initindex(&msg->hdr.nexus);
8629 	switch(msg->pr.pr_info.action) {
8630 	case CTL_PR_REG_KEY:
8631 		ctl_alloc_prkey(lun, msg->pr.pr_info.residx);
8632 		if (ctl_get_prkey(lun, msg->pr.pr_info.residx) == 0)
8633 			lun->pr_key_count++;
8634 		ctl_set_prkey(lun, msg->pr.pr_info.residx,
8635 		    scsi_8btou64(msg->pr.pr_info.sa_res_key));
8636 		lun->pr_generation++;
8637 		break;
8638 
8639 	case CTL_PR_UNREG_KEY:
8640 		ctl_clr_prkey(lun, msg->pr.pr_info.residx);
8641 		lun->pr_key_count--;
8642 
8643 		/* XXX Need to see if the reservation has been released */
8644 		/* if so do we need to generate UA? */
8645 		if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8646 			lun->flags &= ~CTL_LUN_PR_RESERVED;
8647 			lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8648 
8649 			if ((lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8650 			     lun->pr_res_type == SPR_TYPE_EX_AC_RO) &&
8651 			    lun->pr_key_count) {
8652 				/*
8653 				 * If the reservation is a registrants
8654 				 * only type we need to generate a UA
8655 				 * for other registered inits.  The
8656 				 * sense code should be RESERVATIONS
8657 				 * RELEASED
8658 				 */
8659 
8660 				for (i = softc->init_min; i < softc->init_max; i++) {
8661 					if (ctl_get_prkey(lun, i) == 0)
8662 						continue;
8663 
8664 					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8665 				}
8666 			}
8667 			lun->pr_res_type = 0;
8668 		} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8669 			if (lun->pr_key_count==0) {
8670 				lun->flags &= ~CTL_LUN_PR_RESERVED;
8671 				lun->pr_res_type = 0;
8672 				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8673 			}
8674 		}
8675 		lun->pr_generation++;
8676 		break;
8677 
8678 	case CTL_PR_RESERVE:
8679 		lun->flags |= CTL_LUN_PR_RESERVED;
8680 		lun->pr_res_type = msg->pr.pr_info.res_type;
8681 		lun->pr_res_idx = msg->pr.pr_info.residx;
8682 
8683 		break;
8684 
8685 	case CTL_PR_RELEASE:
8686 		/*
8687 		 * If this isn't an exclusive access reservation and NUAR
8688 		 * is not set, generate UA for all other registrants.
8689 		 */
8690 		if (lun->pr_res_type != SPR_TYPE_EX_AC &&
8691 		    lun->pr_res_type != SPR_TYPE_WR_EX &&
8692 		    (lun->MODE_CTRL.queue_flags & SCP_NUAR) == 0) {
8693 			for (i = softc->init_min; i < softc->init_max; i++) {
8694 				if (i == residx || ctl_get_prkey(lun, i) == 0)
8695 					continue;
8696 				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8697 			}
8698 		}
8699 
8700 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8701 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8702 		lun->pr_res_type = 0;
8703 		break;
8704 
8705 	case CTL_PR_PREEMPT:
8706 		ctl_pro_preempt_other(lun, msg);
8707 		break;
8708 	case CTL_PR_CLEAR:
8709 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8710 		lun->pr_res_type = 0;
8711 		lun->pr_key_count = 0;
8712 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8713 
8714 		for (i=0; i < CTL_MAX_INITIATORS; i++) {
8715 			if (ctl_get_prkey(lun, i) == 0)
8716 				continue;
8717 			ctl_clr_prkey(lun, i);
8718 			ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8719 		}
8720 		lun->pr_generation++;
8721 		break;
8722 	}
8723 
8724 	mtx_unlock(&lun->lun_lock);
8725 }
8726 
8727 int
8728 ctl_read_write(struct ctl_scsiio *ctsio)
8729 {
8730 	struct ctl_lun *lun = CTL_LUN(ctsio);
8731 	struct ctl_lba_len_flags *lbalen;
8732 	uint64_t lba;
8733 	uint32_t num_blocks;
8734 	int flags, retval;
8735 	int isread;
8736 
8737 	CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8738 
8739 	flags = 0;
8740 	isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8741 	      || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8742 	switch (ctsio->cdb[0]) {
8743 	case READ_6:
8744 	case WRITE_6: {
8745 		struct scsi_rw_6 *cdb;
8746 
8747 		cdb = (struct scsi_rw_6 *)ctsio->cdb;
8748 
8749 		lba = scsi_3btoul(cdb->addr);
8750 		/* only 5 bits are valid in the most significant address byte */
8751 		lba &= 0x1fffff;
8752 		num_blocks = cdb->length;
8753 		/*
8754 		 * This is correct according to SBC-2.
8755 		 */
8756 		if (num_blocks == 0)
8757 			num_blocks = 256;
8758 		break;
8759 	}
8760 	case READ_10:
8761 	case WRITE_10: {
8762 		struct scsi_rw_10 *cdb;
8763 
8764 		cdb = (struct scsi_rw_10 *)ctsio->cdb;
8765 		if (cdb->byte2 & SRW10_FUA)
8766 			flags |= CTL_LLF_FUA;
8767 		if (cdb->byte2 & SRW10_DPO)
8768 			flags |= CTL_LLF_DPO;
8769 		lba = scsi_4btoul(cdb->addr);
8770 		num_blocks = scsi_2btoul(cdb->length);
8771 		break;
8772 	}
8773 	case WRITE_VERIFY_10: {
8774 		struct scsi_write_verify_10 *cdb;
8775 
8776 		cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
8777 		flags |= CTL_LLF_FUA;
8778 		if (cdb->byte2 & SWV_DPO)
8779 			flags |= CTL_LLF_DPO;
8780 		lba = scsi_4btoul(cdb->addr);
8781 		num_blocks = scsi_2btoul(cdb->length);
8782 		break;
8783 	}
8784 	case READ_12:
8785 	case WRITE_12: {
8786 		struct scsi_rw_12 *cdb;
8787 
8788 		cdb = (struct scsi_rw_12 *)ctsio->cdb;
8789 		if (cdb->byte2 & SRW12_FUA)
8790 			flags |= CTL_LLF_FUA;
8791 		if (cdb->byte2 & SRW12_DPO)
8792 			flags |= CTL_LLF_DPO;
8793 		lba = scsi_4btoul(cdb->addr);
8794 		num_blocks = scsi_4btoul(cdb->length);
8795 		break;
8796 	}
8797 	case WRITE_VERIFY_12: {
8798 		struct scsi_write_verify_12 *cdb;
8799 
8800 		cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
8801 		flags |= CTL_LLF_FUA;
8802 		if (cdb->byte2 & SWV_DPO)
8803 			flags |= CTL_LLF_DPO;
8804 		lba = scsi_4btoul(cdb->addr);
8805 		num_blocks = scsi_4btoul(cdb->length);
8806 		break;
8807 	}
8808 	case READ_16:
8809 	case WRITE_16: {
8810 		struct scsi_rw_16 *cdb;
8811 
8812 		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8813 		if (cdb->byte2 & SRW12_FUA)
8814 			flags |= CTL_LLF_FUA;
8815 		if (cdb->byte2 & SRW12_DPO)
8816 			flags |= CTL_LLF_DPO;
8817 		lba = scsi_8btou64(cdb->addr);
8818 		num_blocks = scsi_4btoul(cdb->length);
8819 		break;
8820 	}
8821 	case WRITE_ATOMIC_16: {
8822 		struct scsi_write_atomic_16 *cdb;
8823 
8824 		if (lun->be_lun->atomicblock == 0) {
8825 			ctl_set_invalid_opcode(ctsio);
8826 			ctl_done((union ctl_io *)ctsio);
8827 			return (CTL_RETVAL_COMPLETE);
8828 		}
8829 
8830 		cdb = (struct scsi_write_atomic_16 *)ctsio->cdb;
8831 		if (cdb->byte2 & SRW12_FUA)
8832 			flags |= CTL_LLF_FUA;
8833 		if (cdb->byte2 & SRW12_DPO)
8834 			flags |= CTL_LLF_DPO;
8835 		lba = scsi_8btou64(cdb->addr);
8836 		num_blocks = scsi_2btoul(cdb->length);
8837 		if (num_blocks > lun->be_lun->atomicblock) {
8838 			ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
8839 			    /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
8840 			    /*bit*/ 0);
8841 			ctl_done((union ctl_io *)ctsio);
8842 			return (CTL_RETVAL_COMPLETE);
8843 		}
8844 		break;
8845 	}
8846 	case WRITE_VERIFY_16: {
8847 		struct scsi_write_verify_16 *cdb;
8848 
8849 		cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
8850 		flags |= CTL_LLF_FUA;
8851 		if (cdb->byte2 & SWV_DPO)
8852 			flags |= CTL_LLF_DPO;
8853 		lba = scsi_8btou64(cdb->addr);
8854 		num_blocks = scsi_4btoul(cdb->length);
8855 		break;
8856 	}
8857 	default:
8858 		/*
8859 		 * We got a command we don't support.  This shouldn't
8860 		 * happen, commands should be filtered out above us.
8861 		 */
8862 		ctl_set_invalid_opcode(ctsio);
8863 		ctl_done((union ctl_io *)ctsio);
8864 
8865 		return (CTL_RETVAL_COMPLETE);
8866 		break; /* NOTREACHED */
8867 	}
8868 
8869 	/*
8870 	 * The first check is to make sure we're in bounds, the second
8871 	 * check is to catch wrap-around problems.  If the lba + num blocks
8872 	 * is less than the lba, then we've wrapped around and the block
8873 	 * range is invalid anyway.
8874 	 */
8875 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8876 	 || ((lba + num_blocks) < lba)) {
8877 		ctl_set_lba_out_of_range(ctsio,
8878 		    MAX(lba, lun->be_lun->maxlba + 1));
8879 		ctl_done((union ctl_io *)ctsio);
8880 		return (CTL_RETVAL_COMPLETE);
8881 	}
8882 
8883 	/*
8884 	 * According to SBC-3, a transfer length of 0 is not an error.
8885 	 * Note that this cannot happen with WRITE(6) or READ(6), since 0
8886 	 * translates to 256 blocks for those commands.
8887 	 */
8888 	if (num_blocks == 0) {
8889 		ctl_set_success(ctsio);
8890 		ctl_done((union ctl_io *)ctsio);
8891 		return (CTL_RETVAL_COMPLETE);
8892 	}
8893 
8894 	/* Set FUA and/or DPO if caches are disabled. */
8895 	if (isread) {
8896 		if ((lun->MODE_CACHING.flags1 & SCP_RCD) != 0)
8897 			flags |= CTL_LLF_FUA | CTL_LLF_DPO;
8898 	} else {
8899 		if ((lun->MODE_CACHING.flags1 & SCP_WCE) == 0)
8900 			flags |= CTL_LLF_FUA;
8901 	}
8902 
8903 	lbalen = (struct ctl_lba_len_flags *)
8904 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8905 	lbalen->lba = lba;
8906 	lbalen->len = num_blocks;
8907 	lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
8908 
8909 	ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
8910 	ctsio->kern_rel_offset = 0;
8911 
8912 	CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
8913 
8914 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8915 	return (retval);
8916 }
8917 
8918 static int
8919 ctl_cnw_cont(union ctl_io *io)
8920 {
8921 	struct ctl_lun *lun = CTL_LUN(io);
8922 	struct ctl_scsiio *ctsio;
8923 	struct ctl_lba_len_flags *lbalen;
8924 	int retval;
8925 
8926 	CTL_IO_ASSERT(io, SCSI);
8927 
8928 	ctsio = &io->scsiio;
8929 	ctsio->io_hdr.status = CTL_STATUS_NONE;
8930 	ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
8931 	lbalen = (struct ctl_lba_len_flags *)
8932 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8933 	lbalen->flags &= ~CTL_LLF_COMPARE;
8934 	lbalen->flags |= CTL_LLF_WRITE;
8935 
8936 	CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
8937 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8938 	return (retval);
8939 }
8940 
8941 int
8942 ctl_cnw(struct ctl_scsiio *ctsio)
8943 {
8944 	struct ctl_lun *lun = CTL_LUN(ctsio);
8945 	struct ctl_lba_len_flags *lbalen;
8946 	uint64_t lba;
8947 	uint32_t num_blocks;
8948 	int flags, retval;
8949 
8950 	CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
8951 
8952 	flags = 0;
8953 	switch (ctsio->cdb[0]) {
8954 	case COMPARE_AND_WRITE: {
8955 		struct scsi_compare_and_write *cdb;
8956 
8957 		cdb = (struct scsi_compare_and_write *)ctsio->cdb;
8958 		if (cdb->byte2 & SRW10_FUA)
8959 			flags |= CTL_LLF_FUA;
8960 		if (cdb->byte2 & SRW10_DPO)
8961 			flags |= CTL_LLF_DPO;
8962 		lba = scsi_8btou64(cdb->addr);
8963 		num_blocks = cdb->length;
8964 		break;
8965 	}
8966 	default:
8967 		/*
8968 		 * We got a command we don't support.  This shouldn't
8969 		 * happen, commands should be filtered out above us.
8970 		 */
8971 		ctl_set_invalid_opcode(ctsio);
8972 		ctl_done((union ctl_io *)ctsio);
8973 
8974 		return (CTL_RETVAL_COMPLETE);
8975 		break; /* NOTREACHED */
8976 	}
8977 
8978 	/*
8979 	 * The first check is to make sure we're in bounds, the second
8980 	 * check is to catch wrap-around problems.  If the lba + num blocks
8981 	 * is less than the lba, then we've wrapped around and the block
8982 	 * range is invalid anyway.
8983 	 */
8984 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8985 	 || ((lba + num_blocks) < lba)) {
8986 		ctl_set_lba_out_of_range(ctsio,
8987 		    MAX(lba, lun->be_lun->maxlba + 1));
8988 		ctl_done((union ctl_io *)ctsio);
8989 		return (CTL_RETVAL_COMPLETE);
8990 	}
8991 
8992 	/*
8993 	 * According to SBC-3, a transfer length of 0 is not an error.
8994 	 */
8995 	if (num_blocks == 0) {
8996 		ctl_set_success(ctsio);
8997 		ctl_done((union ctl_io *)ctsio);
8998 		return (CTL_RETVAL_COMPLETE);
8999 	}
9000 
9001 	/* Set FUA if write cache is disabled. */
9002 	if ((lun->MODE_CACHING.flags1 & SCP_WCE) == 0)
9003 		flags |= CTL_LLF_FUA;
9004 
9005 	ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
9006 	ctsio->kern_rel_offset = 0;
9007 
9008 	/*
9009 	 * Set the IO_CONT flag, so that if this I/O gets passed to
9010 	 * ctl_data_submit_done(), it'll get passed back to
9011 	 * ctl_ctl_cnw_cont() for further processing.
9012 	 */
9013 	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
9014 	ctsio->io_cont = ctl_cnw_cont;
9015 
9016 	lbalen = (struct ctl_lba_len_flags *)
9017 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9018 	lbalen->lba = lba;
9019 	lbalen->len = num_blocks;
9020 	lbalen->flags = CTL_LLF_COMPARE | flags;
9021 
9022 	CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
9023 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9024 	return (retval);
9025 }
9026 
9027 int
9028 ctl_verify(struct ctl_scsiio *ctsio)
9029 {
9030 	struct ctl_lun *lun = CTL_LUN(ctsio);
9031 	struct ctl_lba_len_flags *lbalen;
9032 	uint64_t lba;
9033 	uint32_t num_blocks;
9034 	int bytchk, flags;
9035 	int retval;
9036 
9037 	CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
9038 
9039 	bytchk = 0;
9040 	flags = CTL_LLF_FUA;
9041 	switch (ctsio->cdb[0]) {
9042 	case VERIFY_10: {
9043 		struct scsi_verify_10 *cdb;
9044 
9045 		cdb = (struct scsi_verify_10 *)ctsio->cdb;
9046 		if (cdb->byte2 & SVFY_BYTCHK)
9047 			bytchk = 1;
9048 		if (cdb->byte2 & SVFY_DPO)
9049 			flags |= CTL_LLF_DPO;
9050 		lba = scsi_4btoul(cdb->addr);
9051 		num_blocks = scsi_2btoul(cdb->length);
9052 		break;
9053 	}
9054 	case VERIFY_12: {
9055 		struct scsi_verify_12 *cdb;
9056 
9057 		cdb = (struct scsi_verify_12 *)ctsio->cdb;
9058 		if (cdb->byte2 & SVFY_BYTCHK)
9059 			bytchk = 1;
9060 		if (cdb->byte2 & SVFY_DPO)
9061 			flags |= CTL_LLF_DPO;
9062 		lba = scsi_4btoul(cdb->addr);
9063 		num_blocks = scsi_4btoul(cdb->length);
9064 		break;
9065 	}
9066 	case VERIFY_16: {
9067 		struct scsi_rw_16 *cdb;
9068 
9069 		cdb = (struct scsi_rw_16 *)ctsio->cdb;
9070 		if (cdb->byte2 & SVFY_BYTCHK)
9071 			bytchk = 1;
9072 		if (cdb->byte2 & SVFY_DPO)
9073 			flags |= CTL_LLF_DPO;
9074 		lba = scsi_8btou64(cdb->addr);
9075 		num_blocks = scsi_4btoul(cdb->length);
9076 		break;
9077 	}
9078 	default:
9079 		/*
9080 		 * We got a command we don't support.  This shouldn't
9081 		 * happen, commands should be filtered out above us.
9082 		 */
9083 		ctl_set_invalid_opcode(ctsio);
9084 		ctl_done((union ctl_io *)ctsio);
9085 		return (CTL_RETVAL_COMPLETE);
9086 	}
9087 
9088 	/*
9089 	 * The first check is to make sure we're in bounds, the second
9090 	 * check is to catch wrap-around problems.  If the lba + num blocks
9091 	 * is less than the lba, then we've wrapped around and the block
9092 	 * range is invalid anyway.
9093 	 */
9094 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9095 	 || ((lba + num_blocks) < lba)) {
9096 		ctl_set_lba_out_of_range(ctsio,
9097 		    MAX(lba, lun->be_lun->maxlba + 1));
9098 		ctl_done((union ctl_io *)ctsio);
9099 		return (CTL_RETVAL_COMPLETE);
9100 	}
9101 
9102 	/*
9103 	 * According to SBC-3, a transfer length of 0 is not an error.
9104 	 */
9105 	if (num_blocks == 0) {
9106 		ctl_set_success(ctsio);
9107 		ctl_done((union ctl_io *)ctsio);
9108 		return (CTL_RETVAL_COMPLETE);
9109 	}
9110 
9111 	lbalen = (struct ctl_lba_len_flags *)
9112 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9113 	lbalen->lba = lba;
9114 	lbalen->len = num_blocks;
9115 	if (bytchk) {
9116 		lbalen->flags = CTL_LLF_COMPARE | flags;
9117 		ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9118 	} else {
9119 		lbalen->flags = CTL_LLF_VERIFY | flags;
9120 		ctsio->kern_total_len = 0;
9121 	}
9122 	ctsio->kern_rel_offset = 0;
9123 
9124 	CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9125 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9126 	return (retval);
9127 }
9128 
9129 int
9130 ctl_report_luns(struct ctl_scsiio *ctsio)
9131 {
9132 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9133 	struct ctl_port *port = CTL_PORT(ctsio);
9134 	struct ctl_lun *lun, *request_lun = CTL_LUN(ctsio);
9135 	struct scsi_report_luns *cdb;
9136 	struct scsi_report_luns_data *lun_data;
9137 	int num_filled, num_luns, num_port_luns, retval;
9138 	uint32_t alloc_len, lun_datalen;
9139 	uint32_t initidx, targ_lun_id, lun_id;
9140 
9141 	retval = CTL_RETVAL_COMPLETE;
9142 	cdb = (struct scsi_report_luns *)ctsio->cdb;
9143 
9144 	CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9145 
9146 	num_luns = 0;
9147 	num_port_luns = port->lun_map ? port->lun_map_size : ctl_max_luns;
9148 	mtx_lock(&softc->ctl_lock);
9149 	for (targ_lun_id = 0; targ_lun_id < num_port_luns; targ_lun_id++) {
9150 		if (ctl_lun_map_from_port(port, targ_lun_id) != UINT32_MAX)
9151 			num_luns++;
9152 	}
9153 	mtx_unlock(&softc->ctl_lock);
9154 
9155 	switch (cdb->select_report) {
9156 	case RPL_REPORT_DEFAULT:
9157 	case RPL_REPORT_ALL:
9158 	case RPL_REPORT_NONSUBSID:
9159 		break;
9160 	case RPL_REPORT_WELLKNOWN:
9161 	case RPL_REPORT_ADMIN:
9162 	case RPL_REPORT_CONGLOM:
9163 		num_luns = 0;
9164 		break;
9165 	default:
9166 		ctl_set_invalid_field(ctsio,
9167 				      /*sks_valid*/ 1,
9168 				      /*command*/ 1,
9169 				      /*field*/ 2,
9170 				      /*bit_valid*/ 0,
9171 				      /*bit*/ 0);
9172 		ctl_done((union ctl_io *)ctsio);
9173 		return (retval);
9174 		break; /* NOTREACHED */
9175 	}
9176 
9177 	alloc_len = scsi_4btoul(cdb->length);
9178 	/*
9179 	 * The initiator has to allocate at least 16 bytes for this request,
9180 	 * so he can at least get the header and the first LUN.  Otherwise
9181 	 * we reject the request (per SPC-3 rev 14, section 6.21).
9182 	 */
9183 	if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9184 	    sizeof(struct scsi_report_luns_lundata))) {
9185 		ctl_set_invalid_field(ctsio,
9186 				      /*sks_valid*/ 1,
9187 				      /*command*/ 1,
9188 				      /*field*/ 6,
9189 				      /*bit_valid*/ 0,
9190 				      /*bit*/ 0);
9191 		ctl_done((union ctl_io *)ctsio);
9192 		return (retval);
9193 	}
9194 
9195 	lun_datalen = sizeof(*lun_data) +
9196 		(num_luns * sizeof(struct scsi_report_luns_lundata));
9197 
9198 	ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9199 	lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9200 	ctsio->kern_sg_entries = 0;
9201 
9202 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9203 
9204 	mtx_lock(&softc->ctl_lock);
9205 	for (targ_lun_id = 0, num_filled = 0;
9206 	    targ_lun_id < num_port_luns && num_filled < num_luns;
9207 	    targ_lun_id++) {
9208 		lun_id = ctl_lun_map_from_port(port, targ_lun_id);
9209 		if (lun_id == UINT32_MAX)
9210 			continue;
9211 		lun = softc->ctl_luns[lun_id];
9212 		if (lun == NULL)
9213 			continue;
9214 
9215 		be64enc(lun_data->luns[num_filled++].lundata,
9216 		    ctl_encode_lun(targ_lun_id));
9217 
9218 		/*
9219 		 * According to SPC-3, rev 14 section 6.21:
9220 		 *
9221 		 * "The execution of a REPORT LUNS command to any valid and
9222 		 * installed logical unit shall clear the REPORTED LUNS DATA
9223 		 * HAS CHANGED unit attention condition for all logical
9224 		 * units of that target with respect to the requesting
9225 		 * initiator. A valid and installed logical unit is one
9226 		 * having a PERIPHERAL QUALIFIER of 000b in the standard
9227 		 * INQUIRY data (see 6.4.2)."
9228 		 *
9229 		 * If request_lun is NULL, the LUN this report luns command
9230 		 * was issued to is either disabled or doesn't exist. In that
9231 		 * case, we shouldn't clear any pending lun change unit
9232 		 * attention.
9233 		 */
9234 		if (request_lun != NULL) {
9235 			mtx_lock(&lun->lun_lock);
9236 			ctl_clr_ua(lun, initidx, CTL_UA_LUN_CHANGE);
9237 			mtx_unlock(&lun->lun_lock);
9238 		}
9239 	}
9240 	mtx_unlock(&softc->ctl_lock);
9241 
9242 	/*
9243 	 * It's quite possible that we've returned fewer LUNs than we allocated
9244 	 * space for.  Trim it.
9245 	 */
9246 	lun_datalen = sizeof(*lun_data) +
9247 		(num_filled * sizeof(struct scsi_report_luns_lundata));
9248 	ctsio->kern_rel_offset = 0;
9249 	ctsio->kern_sg_entries = 0;
9250 	ctsio->kern_data_len = min(lun_datalen, alloc_len);
9251 	ctsio->kern_total_len = ctsio->kern_data_len;
9252 
9253 	/*
9254 	 * We set this to the actual data length, regardless of how much
9255 	 * space we actually have to return results.  If the user looks at
9256 	 * this value, he'll know whether or not he allocated enough space
9257 	 * and reissue the command if necessary.  We don't support well
9258 	 * known logical units, so if the user asks for that, return none.
9259 	 */
9260 	scsi_ulto4b(lun_datalen - 8, lun_data->length);
9261 
9262 	/*
9263 	 * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9264 	 * this request.
9265 	 */
9266 	ctl_set_success(ctsio);
9267 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9268 	ctsio->be_move_done = ctl_config_move_done;
9269 	ctl_datamove((union ctl_io *)ctsio);
9270 	return (retval);
9271 }
9272 
9273 int
9274 ctl_request_sense(struct ctl_scsiio *ctsio)
9275 {
9276 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9277 	struct ctl_lun *lun = CTL_LUN(ctsio);
9278 	struct scsi_request_sense *cdb;
9279 	struct scsi_sense_data *sense_ptr, *ps;
9280 	uint32_t initidx;
9281 	int have_error;
9282 	u_int sense_len = SSD_FULL_SIZE;
9283 	scsi_sense_data_type sense_format;
9284 	ctl_ua_type ua_type;
9285 	uint8_t asc = 0, ascq = 0;
9286 
9287 	cdb = (struct scsi_request_sense *)ctsio->cdb;
9288 
9289 	CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9290 
9291 	/*
9292 	 * Determine which sense format the user wants.
9293 	 */
9294 	if (cdb->byte2 & SRS_DESC)
9295 		sense_format = SSD_TYPE_DESC;
9296 	else
9297 		sense_format = SSD_TYPE_FIXED;
9298 
9299 	ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9300 	sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9301 	ctsio->kern_sg_entries = 0;
9302 	ctsio->kern_rel_offset = 0;
9303 	ctsio->kern_data_len = ctsio->kern_total_len =
9304 	    MIN(cdb->length, sizeof(*sense_ptr));
9305 
9306 	/*
9307 	 * If we don't have a LUN, we don't have any pending sense.
9308 	 */
9309 	if (lun == NULL ||
9310 	    ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
9311 	     softc->ha_link < CTL_HA_LINK_UNKNOWN)) {
9312 		/* "Logical unit not supported" */
9313 		ctl_set_sense_data(sense_ptr, &sense_len, NULL, sense_format,
9314 		    /*current_error*/ 1,
9315 		    /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
9316 		    /*asc*/ 0x25,
9317 		    /*ascq*/ 0x00,
9318 		    SSD_ELEM_NONE);
9319 		goto send;
9320 	}
9321 
9322 	have_error = 0;
9323 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9324 	/*
9325 	 * Check for pending sense, and then for pending unit attentions.
9326 	 * Pending sense gets returned first, then pending unit attentions.
9327 	 */
9328 	mtx_lock(&lun->lun_lock);
9329 	ps = lun->pending_sense[initidx / CTL_MAX_INIT_PER_PORT];
9330 	if (ps != NULL)
9331 		ps += initidx % CTL_MAX_INIT_PER_PORT;
9332 	if (ps != NULL && ps->error_code != 0) {
9333 		scsi_sense_data_type stored_format;
9334 
9335 		/*
9336 		 * Check to see which sense format was used for the stored
9337 		 * sense data.
9338 		 */
9339 		stored_format = scsi_sense_type(ps);
9340 
9341 		/*
9342 		 * If the user requested a different sense format than the
9343 		 * one we stored, then we need to convert it to the other
9344 		 * format.  If we're going from descriptor to fixed format
9345 		 * sense data, we may lose things in translation, depending
9346 		 * on what options were used.
9347 		 *
9348 		 * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9349 		 * for some reason we'll just copy it out as-is.
9350 		 */
9351 		if ((stored_format == SSD_TYPE_FIXED)
9352 		 && (sense_format == SSD_TYPE_DESC))
9353 			ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9354 			    ps, (struct scsi_sense_data_desc *)sense_ptr);
9355 		else if ((stored_format == SSD_TYPE_DESC)
9356 		      && (sense_format == SSD_TYPE_FIXED))
9357 			ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9358 			    ps, (struct scsi_sense_data_fixed *)sense_ptr);
9359 		else
9360 			memcpy(sense_ptr, ps, sizeof(*sense_ptr));
9361 
9362 		ps->error_code = 0;
9363 		have_error = 1;
9364 	} else {
9365 		ua_type = ctl_build_ua(lun, initidx, sense_ptr, &sense_len,
9366 		    sense_format);
9367 		if (ua_type != CTL_UA_NONE)
9368 			have_error = 1;
9369 	}
9370 	if (have_error == 0) {
9371 		/*
9372 		 * Report informational exception if have one and allowed.
9373 		 */
9374 		if (lun->MODE_IE.mrie != SIEP_MRIE_NO) {
9375 			asc = lun->ie_asc;
9376 			ascq = lun->ie_ascq;
9377 		}
9378 		ctl_set_sense_data(sense_ptr, &sense_len, lun, sense_format,
9379 		    /*current_error*/ 1,
9380 		    /*sense_key*/ SSD_KEY_NO_SENSE,
9381 		    /*asc*/ asc,
9382 		    /*ascq*/ ascq,
9383 		    SSD_ELEM_NONE);
9384 	}
9385 	mtx_unlock(&lun->lun_lock);
9386 
9387 send:
9388 	/*
9389 	 * We report the SCSI status as OK, since the status of the command
9390 	 * itself is OK.  We're reporting sense as parameter data.
9391 	 */
9392 	ctl_set_success(ctsio);
9393 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9394 	ctsio->be_move_done = ctl_config_move_done;
9395 	ctl_datamove((union ctl_io *)ctsio);
9396 	return (CTL_RETVAL_COMPLETE);
9397 }
9398 
9399 int
9400 ctl_tur(struct ctl_scsiio *ctsio)
9401 {
9402 
9403 	CTL_DEBUG_PRINT(("ctl_tur\n"));
9404 
9405 	ctl_set_success(ctsio);
9406 	ctl_done((union ctl_io *)ctsio);
9407 
9408 	return (CTL_RETVAL_COMPLETE);
9409 }
9410 
9411 /*
9412  * SCSI VPD page 0x00, the Supported VPD Pages page.
9413  */
9414 static int
9415 ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9416 {
9417 	struct ctl_lun *lun = CTL_LUN(ctsio);
9418 	struct scsi_vpd_supported_pages *pages;
9419 	int sup_page_size;
9420 	int p;
9421 
9422 	sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9423 	    SCSI_EVPD_NUM_SUPPORTED_PAGES;
9424 	ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9425 	pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9426 	ctsio->kern_rel_offset = 0;
9427 	ctsio->kern_sg_entries = 0;
9428 	ctsio->kern_data_len = min(sup_page_size, alloc_len);
9429 	ctsio->kern_total_len = ctsio->kern_data_len;
9430 
9431 	/*
9432 	 * The control device is always connected.  The disk device, on the
9433 	 * other hand, may not be online all the time.  Need to change this
9434 	 * to figure out whether the disk device is actually online or not.
9435 	 */
9436 	if (lun != NULL)
9437 		pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9438 				lun->be_lun->lun_type;
9439 	else
9440 		pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9441 
9442 	p = 0;
9443 	/* Supported VPD pages */
9444 	pages->page_list[p++] = SVPD_SUPPORTED_PAGES;
9445 	/* Serial Number */
9446 	pages->page_list[p++] = SVPD_UNIT_SERIAL_NUMBER;
9447 	/* Device Identification */
9448 	pages->page_list[p++] = SVPD_DEVICE_ID;
9449 	/* Extended INQUIRY Data */
9450 	pages->page_list[p++] = SVPD_EXTENDED_INQUIRY_DATA;
9451 	/* Mode Page Policy */
9452 	pages->page_list[p++] = SVPD_MODE_PAGE_POLICY;
9453 	/* SCSI Ports */
9454 	pages->page_list[p++] = SVPD_SCSI_PORTS;
9455 	/* Third-party Copy */
9456 	pages->page_list[p++] = SVPD_SCSI_TPC;
9457 	/* SCSI Feature Sets */
9458 	pages->page_list[p++] = SVPD_SCSI_SFS;
9459 	if (lun != NULL && lun->be_lun->lun_type == T_DIRECT) {
9460 		/* Block limits */
9461 		pages->page_list[p++] = SVPD_BLOCK_LIMITS;
9462 		/* Block Device Characteristics */
9463 		pages->page_list[p++] = SVPD_BDC;
9464 		/* Logical Block Provisioning */
9465 		pages->page_list[p++] = SVPD_LBP;
9466 	}
9467 	pages->length = p;
9468 
9469 	ctl_set_success(ctsio);
9470 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9471 	ctsio->be_move_done = ctl_config_move_done;
9472 	ctl_datamove((union ctl_io *)ctsio);
9473 	return (CTL_RETVAL_COMPLETE);
9474 }
9475 
9476 /*
9477  * SCSI VPD page 0x80, the Unit Serial Number page.
9478  */
9479 static int
9480 ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9481 {
9482 	struct ctl_lun *lun = CTL_LUN(ctsio);
9483 	struct scsi_vpd_unit_serial_number *sn_ptr;
9484 	int data_len;
9485 
9486 	data_len = 4 + CTL_SN_LEN;
9487 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9488 	sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9489 	ctsio->kern_rel_offset = 0;
9490 	ctsio->kern_sg_entries = 0;
9491 	ctsio->kern_data_len = min(data_len, alloc_len);
9492 	ctsio->kern_total_len = ctsio->kern_data_len;
9493 
9494 	/*
9495 	 * The control device is always connected.  The disk device, on the
9496 	 * other hand, may not be online all the time.  Need to change this
9497 	 * to figure out whether the disk device is actually online or not.
9498 	 */
9499 	if (lun != NULL)
9500 		sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9501 				  lun->be_lun->lun_type;
9502 	else
9503 		sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9504 
9505 	sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9506 	sn_ptr->length = CTL_SN_LEN;
9507 	/*
9508 	 * If we don't have a LUN, we just leave the serial number as
9509 	 * all spaces.
9510 	 */
9511 	if (lun != NULL) {
9512 		strncpy((char *)sn_ptr->serial_num,
9513 			(char *)lun->be_lun->serial_num, CTL_SN_LEN);
9514 	} else
9515 		memset(sn_ptr->serial_num, 0x20, CTL_SN_LEN);
9516 
9517 	ctl_set_success(ctsio);
9518 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9519 	ctsio->be_move_done = ctl_config_move_done;
9520 	ctl_datamove((union ctl_io *)ctsio);
9521 	return (CTL_RETVAL_COMPLETE);
9522 }
9523 
9524 /*
9525  * SCSI VPD page 0x86, the Extended INQUIRY Data page.
9526  */
9527 static int
9528 ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9529 {
9530 	struct ctl_lun *lun = CTL_LUN(ctsio);
9531 	struct scsi_vpd_extended_inquiry_data *eid_ptr;
9532 	int data_len;
9533 
9534 	data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
9535 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9536 	eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9537 	ctsio->kern_sg_entries = 0;
9538 	ctsio->kern_rel_offset = 0;
9539 	ctsio->kern_data_len = min(data_len, alloc_len);
9540 	ctsio->kern_total_len = ctsio->kern_data_len;
9541 
9542 	/*
9543 	 * The control device is always connected.  The disk device, on the
9544 	 * other hand, may not be online all the time.
9545 	 */
9546 	if (lun != NULL)
9547 		eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9548 				     lun->be_lun->lun_type;
9549 	else
9550 		eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9551 	eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9552 	scsi_ulto2b(data_len - 4, eid_ptr->page_length);
9553 	/*
9554 	 * We support head of queue, ordered and simple tags.
9555 	 */
9556 	eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9557 	/*
9558 	 * Volatile cache supported.
9559 	 */
9560 	eid_ptr->flags3 = SVPD_EID_V_SUP;
9561 
9562 	/*
9563 	 * This means that we clear the REPORTED LUNS DATA HAS CHANGED unit
9564 	 * attention for a particular IT nexus on all LUNs once we report
9565 	 * it to that nexus once.  This bit is required as of SPC-4.
9566 	 */
9567 	eid_ptr->flags4 = SVPD_EID_LUICLR;
9568 
9569 	/*
9570 	 * We support revert to defaults (RTD) bit in MODE SELECT.
9571 	 */
9572 	eid_ptr->flags5 = SVPD_EID_RTD_SUP;
9573 
9574 	/*
9575 	 * XXX KDM in order to correctly answer this, we would need
9576 	 * information from the SIM to determine how much sense data it
9577 	 * can send.  So this would really be a path inquiry field, most
9578 	 * likely.  This can be set to a maximum of 252 according to SPC-4,
9579 	 * but the hardware may or may not be able to support that much.
9580 	 * 0 just means that the maximum sense data length is not reported.
9581 	 */
9582 	eid_ptr->max_sense_length = 0;
9583 
9584 	ctl_set_success(ctsio);
9585 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9586 	ctsio->be_move_done = ctl_config_move_done;
9587 	ctl_datamove((union ctl_io *)ctsio);
9588 	return (CTL_RETVAL_COMPLETE);
9589 }
9590 
9591 static int
9592 ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
9593 {
9594 	struct ctl_lun *lun = CTL_LUN(ctsio);
9595 	struct scsi_vpd_mode_page_policy *mpp_ptr;
9596 	int data_len;
9597 
9598 	data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9599 	    sizeof(struct scsi_vpd_mode_page_policy_descr);
9600 
9601 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9602 	mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
9603 	ctsio->kern_rel_offset = 0;
9604 	ctsio->kern_sg_entries = 0;
9605 	ctsio->kern_data_len = min(data_len, alloc_len);
9606 	ctsio->kern_total_len = ctsio->kern_data_len;
9607 
9608 	/*
9609 	 * The control device is always connected.  The disk device, on the
9610 	 * other hand, may not be online all the time.
9611 	 */
9612 	if (lun != NULL)
9613 		mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9614 				     lun->be_lun->lun_type;
9615 	else
9616 		mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9617 	mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
9618 	scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
9619 	mpp_ptr->descr[0].page_code = 0x3f;
9620 	mpp_ptr->descr[0].subpage_code = 0xff;
9621 	mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
9622 
9623 	ctl_set_success(ctsio);
9624 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9625 	ctsio->be_move_done = ctl_config_move_done;
9626 	ctl_datamove((union ctl_io *)ctsio);
9627 	return (CTL_RETVAL_COMPLETE);
9628 }
9629 
9630 /*
9631  * SCSI VPD page 0x83, the Device Identification page.
9632  */
9633 static int
9634 ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9635 {
9636 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9637 	struct ctl_port *port = CTL_PORT(ctsio);
9638 	struct ctl_lun *lun = CTL_LUN(ctsio);
9639 	struct scsi_vpd_device_id *devid_ptr;
9640 	struct scsi_vpd_id_descriptor *desc;
9641 	int data_len, g;
9642 	uint8_t proto;
9643 
9644 	data_len = sizeof(struct scsi_vpd_device_id) +
9645 	    sizeof(struct scsi_vpd_id_descriptor) +
9646 		sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9647 	    sizeof(struct scsi_vpd_id_descriptor) +
9648 		sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9649 	if (lun && lun->lun_devid)
9650 		data_len += lun->lun_devid->len;
9651 	if (port && port->port_devid)
9652 		data_len += port->port_devid->len;
9653 	if (port && port->target_devid)
9654 		data_len += port->target_devid->len;
9655 
9656 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9657 	devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9658 	ctsio->kern_sg_entries = 0;
9659 	ctsio->kern_rel_offset = 0;
9660 	ctsio->kern_sg_entries = 0;
9661 	ctsio->kern_data_len = min(data_len, alloc_len);
9662 	ctsio->kern_total_len = ctsio->kern_data_len;
9663 
9664 	/*
9665 	 * The control device is always connected.  The disk device, on the
9666 	 * other hand, may not be online all the time.
9667 	 */
9668 	if (lun != NULL)
9669 		devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9670 				     lun->be_lun->lun_type;
9671 	else
9672 		devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9673 	devid_ptr->page_code = SVPD_DEVICE_ID;
9674 	scsi_ulto2b(data_len - 4, devid_ptr->length);
9675 
9676 	if (port && port->port_type == CTL_PORT_FC)
9677 		proto = SCSI_PROTO_FC << 4;
9678 	else if (port && port->port_type == CTL_PORT_SAS)
9679 		proto = SCSI_PROTO_SAS << 4;
9680 	else if (port && port->port_type == CTL_PORT_ISCSI)
9681 		proto = SCSI_PROTO_ISCSI << 4;
9682 	else
9683 		proto = SCSI_PROTO_SPI << 4;
9684 	desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
9685 
9686 	/*
9687 	 * We're using a LUN association here.  i.e., this device ID is a
9688 	 * per-LUN identifier.
9689 	 */
9690 	if (lun && lun->lun_devid) {
9691 		memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
9692 		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9693 		    lun->lun_devid->len);
9694 	}
9695 
9696 	/*
9697 	 * This is for the WWPN which is a port association.
9698 	 */
9699 	if (port && port->port_devid) {
9700 		memcpy(desc, port->port_devid->data, port->port_devid->len);
9701 		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9702 		    port->port_devid->len);
9703 	}
9704 
9705 	/*
9706 	 * This is for the Relative Target Port(type 4h) identifier
9707 	 */
9708 	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9709 	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9710 	    SVPD_ID_TYPE_RELTARG;
9711 	desc->length = 4;
9712 	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
9713 	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9714 	    sizeof(struct scsi_vpd_id_rel_trgt_port_id));
9715 
9716 	/*
9717 	 * This is for the Target Port Group(type 5h) identifier
9718 	 */
9719 	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9720 	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9721 	    SVPD_ID_TYPE_TPORTGRP;
9722 	desc->length = 4;
9723 	if (softc->is_single ||
9724 	    (port && port->status & CTL_PORT_STATUS_HA_SHARED))
9725 		g = 1;
9726 	else
9727 		g = 2 + ctsio->io_hdr.nexus.targ_port / softc->port_cnt;
9728 	scsi_ulto2b(g, &desc->identifier[2]);
9729 	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9730 	    sizeof(struct scsi_vpd_id_trgt_port_grp_id));
9731 
9732 	/*
9733 	 * This is for the Target identifier
9734 	 */
9735 	if (port && port->target_devid) {
9736 		memcpy(desc, port->target_devid->data, port->target_devid->len);
9737 	}
9738 
9739 	ctl_set_success(ctsio);
9740 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9741 	ctsio->be_move_done = ctl_config_move_done;
9742 	ctl_datamove((union ctl_io *)ctsio);
9743 	return (CTL_RETVAL_COMPLETE);
9744 }
9745 
9746 static int
9747 ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
9748 {
9749 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9750 	struct ctl_lun *lun = CTL_LUN(ctsio);
9751 	struct scsi_vpd_scsi_ports *sp;
9752 	struct scsi_vpd_port_designation *pd;
9753 	struct scsi_vpd_port_designation_cont *pdc;
9754 	struct ctl_port *port;
9755 	int data_len, num_target_ports, iid_len, id_len;
9756 
9757 	num_target_ports = 0;
9758 	iid_len = 0;
9759 	id_len = 0;
9760 	mtx_lock(&softc->ctl_lock);
9761 	STAILQ_FOREACH(port, &softc->port_list, links) {
9762 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9763 			continue;
9764 		if (lun != NULL &&
9765 		    ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
9766 			continue;
9767 		num_target_ports++;
9768 		if (port->init_devid)
9769 			iid_len += port->init_devid->len;
9770 		if (port->port_devid)
9771 			id_len += port->port_devid->len;
9772 	}
9773 	mtx_unlock(&softc->ctl_lock);
9774 
9775 	data_len = sizeof(struct scsi_vpd_scsi_ports) +
9776 	    num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
9777 	     sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
9778 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9779 	sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
9780 	ctsio->kern_sg_entries = 0;
9781 	ctsio->kern_rel_offset = 0;
9782 	ctsio->kern_sg_entries = 0;
9783 	ctsio->kern_data_len = min(data_len, alloc_len);
9784 	ctsio->kern_total_len = ctsio->kern_data_len;
9785 
9786 	/*
9787 	 * The control device is always connected.  The disk device, on the
9788 	 * other hand, may not be online all the time.  Need to change this
9789 	 * to figure out whether the disk device is actually online or not.
9790 	 */
9791 	if (lun != NULL)
9792 		sp->device = (SID_QUAL_LU_CONNECTED << 5) |
9793 				  lun->be_lun->lun_type;
9794 	else
9795 		sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9796 
9797 	sp->page_code = SVPD_SCSI_PORTS;
9798 	scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
9799 	    sp->page_length);
9800 	pd = &sp->design[0];
9801 
9802 	mtx_lock(&softc->ctl_lock);
9803 	STAILQ_FOREACH(port, &softc->port_list, links) {
9804 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9805 			continue;
9806 		if (lun != NULL &&
9807 		    ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
9808 			continue;
9809 		scsi_ulto2b(port->targ_port, pd->relative_port_id);
9810 		if (port->init_devid) {
9811 			iid_len = port->init_devid->len;
9812 			memcpy(pd->initiator_transportid,
9813 			    port->init_devid->data, port->init_devid->len);
9814 		} else
9815 			iid_len = 0;
9816 		scsi_ulto2b(iid_len, pd->initiator_transportid_length);
9817 		pdc = (struct scsi_vpd_port_designation_cont *)
9818 		    (&pd->initiator_transportid[iid_len]);
9819 		if (port->port_devid) {
9820 			id_len = port->port_devid->len;
9821 			memcpy(pdc->target_port_descriptors,
9822 			    port->port_devid->data, port->port_devid->len);
9823 		} else
9824 			id_len = 0;
9825 		scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
9826 		pd = (struct scsi_vpd_port_designation *)
9827 		    ((uint8_t *)pdc->target_port_descriptors + id_len);
9828 	}
9829 	mtx_unlock(&softc->ctl_lock);
9830 
9831 	ctl_set_success(ctsio);
9832 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9833 	ctsio->be_move_done = ctl_config_move_done;
9834 	ctl_datamove((union ctl_io *)ctsio);
9835 	return (CTL_RETVAL_COMPLETE);
9836 }
9837 
9838 static int
9839 ctl_inquiry_evpd_sfs(struct ctl_scsiio *ctsio, int alloc_len)
9840 {
9841 	struct ctl_lun *lun = CTL_LUN(ctsio);
9842 	struct scsi_vpd_sfs *sfs_ptr;
9843 	int sfs_page_size, n;
9844 
9845 	sfs_page_size = sizeof(*sfs_ptr) + 5 * 2;
9846 	ctsio->kern_data_ptr = malloc(sfs_page_size, M_CTL, M_WAITOK | M_ZERO);
9847 	sfs_ptr = (struct scsi_vpd_sfs *)ctsio->kern_data_ptr;
9848 	ctsio->kern_sg_entries = 0;
9849 	ctsio->kern_rel_offset = 0;
9850 	ctsio->kern_sg_entries = 0;
9851 	ctsio->kern_data_len = min(sfs_page_size, alloc_len);
9852 	ctsio->kern_total_len = ctsio->kern_data_len;
9853 
9854 	/*
9855 	 * The control device is always connected.  The disk device, on the
9856 	 * other hand, may not be online all the time.  Need to change this
9857 	 * to figure out whether the disk device is actually online or not.
9858 	 */
9859 	if (lun != NULL)
9860 		sfs_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9861 				  lun->be_lun->lun_type;
9862 	else
9863 		sfs_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9864 
9865 	sfs_ptr->page_code = SVPD_SCSI_SFS;
9866 	n = 0;
9867 	/* Discovery 2016 */
9868 	scsi_ulto2b(0x0001, &sfs_ptr->codes[2 * n++]);
9869 	if (lun != NULL && lun->be_lun->lun_type == T_DIRECT) {
9870 		 /* SBC Base 2016 */
9871 		scsi_ulto2b(0x0101, &sfs_ptr->codes[2 * n++]);
9872 		 /* SBC Base 2010 */
9873 		scsi_ulto2b(0x0102, &sfs_ptr->codes[2 * n++]);
9874 		if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9875 			/* Basic Provisioning 2016 */
9876 			scsi_ulto2b(0x0103, &sfs_ptr->codes[2 * n++]);
9877 		}
9878 		/* Drive Maintenance 2016 */
9879 		//scsi_ulto2b(0x0104, &sfs_ptr->codes[2 * n++]);
9880 	}
9881 	scsi_ulto2b(4 + 2 * n, sfs_ptr->page_length);
9882 
9883 	ctl_set_success(ctsio);
9884 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9885 	ctsio->be_move_done = ctl_config_move_done;
9886 	ctl_datamove((union ctl_io *)ctsio);
9887 	return (CTL_RETVAL_COMPLETE);
9888 }
9889 
9890 static int
9891 ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
9892 {
9893 	struct ctl_lun *lun = CTL_LUN(ctsio);
9894 	struct scsi_vpd_block_limits *bl_ptr;
9895 	const char *val;
9896 	uint64_t ival;
9897 
9898 	ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
9899 	bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
9900 	ctsio->kern_sg_entries = 0;
9901 	ctsio->kern_rel_offset = 0;
9902 	ctsio->kern_sg_entries = 0;
9903 	ctsio->kern_data_len = min(sizeof(*bl_ptr), alloc_len);
9904 	ctsio->kern_total_len = ctsio->kern_data_len;
9905 
9906 	/*
9907 	 * The control device is always connected.  The disk device, on the
9908 	 * other hand, may not be online all the time.  Need to change this
9909 	 * to figure out whether the disk device is actually online or not.
9910 	 */
9911 	if (lun != NULL)
9912 		bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9913 				  lun->be_lun->lun_type;
9914 	else
9915 		bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9916 
9917 	bl_ptr->page_code = SVPD_BLOCK_LIMITS;
9918 	scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
9919 	bl_ptr->max_cmp_write_len = 0xff;
9920 	scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
9921 	if (lun != NULL) {
9922 		scsi_ulto4b(lun->be_lun->opttxferlen, bl_ptr->opt_txfer_len);
9923 		if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9924 			ival = 0xffffffff;
9925 			val = dnvlist_get_string(lun->be_lun->options,
9926 			    "unmap_max_lba", NULL);
9927 			if (val != NULL)
9928 				ctl_expand_number(val, &ival);
9929 			scsi_ulto4b(ival, bl_ptr->max_unmap_lba_cnt);
9930 			ival = 0xffffffff;
9931 			val = dnvlist_get_string(lun->be_lun->options,
9932 			    "unmap_max_descr", NULL);
9933 			if (val != NULL)
9934 				ctl_expand_number(val, &ival);
9935 			scsi_ulto4b(ival, bl_ptr->max_unmap_blk_cnt);
9936 			if (lun->be_lun->ublockexp != 0) {
9937 				scsi_ulto4b((1 << lun->be_lun->ublockexp),
9938 				    bl_ptr->opt_unmap_grain);
9939 				scsi_ulto4b(0x80000000 | lun->be_lun->ublockoff,
9940 				    bl_ptr->unmap_grain_align);
9941 			}
9942 		}
9943 		scsi_ulto4b(lun->be_lun->atomicblock,
9944 		    bl_ptr->max_atomic_transfer_length);
9945 		scsi_ulto4b(0, bl_ptr->atomic_alignment);
9946 		scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
9947 		scsi_ulto4b(0, bl_ptr->max_atomic_transfer_length_with_atomic_boundary);
9948 		scsi_ulto4b(0, bl_ptr->max_atomic_boundary_size);
9949 		ival = UINT64_MAX;
9950 		val = dnvlist_get_string(lun->be_lun->options,
9951 		    "write_same_max_lba", NULL);
9952 		if (val != NULL)
9953 			ctl_expand_number(val, &ival);
9954 		scsi_u64to8b(ival, bl_ptr->max_write_same_length);
9955 		if (lun->be_lun->maxlba + 1 > ival)
9956 			bl_ptr->flags |= SVPD_BL_WSNZ;
9957 	}
9958 
9959 	ctl_set_success(ctsio);
9960 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9961 	ctsio->be_move_done = ctl_config_move_done;
9962 	ctl_datamove((union ctl_io *)ctsio);
9963 	return (CTL_RETVAL_COMPLETE);
9964 }
9965 
9966 static int
9967 ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
9968 {
9969 	struct ctl_lun *lun = CTL_LUN(ctsio);
9970 	struct scsi_vpd_block_device_characteristics *bdc_ptr;
9971 	const char *value;
9972 	u_int i;
9973 
9974 	ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
9975 	bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
9976 	ctsio->kern_sg_entries = 0;
9977 	ctsio->kern_rel_offset = 0;
9978 	ctsio->kern_data_len = min(sizeof(*bdc_ptr), alloc_len);
9979 	ctsio->kern_total_len = ctsio->kern_data_len;
9980 
9981 	/*
9982 	 * The control device is always connected.  The disk device, on the
9983 	 * other hand, may not be online all the time.  Need to change this
9984 	 * to figure out whether the disk device is actually online or not.
9985 	 */
9986 	if (lun != NULL)
9987 		bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9988 				  lun->be_lun->lun_type;
9989 	else
9990 		bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9991 	bdc_ptr->page_code = SVPD_BDC;
9992 	scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
9993 	if (lun != NULL &&
9994 	    (value = dnvlist_get_string(lun->be_lun->options, "rpm", NULL)) != NULL)
9995 		i = strtol(value, NULL, 0);
9996 	else
9997 		i = CTL_DEFAULT_ROTATION_RATE;
9998 	scsi_ulto2b(i, bdc_ptr->medium_rotation_rate);
9999 	if (lun != NULL &&
10000 	    (value = dnvlist_get_string(lun->be_lun->options, "formfactor", NULL)) != NULL)
10001 		i = strtol(value, NULL, 0);
10002 	else
10003 		i = 0;
10004 	bdc_ptr->wab_wac_ff = (i & 0x0f);
10005 	bdc_ptr->flags = SVPD_RBWZ | SVPD_FUAB | SVPD_VBULS;
10006 
10007 	ctl_set_success(ctsio);
10008 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10009 	ctsio->be_move_done = ctl_config_move_done;
10010 	ctl_datamove((union ctl_io *)ctsio);
10011 	return (CTL_RETVAL_COMPLETE);
10012 }
10013 
10014 static int
10015 ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
10016 {
10017 	struct ctl_lun *lun = CTL_LUN(ctsio);
10018 	struct scsi_vpd_logical_block_prov *lbp_ptr;
10019 	const char *value;
10020 
10021 	ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
10022 	lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
10023 	ctsio->kern_sg_entries = 0;
10024 	ctsio->kern_rel_offset = 0;
10025 	ctsio->kern_data_len = min(sizeof(*lbp_ptr), alloc_len);
10026 	ctsio->kern_total_len = ctsio->kern_data_len;
10027 
10028 	/*
10029 	 * The control device is always connected.  The disk device, on the
10030 	 * other hand, may not be online all the time.  Need to change this
10031 	 * to figure out whether the disk device is actually online or not.
10032 	 */
10033 	if (lun != NULL)
10034 		lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10035 				  lun->be_lun->lun_type;
10036 	else
10037 		lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10038 
10039 	lbp_ptr->page_code = SVPD_LBP;
10040 	scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
10041 	lbp_ptr->threshold_exponent = CTL_LBP_EXPONENT;
10042 	if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10043 		lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
10044 		    SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
10045 		value = dnvlist_get_string(lun->be_lun->options,
10046 		    "provisioning_type", NULL);
10047 		if (value != NULL) {
10048 			if (strcmp(value, "resource") == 0)
10049 				lbp_ptr->prov_type = SVPD_LBP_RESOURCE;
10050 			else if (strcmp(value, "thin") == 0)
10051 				lbp_ptr->prov_type = SVPD_LBP_THIN;
10052 		} else
10053 			lbp_ptr->prov_type = SVPD_LBP_THIN;
10054 	}
10055 
10056 	ctl_set_success(ctsio);
10057 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10058 	ctsio->be_move_done = ctl_config_move_done;
10059 	ctl_datamove((union ctl_io *)ctsio);
10060 	return (CTL_RETVAL_COMPLETE);
10061 }
10062 
10063 /*
10064  * INQUIRY with the EVPD bit set.
10065  */
10066 static int
10067 ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
10068 {
10069 	struct ctl_lun *lun = CTL_LUN(ctsio);
10070 	struct scsi_inquiry *cdb;
10071 	int alloc_len, retval;
10072 
10073 	cdb = (struct scsi_inquiry *)ctsio->cdb;
10074 	alloc_len = scsi_2btoul(cdb->length);
10075 
10076 	switch (cdb->page_code) {
10077 	case SVPD_SUPPORTED_PAGES:
10078 		retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
10079 		break;
10080 	case SVPD_UNIT_SERIAL_NUMBER:
10081 		retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
10082 		break;
10083 	case SVPD_DEVICE_ID:
10084 		retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
10085 		break;
10086 	case SVPD_EXTENDED_INQUIRY_DATA:
10087 		retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
10088 		break;
10089 	case SVPD_MODE_PAGE_POLICY:
10090 		retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
10091 		break;
10092 	case SVPD_SCSI_PORTS:
10093 		retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10094 		break;
10095 	case SVPD_SCSI_TPC:
10096 		retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
10097 		break;
10098 	case SVPD_SCSI_SFS:
10099 		retval = ctl_inquiry_evpd_sfs(ctsio, alloc_len);
10100 		break;
10101 	case SVPD_BLOCK_LIMITS:
10102 		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10103 			goto err;
10104 		retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10105 		break;
10106 	case SVPD_BDC:
10107 		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10108 			goto err;
10109 		retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
10110 		break;
10111 	case SVPD_LBP:
10112 		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10113 			goto err;
10114 		retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10115 		break;
10116 	default:
10117 err:
10118 		ctl_set_invalid_field(ctsio,
10119 				      /*sks_valid*/ 1,
10120 				      /*command*/ 1,
10121 				      /*field*/ 2,
10122 				      /*bit_valid*/ 0,
10123 				      /*bit*/ 0);
10124 		ctl_done((union ctl_io *)ctsio);
10125 		retval = CTL_RETVAL_COMPLETE;
10126 		break;
10127 	}
10128 
10129 	return (retval);
10130 }
10131 
10132 /*
10133  * Standard INQUIRY data.
10134  */
10135 static int
10136 ctl_inquiry_std(struct ctl_scsiio *ctsio)
10137 {
10138 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
10139 	struct ctl_port *port = CTL_PORT(ctsio);
10140 	struct ctl_lun *lun = CTL_LUN(ctsio);
10141 	struct scsi_inquiry_data *inq_ptr;
10142 	struct scsi_inquiry *cdb;
10143 	const char *val;
10144 	uint32_t alloc_len, data_len;
10145 	ctl_port_type port_type;
10146 
10147 	port_type = port->port_type;
10148 	if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10149 		port_type = CTL_PORT_SCSI;
10150 
10151 	cdb = (struct scsi_inquiry *)ctsio->cdb;
10152 	alloc_len = scsi_2btoul(cdb->length);
10153 
10154 	/*
10155 	 * We malloc the full inquiry data size here and fill it
10156 	 * in.  If the user only asks for less, we'll give him
10157 	 * that much.
10158 	 */
10159 	data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
10160 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10161 	inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10162 	ctsio->kern_sg_entries = 0;
10163 	ctsio->kern_rel_offset = 0;
10164 	ctsio->kern_data_len = min(data_len, alloc_len);
10165 	ctsio->kern_total_len = ctsio->kern_data_len;
10166 
10167 	if (lun != NULL) {
10168 		if ((lun->flags & CTL_LUN_PRIMARY_SC) ||
10169 		    softc->ha_link >= CTL_HA_LINK_UNKNOWN) {
10170 			inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10171 			    lun->be_lun->lun_type;
10172 		} else {
10173 			inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) |
10174 			    lun->be_lun->lun_type;
10175 		}
10176 		if (lun->flags & CTL_LUN_REMOVABLE)
10177 			inq_ptr->dev_qual2 |= SID_RMB;
10178 	} else
10179 		inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10180 
10181 	/* RMB in byte 2 is 0 */
10182 	inq_ptr->version = SCSI_REV_SPC5;
10183 
10184 	/*
10185 	 * According to SAM-3, even if a device only supports a single
10186 	 * level of LUN addressing, it should still set the HISUP bit:
10187 	 *
10188 	 * 4.9.1 Logical unit numbers overview
10189 	 *
10190 	 * All logical unit number formats described in this standard are
10191 	 * hierarchical in structure even when only a single level in that
10192 	 * hierarchy is used. The HISUP bit shall be set to one in the
10193 	 * standard INQUIRY data (see SPC-2) when any logical unit number
10194 	 * format described in this standard is used.  Non-hierarchical
10195 	 * formats are outside the scope of this standard.
10196 	 *
10197 	 * Therefore we set the HiSup bit here.
10198 	 *
10199 	 * The response format is 2, per SPC-3.
10200 	 */
10201 	inq_ptr->response_format = SID_HiSup | 2;
10202 
10203 	inq_ptr->additional_length = data_len -
10204 	    (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10205 	CTL_DEBUG_PRINT(("additional_length = %d\n",
10206 			 inq_ptr->additional_length));
10207 
10208 	inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10209 	if (port_type == CTL_PORT_SCSI)
10210 		inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10211 	inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10212 	inq_ptr->flags = SID_CmdQue;
10213 	if (port_type == CTL_PORT_SCSI)
10214 		inq_ptr->flags |= SID_WBus16 | SID_Sync;
10215 
10216 	/*
10217 	 * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10218 	 * We have 8 bytes for the vendor name, and 16 bytes for the device
10219 	 * name and 4 bytes for the revision.
10220 	 */
10221 	if (lun == NULL || (val = dnvlist_get_string(lun->be_lun->options,
10222 	    "vendor", NULL)) == NULL) {
10223 		strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10224 	} else {
10225 		memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10226 		strncpy(inq_ptr->vendor, val,
10227 		    min(sizeof(inq_ptr->vendor), strlen(val)));
10228 	}
10229 	if (lun == NULL) {
10230 		strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10231 		    sizeof(inq_ptr->product));
10232 	} else if ((val = dnvlist_get_string(lun->be_lun->options, "product",
10233 	    NULL)) == NULL) {
10234 		switch (lun->be_lun->lun_type) {
10235 		case T_DIRECT:
10236 			strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10237 			    sizeof(inq_ptr->product));
10238 			break;
10239 		case T_PROCESSOR:
10240 			strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10241 			    sizeof(inq_ptr->product));
10242 			break;
10243 		case T_CDROM:
10244 			strncpy(inq_ptr->product, CTL_CDROM_PRODUCT,
10245 			    sizeof(inq_ptr->product));
10246 			break;
10247 		default:
10248 			strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10249 			    sizeof(inq_ptr->product));
10250 			break;
10251 		}
10252 	} else {
10253 		memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10254 		strncpy(inq_ptr->product, val,
10255 		    min(sizeof(inq_ptr->product), strlen(val)));
10256 	}
10257 
10258 	/*
10259 	 * XXX make this a macro somewhere so it automatically gets
10260 	 * incremented when we make changes.
10261 	 */
10262 	if (lun == NULL || (val = dnvlist_get_string(lun->be_lun->options,
10263 	    "revision", NULL)) == NULL) {
10264 		strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10265 	} else {
10266 		memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10267 		strncpy(inq_ptr->revision, val,
10268 		    min(sizeof(inq_ptr->revision), strlen(val)));
10269 	}
10270 
10271 	/*
10272 	 * For parallel SCSI, we support double transition and single
10273 	 * transition clocking.  We also support QAS (Quick Arbitration
10274 	 * and Selection) and Information Unit transfers on both the
10275 	 * control and array devices.
10276 	 */
10277 	if (port_type == CTL_PORT_SCSI)
10278 		inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10279 				    SID_SPI_IUS;
10280 
10281 	/* SAM-6 (no version claimed) */
10282 	scsi_ulto2b(0x00C0, inq_ptr->version1);
10283 	/* SPC-5 (no version claimed) */
10284 	scsi_ulto2b(0x05C0, inq_ptr->version2);
10285 	if (port_type == CTL_PORT_FC) {
10286 		/* FCP-2 ANSI INCITS.350:2003 */
10287 		scsi_ulto2b(0x0917, inq_ptr->version3);
10288 	} else if (port_type == CTL_PORT_SCSI) {
10289 		/* SPI-4 ANSI INCITS.362:200x */
10290 		scsi_ulto2b(0x0B56, inq_ptr->version3);
10291 	} else if (port_type == CTL_PORT_ISCSI) {
10292 		/* iSCSI (no version claimed) */
10293 		scsi_ulto2b(0x0960, inq_ptr->version3);
10294 	} else if (port_type == CTL_PORT_SAS) {
10295 		/* SAS (no version claimed) */
10296 		scsi_ulto2b(0x0BE0, inq_ptr->version3);
10297 	} else if (port_type == CTL_PORT_UMASS) {
10298 		/* USB Mass Storage Class Bulk-Only Transport, Revision 1.0 */
10299 		scsi_ulto2b(0x1730, inq_ptr->version3);
10300 	}
10301 
10302 	if (lun == NULL) {
10303 		/* SBC-4 (no version claimed) */
10304 		scsi_ulto2b(0x0600, inq_ptr->version4);
10305 	} else {
10306 		switch (lun->be_lun->lun_type) {
10307 		case T_DIRECT:
10308 			/* SBC-4 (no version claimed) */
10309 			scsi_ulto2b(0x0600, inq_ptr->version4);
10310 			break;
10311 		case T_PROCESSOR:
10312 			break;
10313 		case T_CDROM:
10314 			/* MMC-6 (no version claimed) */
10315 			scsi_ulto2b(0x04E0, inq_ptr->version4);
10316 			break;
10317 		default:
10318 			break;
10319 		}
10320 	}
10321 
10322 	ctl_set_success(ctsio);
10323 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10324 	ctsio->be_move_done = ctl_config_move_done;
10325 	ctl_datamove((union ctl_io *)ctsio);
10326 	return (CTL_RETVAL_COMPLETE);
10327 }
10328 
10329 int
10330 ctl_inquiry(struct ctl_scsiio *ctsio)
10331 {
10332 	struct scsi_inquiry *cdb;
10333 	int retval;
10334 
10335 	CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10336 
10337 	cdb = (struct scsi_inquiry *)ctsio->cdb;
10338 	if (cdb->byte2 & SI_EVPD)
10339 		retval = ctl_inquiry_evpd(ctsio);
10340 	else if (cdb->page_code == 0)
10341 		retval = ctl_inquiry_std(ctsio);
10342 	else {
10343 		ctl_set_invalid_field(ctsio,
10344 				      /*sks_valid*/ 1,
10345 				      /*command*/ 1,
10346 				      /*field*/ 2,
10347 				      /*bit_valid*/ 0,
10348 				      /*bit*/ 0);
10349 		ctl_done((union ctl_io *)ctsio);
10350 		return (CTL_RETVAL_COMPLETE);
10351 	}
10352 
10353 	return (retval);
10354 }
10355 
10356 int
10357 ctl_get_config(struct ctl_scsiio *ctsio)
10358 {
10359 	struct ctl_lun *lun = CTL_LUN(ctsio);
10360 	struct scsi_get_config_header *hdr;
10361 	struct scsi_get_config_feature *feature;
10362 	struct scsi_get_config *cdb;
10363 	uint32_t alloc_len, data_len;
10364 	int rt, starting;
10365 
10366 	cdb = (struct scsi_get_config *)ctsio->cdb;
10367 	rt = (cdb->rt & SGC_RT_MASK);
10368 	starting = scsi_2btoul(cdb->starting_feature);
10369 	alloc_len = scsi_2btoul(cdb->length);
10370 
10371 	data_len = sizeof(struct scsi_get_config_header) +
10372 	    sizeof(struct scsi_get_config_feature) + 8 +
10373 	    sizeof(struct scsi_get_config_feature) + 8 +
10374 	    sizeof(struct scsi_get_config_feature) + 4 +
10375 	    sizeof(struct scsi_get_config_feature) + 4 +
10376 	    sizeof(struct scsi_get_config_feature) + 8 +
10377 	    sizeof(struct scsi_get_config_feature) +
10378 	    sizeof(struct scsi_get_config_feature) + 4 +
10379 	    sizeof(struct scsi_get_config_feature) + 4 +
10380 	    sizeof(struct scsi_get_config_feature) + 4 +
10381 	    sizeof(struct scsi_get_config_feature) + 4 +
10382 	    sizeof(struct scsi_get_config_feature) + 4 +
10383 	    sizeof(struct scsi_get_config_feature) + 4;
10384 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10385 	ctsio->kern_sg_entries = 0;
10386 	ctsio->kern_rel_offset = 0;
10387 
10388 	hdr = (struct scsi_get_config_header *)ctsio->kern_data_ptr;
10389 	if (lun->flags & CTL_LUN_NO_MEDIA)
10390 		scsi_ulto2b(0x0000, hdr->current_profile);
10391 	else
10392 		scsi_ulto2b(0x0010, hdr->current_profile);
10393 	feature = (struct scsi_get_config_feature *)(hdr + 1);
10394 
10395 	if (starting > 0x003b)
10396 		goto done;
10397 	if (starting > 0x003a)
10398 		goto f3b;
10399 	if (starting > 0x002b)
10400 		goto f3a;
10401 	if (starting > 0x002a)
10402 		goto f2b;
10403 	if (starting > 0x001f)
10404 		goto f2a;
10405 	if (starting > 0x001e)
10406 		goto f1f;
10407 	if (starting > 0x001d)
10408 		goto f1e;
10409 	if (starting > 0x0010)
10410 		goto f1d;
10411 	if (starting > 0x0003)
10412 		goto f10;
10413 	if (starting > 0x0002)
10414 		goto f3;
10415 	if (starting > 0x0001)
10416 		goto f2;
10417 	if (starting > 0x0000)
10418 		goto f1;
10419 
10420 	/* Profile List */
10421 	scsi_ulto2b(0x0000, feature->feature_code);
10422 	feature->flags = SGC_F_PERSISTENT | SGC_F_CURRENT;
10423 	feature->add_length = 8;
10424 	scsi_ulto2b(0x0008, &feature->feature_data[0]);	/* CD-ROM */
10425 	feature->feature_data[2] = 0x00;
10426 	scsi_ulto2b(0x0010, &feature->feature_data[4]);	/* DVD-ROM */
10427 	feature->feature_data[6] = 0x01;
10428 	feature = (struct scsi_get_config_feature *)
10429 	    &feature->feature_data[feature->add_length];
10430 
10431 f1:	/* Core */
10432 	scsi_ulto2b(0x0001, feature->feature_code);
10433 	feature->flags = 0x08 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10434 	feature->add_length = 8;
10435 	scsi_ulto4b(0x00000000, &feature->feature_data[0]);
10436 	feature->feature_data[4] = 0x03;
10437 	feature = (struct scsi_get_config_feature *)
10438 	    &feature->feature_data[feature->add_length];
10439 
10440 f2:	/* Morphing */
10441 	scsi_ulto2b(0x0002, feature->feature_code);
10442 	feature->flags = 0x04 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10443 	feature->add_length = 4;
10444 	feature->feature_data[0] = 0x02;
10445 	feature = (struct scsi_get_config_feature *)
10446 	    &feature->feature_data[feature->add_length];
10447 
10448 f3:	/* Removable Medium */
10449 	scsi_ulto2b(0x0003, feature->feature_code);
10450 	feature->flags = 0x04 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10451 	feature->add_length = 4;
10452 	feature->feature_data[0] = 0x39;
10453 	feature = (struct scsi_get_config_feature *)
10454 	    &feature->feature_data[feature->add_length];
10455 
10456 	if (rt == SGC_RT_CURRENT && (lun->flags & CTL_LUN_NO_MEDIA))
10457 		goto done;
10458 
10459 f10:	/* Random Read */
10460 	scsi_ulto2b(0x0010, feature->feature_code);
10461 	feature->flags = 0x00;
10462 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10463 		feature->flags |= SGC_F_CURRENT;
10464 	feature->add_length = 8;
10465 	scsi_ulto4b(lun->be_lun->blocksize, &feature->feature_data[0]);
10466 	scsi_ulto2b(1, &feature->feature_data[4]);
10467 	feature->feature_data[6] = 0x00;
10468 	feature = (struct scsi_get_config_feature *)
10469 	    &feature->feature_data[feature->add_length];
10470 
10471 f1d:	/* Multi-Read */
10472 	scsi_ulto2b(0x001D, feature->feature_code);
10473 	feature->flags = 0x00;
10474 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10475 		feature->flags |= SGC_F_CURRENT;
10476 	feature->add_length = 0;
10477 	feature = (struct scsi_get_config_feature *)
10478 	    &feature->feature_data[feature->add_length];
10479 
10480 f1e:	/* CD Read */
10481 	scsi_ulto2b(0x001E, feature->feature_code);
10482 	feature->flags = 0x00;
10483 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10484 		feature->flags |= SGC_F_CURRENT;
10485 	feature->add_length = 4;
10486 	feature->feature_data[0] = 0x00;
10487 	feature = (struct scsi_get_config_feature *)
10488 	    &feature->feature_data[feature->add_length];
10489 
10490 f1f:	/* DVD Read */
10491 	scsi_ulto2b(0x001F, feature->feature_code);
10492 	feature->flags = 0x08;
10493 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10494 		feature->flags |= SGC_F_CURRENT;
10495 	feature->add_length = 4;
10496 	feature->feature_data[0] = 0x01;
10497 	feature->feature_data[2] = 0x03;
10498 	feature = (struct scsi_get_config_feature *)
10499 	    &feature->feature_data[feature->add_length];
10500 
10501 f2a:	/* DVD+RW */
10502 	scsi_ulto2b(0x002A, feature->feature_code);
10503 	feature->flags = 0x04;
10504 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10505 		feature->flags |= SGC_F_CURRENT;
10506 	feature->add_length = 4;
10507 	feature->feature_data[0] = 0x00;
10508 	feature->feature_data[1] = 0x00;
10509 	feature = (struct scsi_get_config_feature *)
10510 	    &feature->feature_data[feature->add_length];
10511 
10512 f2b:	/* DVD+R */
10513 	scsi_ulto2b(0x002B, feature->feature_code);
10514 	feature->flags = 0x00;
10515 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10516 		feature->flags |= SGC_F_CURRENT;
10517 	feature->add_length = 4;
10518 	feature->feature_data[0] = 0x00;
10519 	feature = (struct scsi_get_config_feature *)
10520 	    &feature->feature_data[feature->add_length];
10521 
10522 f3a:	/* DVD+RW Dual Layer */
10523 	scsi_ulto2b(0x003A, feature->feature_code);
10524 	feature->flags = 0x00;
10525 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10526 		feature->flags |= SGC_F_CURRENT;
10527 	feature->add_length = 4;
10528 	feature->feature_data[0] = 0x00;
10529 	feature->feature_data[1] = 0x00;
10530 	feature = (struct scsi_get_config_feature *)
10531 	    &feature->feature_data[feature->add_length];
10532 
10533 f3b:	/* DVD+R Dual Layer */
10534 	scsi_ulto2b(0x003B, feature->feature_code);
10535 	feature->flags = 0x00;
10536 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10537 		feature->flags |= SGC_F_CURRENT;
10538 	feature->add_length = 4;
10539 	feature->feature_data[0] = 0x00;
10540 	feature = (struct scsi_get_config_feature *)
10541 	    &feature->feature_data[feature->add_length];
10542 
10543 done:
10544 	data_len = (uint8_t *)feature - (uint8_t *)hdr;
10545 	if (rt == SGC_RT_SPECIFIC && data_len > 4) {
10546 		feature = (struct scsi_get_config_feature *)(hdr + 1);
10547 		if (scsi_2btoul(feature->feature_code) == starting)
10548 			feature = (struct scsi_get_config_feature *)
10549 			    &feature->feature_data[feature->add_length];
10550 		data_len = (uint8_t *)feature - (uint8_t *)hdr;
10551 	}
10552 	scsi_ulto4b(data_len - 4, hdr->data_length);
10553 	ctsio->kern_data_len = min(data_len, alloc_len);
10554 	ctsio->kern_total_len = ctsio->kern_data_len;
10555 
10556 	ctl_set_success(ctsio);
10557 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10558 	ctsio->be_move_done = ctl_config_move_done;
10559 	ctl_datamove((union ctl_io *)ctsio);
10560 	return (CTL_RETVAL_COMPLETE);
10561 }
10562 
10563 int
10564 ctl_get_event_status(struct ctl_scsiio *ctsio)
10565 {
10566 	struct scsi_get_event_status_header *hdr;
10567 	struct scsi_get_event_status *cdb;
10568 	uint32_t alloc_len, data_len;
10569 
10570 	cdb = (struct scsi_get_event_status *)ctsio->cdb;
10571 	if ((cdb->byte2 & SGESN_POLLED) == 0) {
10572 		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1, /*command*/ 1,
10573 		    /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
10574 		ctl_done((union ctl_io *)ctsio);
10575 		return (CTL_RETVAL_COMPLETE);
10576 	}
10577 	alloc_len = scsi_2btoul(cdb->length);
10578 
10579 	data_len = sizeof(struct scsi_get_event_status_header);
10580 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10581 	ctsio->kern_sg_entries = 0;
10582 	ctsio->kern_rel_offset = 0;
10583 	ctsio->kern_data_len = min(data_len, alloc_len);
10584 	ctsio->kern_total_len = ctsio->kern_data_len;
10585 
10586 	hdr = (struct scsi_get_event_status_header *)ctsio->kern_data_ptr;
10587 	scsi_ulto2b(0, hdr->descr_length);
10588 	hdr->nea_class = SGESN_NEA;
10589 	hdr->supported_class = 0;
10590 
10591 	ctl_set_success(ctsio);
10592 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10593 	ctsio->be_move_done = ctl_config_move_done;
10594 	ctl_datamove((union ctl_io *)ctsio);
10595 	return (CTL_RETVAL_COMPLETE);
10596 }
10597 
10598 int
10599 ctl_mechanism_status(struct ctl_scsiio *ctsio)
10600 {
10601 	struct scsi_mechanism_status_header *hdr;
10602 	struct scsi_mechanism_status *cdb;
10603 	uint32_t alloc_len, data_len;
10604 
10605 	cdb = (struct scsi_mechanism_status *)ctsio->cdb;
10606 	alloc_len = scsi_2btoul(cdb->length);
10607 
10608 	data_len = sizeof(struct scsi_mechanism_status_header);
10609 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10610 	ctsio->kern_sg_entries = 0;
10611 	ctsio->kern_rel_offset = 0;
10612 	ctsio->kern_data_len = min(data_len, alloc_len);
10613 	ctsio->kern_total_len = ctsio->kern_data_len;
10614 
10615 	hdr = (struct scsi_mechanism_status_header *)ctsio->kern_data_ptr;
10616 	hdr->state1 = 0x00;
10617 	hdr->state2 = 0xe0;
10618 	scsi_ulto3b(0, hdr->lba);
10619 	hdr->slots_num = 0;
10620 	scsi_ulto2b(0, hdr->slots_length);
10621 
10622 	ctl_set_success(ctsio);
10623 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10624 	ctsio->be_move_done = ctl_config_move_done;
10625 	ctl_datamove((union ctl_io *)ctsio);
10626 	return (CTL_RETVAL_COMPLETE);
10627 }
10628 
10629 static void
10630 ctl_ultomsf(uint32_t lba, uint8_t *buf)
10631 {
10632 
10633 	lba += 150;
10634 	buf[0] = 0;
10635 	buf[1] = bin2bcd((lba / 75) / 60);
10636 	buf[2] = bin2bcd((lba / 75) % 60);
10637 	buf[3] = bin2bcd(lba % 75);
10638 }
10639 
10640 int
10641 ctl_read_toc(struct ctl_scsiio *ctsio)
10642 {
10643 	struct ctl_lun *lun = CTL_LUN(ctsio);
10644 	struct scsi_read_toc_hdr *hdr;
10645 	struct scsi_read_toc_type01_descr *descr;
10646 	struct scsi_read_toc *cdb;
10647 	uint32_t alloc_len, data_len;
10648 	int format, msf;
10649 
10650 	cdb = (struct scsi_read_toc *)ctsio->cdb;
10651 	msf = (cdb->byte2 & CD_MSF) != 0;
10652 	format = cdb->format;
10653 	alloc_len = scsi_2btoul(cdb->data_len);
10654 
10655 	data_len = sizeof(struct scsi_read_toc_hdr);
10656 	if (format == 0)
10657 		data_len += 2 * sizeof(struct scsi_read_toc_type01_descr);
10658 	else
10659 		data_len += sizeof(struct scsi_read_toc_type01_descr);
10660 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10661 	ctsio->kern_sg_entries = 0;
10662 	ctsio->kern_rel_offset = 0;
10663 	ctsio->kern_data_len = min(data_len, alloc_len);
10664 	ctsio->kern_total_len = ctsio->kern_data_len;
10665 
10666 	hdr = (struct scsi_read_toc_hdr *)ctsio->kern_data_ptr;
10667 	if (format == 0) {
10668 		scsi_ulto2b(0x12, hdr->data_length);
10669 		hdr->first = 1;
10670 		hdr->last = 1;
10671 		descr = (struct scsi_read_toc_type01_descr *)(hdr + 1);
10672 		descr->addr_ctl = 0x14;
10673 		descr->track_number = 1;
10674 		if (msf)
10675 			ctl_ultomsf(0, descr->track_start);
10676 		else
10677 			scsi_ulto4b(0, descr->track_start);
10678 		descr++;
10679 		descr->addr_ctl = 0x14;
10680 		descr->track_number = 0xaa;
10681 		if (msf)
10682 			ctl_ultomsf(lun->be_lun->maxlba+1, descr->track_start);
10683 		else
10684 			scsi_ulto4b(lun->be_lun->maxlba+1, descr->track_start);
10685 	} else {
10686 		scsi_ulto2b(0x0a, hdr->data_length);
10687 		hdr->first = 1;
10688 		hdr->last = 1;
10689 		descr = (struct scsi_read_toc_type01_descr *)(hdr + 1);
10690 		descr->addr_ctl = 0x14;
10691 		descr->track_number = 1;
10692 		if (msf)
10693 			ctl_ultomsf(0, descr->track_start);
10694 		else
10695 			scsi_ulto4b(0, descr->track_start);
10696 	}
10697 
10698 	ctl_set_success(ctsio);
10699 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10700 	ctsio->be_move_done = ctl_config_move_done;
10701 	ctl_datamove((union ctl_io *)ctsio);
10702 	return (CTL_RETVAL_COMPLETE);
10703 }
10704 
10705 /*
10706  * For NVMe commands, parse the LBA and length.
10707  */
10708 static bool
10709 ctl_nvme_get_lba_len(struct ctl_nvmeio *ctnio, uint64_t *lba, uint32_t *len)
10710 {
10711 	CTL_IO_ASSERT(ctnio, NVME);
10712 
10713 	switch (ctnio->cmd.opc) {
10714 	case NVME_OPC_WRITE:
10715 	case NVME_OPC_READ:
10716 	case NVME_OPC_WRITE_UNCORRECTABLE:
10717 	case NVME_OPC_COMPARE:
10718 	case NVME_OPC_WRITE_ZEROES:
10719 	case NVME_OPC_VERIFY:
10720 		*lba = (uint64_t)le32toh(ctnio->cmd.cdw11) << 32 |
10721 		    le32toh(ctnio->cmd.cdw10);
10722 		*len = (le32toh(ctnio->cmd.cdw12) & 0xffff) + 1;
10723 		return (true);
10724 	default:
10725 		*lba = 0;
10726 		*len = 0;
10727 		return (false);
10728 	}
10729 }
10730 
10731 static bool
10732 ctl_nvme_fua(struct ctl_nvmeio *ctnio)
10733 {
10734 	return ((le32toh(ctnio->cmd.cdw12) & (1U << 30)) != 0);
10735 }
10736 
10737 int
10738 ctl_nvme_identify(struct ctl_nvmeio *ctnio)
10739 {
10740 	struct ctl_lun *lun = CTL_LUN(ctnio);
10741 	size_t len;
10742 	int retval;
10743 	uint8_t cns;
10744 
10745 	CTL_DEBUG_PRINT(("ctl_nvme_identify\n"));
10746 
10747 	CTL_IO_ASSERT(ctnio, NVME_ADMIN);
10748 	MPASS(ctnio->cmd.opc == NVME_OPC_IDENTIFY);
10749 
10750 	/*
10751 	 * The data buffer for Identify is always 4096 bytes, see
10752 	 * 5.51.1 in NVMe base specification 1.4.
10753 	 */
10754 	len = 4096;
10755 
10756 	ctnio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);
10757 	ctnio->kern_data_len = len;
10758 	ctnio->kern_total_len = len;
10759 	ctnio->kern_rel_offset = 0;
10760 	ctnio->kern_sg_entries = 0;
10761 
10762 	ctl_nvme_set_success(ctnio);
10763 	ctnio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10764 	ctnio->be_move_done = ctl_config_move_done;
10765 
10766 	/*
10767 	 * If we don't have a LUN, return an empty result for CNS == 0.
10768 	 */
10769 	if (lun == NULL) {
10770 		cns = le32toh(ctnio->cmd.cdw10) & 0xff;
10771 		switch (cns) {
10772 		case 0:
10773 			memset(ctnio->kern_data_ptr, 0, len);
10774 			ctl_datamove((union ctl_io *)ctnio);
10775 			break;
10776 		default:
10777 			ctl_nvme_set_invalid_field(ctnio);
10778 			break;
10779 		}
10780 		return (CTL_RETVAL_COMPLETE);
10781 	}
10782 
10783 	retval = lun->backend->config_read((union ctl_io *)ctnio);
10784 	return (retval);
10785 }
10786 
10787 int
10788 ctl_nvme_flush(struct ctl_nvmeio *ctnio)
10789 {
10790 	struct ctl_lun *lun = CTL_LUN(ctnio);
10791 	int retval;
10792 
10793 	CTL_DEBUG_PRINT(("ctl_nvme_flush\n"));
10794 
10795 	CTL_IO_ASSERT(ctnio, NVME);
10796 	MPASS(ctnio->cmd.opc == NVME_OPC_FLUSH);
10797 
10798 	/*
10799 	 * NVMe flushes always flush the entire namespace, not an LBA
10800 	 * range.
10801 	 */
10802 	retval = lun->backend->config_write((union ctl_io *)ctnio);
10803 
10804 	return (retval);
10805 }
10806 
10807 int
10808 ctl_nvme_read_write(struct ctl_nvmeio *ctnio)
10809 {
10810 	struct ctl_lun *lun = CTL_LUN(ctnio);
10811 	struct ctl_lba_len_flags *lbalen;
10812 	uint64_t lba;
10813 	uint32_t num_blocks;
10814 	int flags, retval;
10815 	bool isread;
10816 
10817 	CTL_DEBUG_PRINT(("ctl_nvme_read_write: command: %#x\n",
10818 	    ctnio->cmd.opc));
10819 
10820 	CTL_IO_ASSERT(ctnio, NVME);
10821 	MPASS(ctnio->cmd.opc == NVME_OPC_WRITE ||
10822 	    ctnio->cmd.opc == NVME_OPC_READ);
10823 
10824 	flags = 0;
10825 	isread = ctnio->cmd.opc == NVME_OPC_READ;
10826 	ctl_nvme_get_lba_len(ctnio, &lba, &num_blocks);
10827 
10828 	/*
10829 	 * The first check is to make sure we're in bounds, the second
10830 	 * check is to catch wrap-around problems.  If the lba + num blocks
10831 	 * is less than the lba, then we've wrapped around and the block
10832 	 * range is invalid anyway.
10833 	 */
10834 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
10835 	 || ((lba + num_blocks) < lba)) {
10836 		ctl_nvme_set_lba_out_of_range(ctnio);
10837 		ctl_done((union ctl_io *)ctnio);
10838 		return (CTL_RETVAL_COMPLETE);
10839 	}
10840 
10841 	/*
10842 	 * Set FUA and/or DPO if caches are disabled.
10843 	 *
10844 	 * For a read this may not be quite correct for the block
10845 	 * backend as any earlier writes to the LBA range should be
10846 	 * flushed to backing store as part of the read.
10847 	 */
10848 	if (ctl_nvme_fua(ctnio)) {
10849 		flags |= CTL_LLF_FUA;
10850 		if (isread)
10851 			flags |= CTL_LLF_DPO;
10852 	}
10853 
10854 	lbalen = (struct ctl_lba_len_flags *)
10855 	    &ctnio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10856 	lbalen->lba = lba;
10857 	lbalen->len = num_blocks;
10858 	lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
10859 
10860 	ctnio->kern_total_len = num_blocks * lun->be_lun->blocksize;
10861 	ctnio->kern_rel_offset = 0;
10862 
10863 	CTL_DEBUG_PRINT(("ctl_nvme_read_write: calling data_submit()\n"));
10864 
10865 	retval = lun->backend->data_submit((union ctl_io *)ctnio);
10866 	return (retval);
10867 }
10868 
10869 int
10870 ctl_nvme_write_uncorrectable(struct ctl_nvmeio *ctnio)
10871 {
10872 	struct ctl_lun *lun = CTL_LUN(ctnio);
10873 	struct ctl_lba_len_flags *lbalen;
10874 	uint64_t lba;
10875 	uint32_t num_blocks;
10876 	int retval;
10877 
10878 	CTL_DEBUG_PRINT(("ctl_nvme_write_uncorrectable\n"));
10879 
10880 	CTL_IO_ASSERT(ctnio, NVME);
10881 	MPASS(ctnio->cmd.opc == NVME_OPC_WRITE_UNCORRECTABLE);
10882 
10883 	ctl_nvme_get_lba_len(ctnio, &lba, &num_blocks);
10884 
10885 	/*
10886 	 * The first check is to make sure we're in bounds, the second
10887 	 * check is to catch wrap-around problems.  If the lba + num blocks
10888 	 * is less than the lba, then we've wrapped around and the block
10889 	 * range is invalid anyway.
10890 	 */
10891 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
10892 	 || ((lba + num_blocks) < lba)) {
10893 		ctl_nvme_set_lba_out_of_range(ctnio);
10894 		ctl_done((union ctl_io *)ctnio);
10895 		return (CTL_RETVAL_COMPLETE);
10896 	}
10897 
10898 	lbalen = (struct ctl_lba_len_flags *)
10899 	    &ctnio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10900 	lbalen->lba = lba;
10901 	lbalen->len = num_blocks;
10902 	lbalen->flags = 0;
10903 	retval = lun->backend->config_write((union ctl_io *)ctnio);
10904 
10905 	return (retval);
10906 }
10907 
10908 int
10909 ctl_nvme_compare(struct ctl_nvmeio *ctnio)
10910 {
10911 	struct ctl_lun *lun = CTL_LUN(ctnio);
10912 	struct ctl_lba_len_flags *lbalen;
10913 	uint64_t lba;
10914 	uint32_t num_blocks;
10915 	int flags;
10916 	int retval;
10917 
10918 	CTL_DEBUG_PRINT(("ctl_nvme_compare\n"));
10919 
10920 	CTL_IO_ASSERT(ctnio, NVME);
10921 	MPASS(ctnio->cmd.opc == NVME_OPC_COMPARE);
10922 
10923 	flags = 0;
10924 	ctl_nvme_get_lba_len(ctnio, &lba, &num_blocks);
10925 	if (ctl_nvme_fua(ctnio))
10926 		flags |= CTL_LLF_FUA;
10927 
10928 	/*
10929 	 * The first check is to make sure we're in bounds, the second
10930 	 * check is to catch wrap-around problems.  If the lba + num blocks
10931 	 * is less than the lba, then we've wrapped around and the block
10932 	 * range is invalid anyway.
10933 	 */
10934 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
10935 	 || ((lba + num_blocks) < lba)) {
10936 		ctl_nvme_set_lba_out_of_range(ctnio);
10937 		ctl_done((union ctl_io *)ctnio);
10938 		return (CTL_RETVAL_COMPLETE);
10939 	}
10940 
10941 	lbalen = (struct ctl_lba_len_flags *)
10942 	    &ctnio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10943 	lbalen->lba = lba;
10944 	lbalen->len = num_blocks;
10945 	lbalen->flags = CTL_LLF_COMPARE | flags;
10946 	ctnio->kern_total_len = num_blocks * lun->be_lun->blocksize;
10947 	ctnio->kern_rel_offset = 0;
10948 
10949 	CTL_DEBUG_PRINT(("ctl_nvme_compare: calling data_submit()\n"));
10950 	retval = lun->backend->data_submit((union ctl_io *)ctnio);
10951 	return (retval);
10952 }
10953 
10954 int
10955 ctl_nvme_write_zeroes(struct ctl_nvmeio *ctnio)
10956 {
10957 	struct ctl_lun *lun = CTL_LUN(ctnio);
10958 	struct ctl_lba_len_flags *lbalen;
10959 	uint64_t lba;
10960 	uint32_t num_blocks;
10961 	int retval;
10962 
10963 	CTL_DEBUG_PRINT(("ctl_nvme_write_zeroes\n"));
10964 
10965 	CTL_IO_ASSERT(ctnio, NVME);
10966 	MPASS(ctnio->cmd.opc == NVME_OPC_WRITE_ZEROES);
10967 
10968 	ctl_nvme_get_lba_len(ctnio, &lba, &num_blocks);
10969 
10970 	/*
10971 	 * The first check is to make sure we're in bounds, the second
10972 	 * check is to catch wrap-around problems.  If the lba + num blocks
10973 	 * is less than the lba, then we've wrapped around and the block
10974 	 * range is invalid anyway.
10975 	 */
10976 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
10977 	 || ((lba + num_blocks) < lba)) {
10978 		ctl_nvme_set_lba_out_of_range(ctnio);
10979 		ctl_done((union ctl_io *)ctnio);
10980 		return (CTL_RETVAL_COMPLETE);
10981 	}
10982 
10983 	lbalen = (struct ctl_lba_len_flags *)
10984 	    &ctnio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10985 	lbalen->lba = lba;
10986 	lbalen->len = num_blocks;
10987 	lbalen->flags = 0;
10988 	retval = lun->backend->config_write((union ctl_io *)ctnio);
10989 
10990 	return (retval);
10991 }
10992 
10993 int
10994 ctl_nvme_dataset_management(struct ctl_nvmeio *ctnio)
10995 {
10996 	struct ctl_lun *lun = CTL_LUN(ctnio);
10997 	struct nvme_dsm_range *r;
10998 	uint64_t lba;
10999 	uint32_t len, num_blocks;
11000 	u_int i, ranges;
11001 	int retval;
11002 
11003 	CTL_DEBUG_PRINT(("ctl_nvme_dataset_management\n"));
11004 
11005 	CTL_IO_ASSERT(ctnio, NVME);
11006 	MPASS(ctnio->cmd.opc == NVME_OPC_DATASET_MANAGEMENT);
11007 
11008 	ranges = le32toh(ctnio->cmd.cdw10) & 0xff;
11009 	len = ranges * sizeof(struct nvme_dsm_range);
11010 
11011 	/*
11012 	 * If we've got a kernel request that hasn't been malloced yet,
11013 	 * malloc it and tell the caller the data buffer is here.
11014 	 */
11015 	if ((ctnio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
11016 		ctnio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);
11017 		ctnio->kern_data_len = len;
11018 		ctnio->kern_total_len = len;
11019 		ctnio->kern_rel_offset = 0;
11020 		ctnio->kern_sg_entries = 0;
11021 		ctnio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
11022 		ctnio->be_move_done = ctl_config_move_done;
11023 		ctl_datamove((union ctl_io *)ctnio);
11024 
11025 		return (CTL_RETVAL_COMPLETE);
11026 	}
11027 
11028 	/*
11029 	 * Require a flat buffer of the correct size.
11030 	 */
11031 	if (ctnio->kern_sg_entries > 0 ||
11032 	    ctnio->kern_total_len - ctnio->kern_data_resid != len)
11033 		return (CTL_RETVAL_ERROR);
11034 
11035 	/*
11036 	 * Verify that none of the ranges are out of bounds.
11037 	 */
11038 	r = (struct nvme_dsm_range *)ctnio->kern_data_ptr;
11039 	for (i = 0; i < ranges; i++) {
11040 		lba = le64toh(r[i].starting_lba);
11041 		num_blocks = le32toh(r[i].length);
11042 		if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
11043 		    || ((lba + num_blocks) < lba)) {
11044 			ctl_nvme_set_lba_out_of_range(ctnio);
11045 			ctl_done((union ctl_io *)ctnio);
11046 			return (CTL_RETVAL_COMPLETE);
11047 		}
11048 	}
11049 
11050 	CTL_DEBUG_PRINT(("ctl_nvme_dataset_management: calling config_write()\n"));
11051 	retval = lun->backend->config_write((union ctl_io *)ctnio);
11052 	return (retval);
11053 }
11054 
11055 int
11056 ctl_nvme_verify(struct ctl_nvmeio *ctnio)
11057 {
11058 	struct ctl_lun *lun = CTL_LUN(ctnio);
11059 	struct ctl_lba_len_flags *lbalen;
11060 	uint64_t lba;
11061 	uint32_t num_blocks;
11062 	int flags;
11063 	int retval;
11064 
11065 	CTL_DEBUG_PRINT(("ctl_nvme_verify\n"));
11066 
11067 	CTL_IO_ASSERT(ctnio, NVME);
11068 	MPASS(ctnio->cmd.opc == NVME_OPC_VERIFY);
11069 
11070 	flags = 0;
11071 	ctl_nvme_get_lba_len(ctnio, &lba, &num_blocks);
11072 	if (ctl_nvme_fua(ctnio))
11073 		flags |= CTL_LLF_FUA;
11074 
11075 	/*
11076 	 * The first check is to make sure we're in bounds, the second
11077 	 * check is to catch wrap-around problems.  If the lba + num blocks
11078 	 * is less than the lba, then we've wrapped around and the block
11079 	 * range is invalid anyway.
11080 	 */
11081 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
11082 	 || ((lba + num_blocks) < lba)) {
11083 		ctl_nvme_set_lba_out_of_range(ctnio);
11084 		ctl_done((union ctl_io *)ctnio);
11085 		return (CTL_RETVAL_COMPLETE);
11086 	}
11087 
11088 	lbalen = (struct ctl_lba_len_flags *)
11089 	    &ctnio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
11090 	lbalen->lba = lba;
11091 	lbalen->len = num_blocks;
11092 	lbalen->flags = CTL_LLF_VERIFY | flags;
11093 	ctnio->kern_total_len = 0;
11094 	ctnio->kern_rel_offset = 0;
11095 
11096 	CTL_DEBUG_PRINT(("ctl_nvme_verify: calling data_submit()\n"));
11097 	retval = lun->backend->data_submit((union ctl_io *)ctnio);
11098 	return (retval);
11099 }
11100 
11101 static const struct ctl_nvme_cmd_entry *
11102 ctl_nvme_get_cmd_entry(struct ctl_nvmeio *ctnio)
11103 {
11104 	const struct ctl_nvme_cmd_entry *entry;
11105 
11106 	switch (ctnio->io_hdr.io_type) {
11107 	case CTL_IO_NVME:
11108 		entry = &nvme_nvm_cmd_table[ctnio->cmd.opc];
11109 		break;
11110 	case CTL_IO_NVME_ADMIN:
11111 		entry = &nvme_admin_cmd_table[ctnio->cmd.opc];
11112 		break;
11113 	default:
11114 		__assert_unreachable();
11115 	}
11116 	return (entry);
11117 }
11118 
11119 static const struct ctl_nvme_cmd_entry *
11120 ctl_nvme_validate_command(struct ctl_nvmeio *ctnio)
11121 {
11122 	const struct ctl_nvme_cmd_entry *entry;
11123 
11124 	entry = ctl_nvme_get_cmd_entry(ctnio);
11125 	if (entry->execute == NULL) {
11126 		ctl_nvme_set_invalid_opcode(ctnio);
11127 		ctl_done((union ctl_io *)ctnio);
11128 		return (NULL);
11129 	}
11130 
11131 	/* Validate fused commands. */
11132 	switch (NVMEV(NVME_CMD_FUSE, ctnio->cmd.fuse)) {
11133 	case NVME_FUSE_NORMAL:
11134 		break;
11135 	case NVME_FUSE_FIRST:
11136 		if (ctnio->io_hdr.io_type != CTL_IO_NVME ||
11137 		    ctnio->cmd.opc != NVME_OPC_COMPARE) {
11138 			ctl_nvme_set_invalid_field(ctnio);
11139 			ctl_done((union ctl_io *)ctnio);
11140 			return (NULL);
11141 		}
11142 		break;
11143 	case NVME_FUSE_SECOND:
11144 		if (ctnio->io_hdr.io_type != CTL_IO_NVME ||
11145 		    ctnio->cmd.opc != NVME_OPC_COMPARE) {
11146 			ctl_nvme_set_invalid_field(ctnio);
11147 			ctl_done((union ctl_io *)ctnio);
11148 			return (NULL);
11149 		}
11150 		break;
11151 	default:
11152 		ctl_nvme_set_invalid_field(ctnio);
11153 		ctl_done((union ctl_io *)ctnio);
11154 		return (NULL);
11155 	}
11156 
11157 	return (entry);
11158 }
11159 
11160 /*
11161  * This is a simpler version of ctl_scsiio_lun_check that fails
11162  * requests on a LUN without active media.
11163  *
11164  * Returns true if the command has been completed with an error.
11165  */
11166 static bool
11167 ctl_nvmeio_lun_check(struct ctl_lun *lun,
11168     const struct ctl_nvme_cmd_entry *entry, struct ctl_nvmeio *ctnio)
11169 {
11170 	mtx_assert(&lun->lun_lock, MA_OWNED);
11171 
11172 	if ((entry->flags & CTL_CMD_FLAG_OK_ON_NO_MEDIA) == 0) {
11173 		if ((lun->flags & (CTL_LUN_EJECTED | CTL_LUN_NO_MEDIA |
11174 		    CTL_LUN_STOPPED)) != 0) {
11175 			ctl_nvme_set_namespace_not_ready(ctnio);
11176 			return (true);
11177 		}
11178 	}
11179 
11180 	return (false);
11181 }
11182 
11183 /*
11184  * Check for blockage against the OOA (Order Of Arrival) queue.
11185  * Assumptions:
11186  * - pending_io is generally either incoming, or on the blocked queue
11187  * - starting I/O is the I/O we want to start the check with.
11188  */
11189 static ctl_action
11190 ctl_nvme_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
11191     union ctl_io **starting_io, union ctl_io **aborted_io)
11192 {
11193 	union ctl_io *ooa_io = *starting_io;
11194 
11195 	CTL_IO_ASSERT(pending_io, NVME, NVME_ADMIN);
11196 
11197 	mtx_assert(&lun->lun_lock, MA_OWNED);
11198 
11199 	*aborted_io = NULL;
11200 
11201 	/*
11202 	 * Aborted commands are not going to be executed and may even
11203 	 * not report completion, so we don't care about their order.
11204 	 * Let them complete ASAP to clean the OOA queue.
11205 	 */
11206 	if (__predict_false(pending_io->io_hdr.flags & CTL_FLAG_ABORT))
11207 		return (CTL_ACTION_PASS);
11208 
11209 	/*
11210 	 * NVMe has rather simple command ordering requirements.  In
11211 	 * particular, there is no requirement on the controller to
11212 	 * enforce a specific order for overlapping LBAs.  The only
11213 	 * constraint is that fused operations (Compare and Write),
11214 	 * must be completed as a unit.
11215 	 *
11216 	 * To support fused operations, the following strategy is used:
11217 	 * - the first half of a fused command is not enqueued to rtr
11218 	 *   until the second half is enqueued
11219 	 * - the second half of a fused command blocks on the first
11220 	 *   half of a fuse command
11221 	 * - subsequent commands block on the second half of the
11222 	 *   fused command
11223 	 */
11224 
11225 	/*
11226 	 * Is the previously submitted command the first half of a
11227 	 * fused operation?
11228 	 */
11229 	if (ooa_io != NULL &&
11230 	    NVMEV(NVME_CMD_FUSE, ooa_io->nvmeio.cmd.fuse) == NVME_FUSE_FIRST) {
11231 		/*
11232 		 * If this is the second half, enqueue the first half
11233 		 * and block the second half on the first half.
11234 		 */
11235 		if (NVMEV(NVME_CMD_FUSE, pending_io->nvmeio.cmd.fuse) ==
11236 		    NVME_FUSE_SECOND) {
11237 			/*
11238 			 * XXX: Do we need to wait for other rtr requests
11239 			 * to drain so this is truly atomic?
11240 			 */
11241 			return (CTL_ACTION_FUSED);
11242 		}
11243 
11244 		/* Abort the first half. */
11245 		ctl_nvme_set_missing_fused_command(&ooa_io->nvmeio);
11246 		*aborted_io = ooa_io;
11247 	} else {
11248 		switch (NVMEV(NVME_CMD_FUSE, pending_io->nvmeio.cmd.fuse)) {
11249 		case NVME_FUSE_FIRST:
11250 			/* First half, wait for the second half. */
11251 			return (CTL_ACTION_SKIP);
11252 		case NVME_FUSE_SECOND:
11253 			/* Second half without a matching first half, abort. */
11254 			ctl_nvme_set_missing_fused_command(&pending_io->nvmeio);
11255 			*aborted_io = pending_io;
11256 			return (CTL_ACTION_SKIP);
11257 		}
11258 	}
11259 
11260 	/*
11261 	 * Scan the OOA queue looking for the most recent second half
11262 	 * of a fused op.
11263 	 */
11264 	for (; ooa_io != NULL;
11265 	     ooa_io = (union ctl_io *)LIST_NEXT(&ooa_io->io_hdr, ooa_links)) {
11266 		if (NVMEV(NVME_CMD_FUSE, ooa_io->nvmeio.cmd.fuse) ==
11267 		    NVME_FUSE_SECOND) {
11268 			*starting_io = ooa_io;
11269 			return (CTL_ACTION_BLOCK);
11270 		}
11271 	}
11272 
11273 	*starting_io = NULL;
11274 	return (CTL_ACTION_PASS);
11275 }
11276 
11277 static void
11278 ctl_nvmeio_precheck(struct ctl_nvmeio *ctnio)
11279 {
11280 	struct ctl_softc *softc = CTL_SOFTC(ctnio);
11281 	struct ctl_lun *lun;
11282 	const struct ctl_nvme_cmd_entry *entry;
11283 	union ctl_io *bio, *aborted_io;
11284 	uint32_t targ_lun;
11285 
11286 	lun = NULL;
11287 	targ_lun = ctnio->io_hdr.nexus.targ_mapped_lun;
11288 	if (targ_lun < ctl_max_luns)
11289 		lun = softc->ctl_luns[targ_lun];
11290 	if (lun != NULL) {
11291 		/*
11292 		 * If the LUN is invalid, pretend that it doesn't exist.
11293 		 * It will go away as soon as all pending I/O has been
11294 		 * completed.
11295 		 */
11296 		mtx_lock(&lun->lun_lock);
11297 		if (lun->flags & CTL_LUN_DISABLED) {
11298 			mtx_unlock(&lun->lun_lock);
11299 			lun = NULL;
11300 		}
11301 	}
11302 	CTL_LUN(ctnio) = lun;
11303 	if (lun != NULL) {
11304 		CTL_BACKEND_LUN(ctnio) = lun->be_lun;
11305 
11306 		/*
11307 		 * Every I/O goes into the OOA queue for a particular LUN,
11308 		 * and stays there until completion.
11309 		 */
11310 #ifdef CTL_TIME_IO
11311 		if (LIST_EMPTY(&lun->ooa_queue))
11312 			lun->idle_time += getsbinuptime() - lun->last_busy;
11313 #endif
11314 		LIST_INSERT_HEAD(&lun->ooa_queue, &ctnio->io_hdr, ooa_links);
11315 	}
11316 
11317 	/* Get command entry and return error if it is unsupported. */
11318 	entry = ctl_nvme_validate_command(ctnio);
11319 	if (entry == NULL) {
11320 		if (lun)
11321 			mtx_unlock(&lun->lun_lock);
11322 		return;
11323 	}
11324 
11325 	ctnio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11326 	ctnio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11327 
11328 	/* All NVMe commands other than IDENTIFY require a LUN. */
11329 	if (lun == NULL) {
11330 		if (entry->flags & CTL_CMD_FLAG_OK_ON_NO_LUN) {
11331 			ctnio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11332 			ctl_enqueue_rtr((union ctl_io *)ctnio);
11333 			return;
11334 		}
11335 
11336 		ctl_nvme_set_invalid_namespace(ctnio);
11337 		ctl_done((union ctl_io *)ctnio);
11338 		CTL_DEBUG_PRINT(("ctl_nvmeio_precheck: bailing out due to invalid LUN\n"));
11339 		return;
11340 	} else {
11341 		/*
11342 		 * NVMe namespaces can only be backed by T_DIRECT LUNs.
11343 		 */
11344 		if (lun->be_lun->lun_type != T_DIRECT) {
11345 			mtx_unlock(&lun->lun_lock);
11346 			ctl_nvme_set_invalid_namespace(ctnio);
11347 			ctl_done((union ctl_io *)ctnio);
11348 			return;
11349 		}
11350 	}
11351 
11352 	if (ctl_nvmeio_lun_check(lun, entry, ctnio) != 0) {
11353 		mtx_unlock(&lun->lun_lock);
11354 		ctl_done((union ctl_io *)ctnio);
11355 		return;
11356 	}
11357 
11358 	bio = (union ctl_io *)LIST_NEXT(&ctnio->io_hdr, ooa_links);
11359 	switch (ctl_nvme_check_ooa(lun, (union ctl_io *)ctnio, &bio,
11360 	    &aborted_io)) {
11361 	case CTL_ACTION_PASS:
11362 		ctnio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11363 		mtx_unlock(&lun->lun_lock);
11364 		ctl_enqueue_rtr((union ctl_io *)ctnio);
11365 		break;
11366 	case CTL_ACTION_FUSED:
11367 		/* Block the second half on the first half. */
11368 		ctnio->io_hdr.blocker = bio;
11369 		TAILQ_INSERT_TAIL(&bio->io_hdr.blocked_queue, &ctnio->io_hdr,
11370 				  blocked_links);
11371 
11372 		/* Pass the first half. */
11373 		bio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11374 		mtx_unlock(&lun->lun_lock);
11375 		ctl_enqueue_rtr(bio);
11376 		break;
11377 	case CTL_ACTION_SKIP:
11378 		mtx_unlock(&lun->lun_lock);
11379 		break;
11380 	case CTL_ACTION_BLOCK:
11381 		ctnio->io_hdr.blocker = bio;
11382 		TAILQ_INSERT_TAIL(&bio->io_hdr.blocked_queue, &ctnio->io_hdr,
11383 				  blocked_links);
11384 		mtx_unlock(&lun->lun_lock);
11385 		break;
11386 	default:
11387 		__assert_unreachable();
11388 	}
11389 	if (aborted_io != NULL)
11390 		ctl_done(aborted_io);
11391 }
11392 
11393 static int
11394 ctl_nvmeio(struct ctl_nvmeio *ctnio)
11395 {
11396 	const struct ctl_nvme_cmd_entry *entry;
11397 	int retval;
11398 
11399 	CTL_DEBUG_PRINT(("ctl_nvmeio %s opc=%02X\n",
11400 	    ctnio->io_hdr.io_type == CTL_IO_NVME ? "nvm" : "admin",
11401 	    ctnio->cmd.opc));
11402 
11403 	entry = ctl_nvme_get_cmd_entry(ctnio);
11404 	MPASS(entry != NULL);
11405 
11406 	/*
11407 	 * If this I/O has been aborted, just send it straight to
11408 	 * ctl_done() without executing it.
11409 	 */
11410 	if (ctnio->io_hdr.flags & CTL_FLAG_ABORT) {
11411 		ctl_done((union ctl_io *)ctnio);
11412 		return (CTL_RETVAL_COMPLETE);
11413 	}
11414 
11415 	/*
11416 	 * All the checks should have been handled by ctl_nvmeio_precheck().
11417 	 * We should be clear now to just execute the I/O.
11418 	 */
11419 	retval = entry->execute(ctnio);
11420 
11421 	return (retval);
11422 }
11423 
11424 /*
11425  * For known CDB types, parse the LBA and length.
11426  */
11427 static int
11428 ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
11429 {
11430 
11431 	CTL_IO_ASSERT(io, SCSI);
11432 
11433 	switch (io->scsiio.cdb[0]) {
11434 	case COMPARE_AND_WRITE: {
11435 		struct scsi_compare_and_write *cdb;
11436 
11437 		cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
11438 
11439 		*lba = scsi_8btou64(cdb->addr);
11440 		*len = cdb->length;
11441 		break;
11442 	}
11443 	case READ_6:
11444 	case WRITE_6: {
11445 		struct scsi_rw_6 *cdb;
11446 
11447 		cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
11448 
11449 		*lba = scsi_3btoul(cdb->addr);
11450 		/* only 5 bits are valid in the most significant address byte */
11451 		*lba &= 0x1fffff;
11452 		*len = cdb->length;
11453 		break;
11454 	}
11455 	case READ_10:
11456 	case WRITE_10: {
11457 		struct scsi_rw_10 *cdb;
11458 
11459 		cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
11460 
11461 		*lba = scsi_4btoul(cdb->addr);
11462 		*len = scsi_2btoul(cdb->length);
11463 		break;
11464 	}
11465 	case WRITE_VERIFY_10: {
11466 		struct scsi_write_verify_10 *cdb;
11467 
11468 		cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
11469 
11470 		*lba = scsi_4btoul(cdb->addr);
11471 		*len = scsi_2btoul(cdb->length);
11472 		break;
11473 	}
11474 	case READ_12:
11475 	case WRITE_12: {
11476 		struct scsi_rw_12 *cdb;
11477 
11478 		cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
11479 
11480 		*lba = scsi_4btoul(cdb->addr);
11481 		*len = scsi_4btoul(cdb->length);
11482 		break;
11483 	}
11484 	case WRITE_VERIFY_12: {
11485 		struct scsi_write_verify_12 *cdb;
11486 
11487 		cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
11488 
11489 		*lba = scsi_4btoul(cdb->addr);
11490 		*len = scsi_4btoul(cdb->length);
11491 		break;
11492 	}
11493 	case READ_16:
11494 	case WRITE_16: {
11495 		struct scsi_rw_16 *cdb;
11496 
11497 		cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
11498 
11499 		*lba = scsi_8btou64(cdb->addr);
11500 		*len = scsi_4btoul(cdb->length);
11501 		break;
11502 	}
11503 	case WRITE_ATOMIC_16: {
11504 		struct scsi_write_atomic_16 *cdb;
11505 
11506 		cdb = (struct scsi_write_atomic_16 *)io->scsiio.cdb;
11507 
11508 		*lba = scsi_8btou64(cdb->addr);
11509 		*len = scsi_2btoul(cdb->length);
11510 		break;
11511 	}
11512 	case WRITE_VERIFY_16: {
11513 		struct scsi_write_verify_16 *cdb;
11514 
11515 		cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
11516 
11517 		*lba = scsi_8btou64(cdb->addr);
11518 		*len = scsi_4btoul(cdb->length);
11519 		break;
11520 	}
11521 	case WRITE_SAME_10: {
11522 		struct scsi_write_same_10 *cdb;
11523 
11524 		cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
11525 
11526 		*lba = scsi_4btoul(cdb->addr);
11527 		*len = scsi_2btoul(cdb->length);
11528 		break;
11529 	}
11530 	case WRITE_SAME_16: {
11531 		struct scsi_write_same_16 *cdb;
11532 
11533 		cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
11534 
11535 		*lba = scsi_8btou64(cdb->addr);
11536 		*len = scsi_4btoul(cdb->length);
11537 		break;
11538 	}
11539 	case VERIFY_10: {
11540 		struct scsi_verify_10 *cdb;
11541 
11542 		cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
11543 
11544 		*lba = scsi_4btoul(cdb->addr);
11545 		*len = scsi_2btoul(cdb->length);
11546 		break;
11547 	}
11548 	case VERIFY_12: {
11549 		struct scsi_verify_12 *cdb;
11550 
11551 		cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
11552 
11553 		*lba = scsi_4btoul(cdb->addr);
11554 		*len = scsi_4btoul(cdb->length);
11555 		break;
11556 	}
11557 	case VERIFY_16: {
11558 		struct scsi_verify_16 *cdb;
11559 
11560 		cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
11561 
11562 		*lba = scsi_8btou64(cdb->addr);
11563 		*len = scsi_4btoul(cdb->length);
11564 		break;
11565 	}
11566 	case UNMAP: {
11567 		*lba = 0;
11568 		*len = UINT64_MAX;
11569 		break;
11570 	}
11571 	case SERVICE_ACTION_IN: {	/* GET LBA STATUS */
11572 		struct scsi_get_lba_status *cdb;
11573 
11574 		cdb = (struct scsi_get_lba_status *)io->scsiio.cdb;
11575 		*lba = scsi_8btou64(cdb->addr);
11576 		*len = UINT32_MAX;
11577 		break;
11578 	}
11579 	default:
11580 		*lba = 0;
11581 		*len = UINT64_MAX;
11582 		return (1);
11583 	}
11584 
11585 	return (0);
11586 }
11587 
11588 static ctl_action
11589 ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2,
11590     bool seq)
11591 {
11592 	uint64_t endlba1, endlba2;
11593 
11594 	endlba1 = lba1 + len1 - (seq ? 0 : 1);
11595 	endlba2 = lba2 + len2 - 1;
11596 
11597 	if ((endlba1 < lba2) || (endlba2 < lba1))
11598 		return (CTL_ACTION_PASS);
11599 	else
11600 		return (CTL_ACTION_BLOCK);
11601 }
11602 
11603 static int
11604 ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
11605 {
11606 	struct ctl_ptr_len_flags *ptrlen;
11607 	struct scsi_unmap_desc *buf, *end, *range;
11608 	uint64_t lba;
11609 	uint32_t len;
11610 
11611 	CTL_IO_ASSERT(io, SCSI);
11612 
11613 	/* If not UNMAP -- go other way. */
11614 	if (io->scsiio.cdb[0] != UNMAP)
11615 		return (CTL_ACTION_SKIP);
11616 
11617 	/* If UNMAP without data -- block and wait for data. */
11618 	ptrlen = (struct ctl_ptr_len_flags *)
11619 	    &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
11620 	if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
11621 	    ptrlen->ptr == NULL)
11622 		return (CTL_ACTION_BLOCK);
11623 
11624 	/* UNMAP with data -- check for collision. */
11625 	buf = (struct scsi_unmap_desc *)ptrlen->ptr;
11626 	end = buf + ptrlen->len / sizeof(*buf);
11627 	for (range = buf; range < end; range++) {
11628 		lba = scsi_8btou64(range->lba);
11629 		len = scsi_4btoul(range->length);
11630 		if ((lba < lba2 + len2) && (lba + len > lba2))
11631 			return (CTL_ACTION_BLOCK);
11632 	}
11633 	return (CTL_ACTION_PASS);
11634 }
11635 
11636 static ctl_action
11637 ctl_extent_check(union ctl_io *io1, union ctl_io *io2, bool seq)
11638 {
11639 	uint64_t lba1, lba2;
11640 	uint64_t len1, len2;
11641 	int retval;
11642 
11643 	retval = ctl_get_lba_len(io2, &lba2, &len2);
11644 	KASSERT(retval == 0, ("ctl_get_lba_len() error"));
11645 
11646 	retval = ctl_extent_check_unmap(io1, lba2, len2);
11647 	if (retval != CTL_ACTION_SKIP)
11648 		return (retval);
11649 
11650 	retval = ctl_get_lba_len(io1, &lba1, &len1);
11651 	KASSERT(retval == 0, ("ctl_get_lba_len() error"));
11652 
11653 	if (seq && (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE))
11654 		seq = FALSE;
11655 	return (ctl_extent_check_lba(lba1, len1, lba2, len2, seq));
11656 }
11657 
11658 static ctl_action
11659 ctl_seq_check(union ctl_io *io1, union ctl_io *io2)
11660 {
11661 	uint64_t lba1, lba2;
11662 	uint64_t len1, len2;
11663 	int retval __diagused;
11664 
11665 	if (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE)
11666 		return (CTL_ACTION_PASS);
11667 	retval = ctl_get_lba_len(io1, &lba1, &len1);
11668 	KASSERT(retval == 0, ("ctl_get_lba_len() error"));
11669 	retval = ctl_get_lba_len(io2, &lba2, &len2);
11670 	KASSERT(retval == 0, ("ctl_get_lba_len() error"));
11671 
11672 	if (lba1 + len1 == lba2)
11673 		return (CTL_ACTION_BLOCK);
11674 	return (CTL_ACTION_PASS);
11675 }
11676 
11677 static ctl_action
11678 ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
11679     const uint8_t *serialize_row, union ctl_io *ooa_io)
11680 {
11681 	CTL_IO_ASSERT(pending_io, SCSI);
11682 	CTL_IO_ASSERT(ooa_io, SCSI);
11683 
11684 	/*
11685 	 * The initiator attempted multiple untagged commands at the same
11686 	 * time.  Can't do that.
11687 	 */
11688 	if (__predict_false(pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
11689 	 && __predict_false(ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
11690 	 && ((pending_io->io_hdr.nexus.targ_port ==
11691 	      ooa_io->io_hdr.nexus.targ_port)
11692 	  && (pending_io->io_hdr.nexus.initid ==
11693 	      ooa_io->io_hdr.nexus.initid))
11694 	 && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
11695 	      CTL_FLAG_STATUS_SENT)) == 0))
11696 		return (CTL_ACTION_OVERLAP);
11697 
11698 	/*
11699 	 * The initiator attempted to send multiple tagged commands with
11700 	 * the same ID.  (It's fine if different initiators have the same
11701 	 * tag ID.)
11702 	 *
11703 	 * Even if all of those conditions are true, we don't kill the I/O
11704 	 * if the command ahead of us has been aborted.  We won't end up
11705 	 * sending it to the FETD, and it's perfectly legal to resend a
11706 	 * command with the same tag number as long as the previous
11707 	 * instance of this tag number has been aborted somehow.
11708 	 */
11709 	if (__predict_true(pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
11710 	 && __predict_true(ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
11711 	 && __predict_false(pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
11712 	 && ((pending_io->io_hdr.nexus.targ_port ==
11713 	      ooa_io->io_hdr.nexus.targ_port)
11714 	  && (pending_io->io_hdr.nexus.initid ==
11715 	      ooa_io->io_hdr.nexus.initid))
11716 	 && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
11717 	      CTL_FLAG_STATUS_SENT)) == 0))
11718 		return (CTL_ACTION_OVERLAP_TAG);
11719 
11720 	/*
11721 	 * If we get a head of queue tag, SAM-3 says that we should
11722 	 * immediately execute it.
11723 	 *
11724 	 * What happens if this command would normally block for some other
11725 	 * reason?  e.g. a request sense with a head of queue tag
11726 	 * immediately after a write.  Normally that would block, but this
11727 	 * will result in its getting executed immediately...
11728 	 *
11729 	 * We currently return "pass" instead of "skip", so we'll end up
11730 	 * going through the rest of the queue to check for overlapped tags.
11731 	 *
11732 	 * XXX KDM check for other types of blockage first??
11733 	 */
11734 	if (__predict_false(pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE))
11735 		return (CTL_ACTION_PASS);
11736 
11737 	/*
11738 	 * Simple tags get blocked until all head of queue and ordered tags
11739 	 * ahead of them have completed.  I'm lumping untagged commands in
11740 	 * with simple tags here.  XXX KDM is that the right thing to do?
11741 	 */
11742 	if (__predict_false(ooa_io->scsiio.tag_type == CTL_TAG_ORDERED) ||
11743 	    __predict_false(ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE))
11744 		return (CTL_ACTION_BLOCK);
11745 
11746 	/* Unsupported command in OOA queue. */
11747 	if (__predict_false(ooa_io->scsiio.seridx == CTL_SERIDX_INVLD))
11748 		return (CTL_ACTION_PASS);
11749 
11750 	switch (serialize_row[ooa_io->scsiio.seridx]) {
11751 	case CTL_SER_SEQ:
11752 		if (lun->be_lun->serseq != CTL_LUN_SERSEQ_OFF)
11753 			return (ctl_seq_check(ooa_io, pending_io));
11754 		/* FALLTHROUGH */
11755 	case CTL_SER_PASS:
11756 		return (CTL_ACTION_PASS);
11757 	case CTL_SER_EXTENTOPT:
11758 		if ((lun->MODE_CTRL.queue_flags & SCP_QUEUE_ALG_MASK) ==
11759 		    SCP_QUEUE_ALG_UNRESTRICTED)
11760 			return (CTL_ACTION_PASS);
11761 		/* FALLTHROUGH */
11762 	case CTL_SER_EXTENT:
11763 		return (ctl_extent_check(ooa_io, pending_io,
11764 		    (lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
11765 	case CTL_SER_BLOCKOPT:
11766 		if ((lun->MODE_CTRL.queue_flags & SCP_QUEUE_ALG_MASK) ==
11767 		    SCP_QUEUE_ALG_UNRESTRICTED)
11768 			return (CTL_ACTION_PASS);
11769 		/* FALLTHROUGH */
11770 	case CTL_SER_BLOCK:
11771 		return (CTL_ACTION_BLOCK);
11772 	default:
11773 		__assert_unreachable();
11774 	}
11775 }
11776 
11777 /*
11778  * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
11779  * Assumptions:
11780  * - pending_io is generally either incoming, or on the blocked queue
11781  * - starting I/O is the I/O we want to start the check with.
11782  */
11783 static ctl_action
11784 ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
11785 	      union ctl_io **starting_io)
11786 {
11787 	union ctl_io *ooa_io = *starting_io;
11788 	const uint8_t *serialize_row;
11789 	ctl_action action;
11790 
11791 	CTL_IO_ASSERT(pending_io, SCSI);
11792 
11793 	mtx_assert(&lun->lun_lock, MA_OWNED);
11794 
11795 	/*
11796 	 * Aborted commands are not going to be executed and may even
11797 	 * not report completion, so we don't care about their order.
11798 	 * Let them complete ASAP to clean the OOA queue.
11799 	 */
11800 	if (__predict_false(pending_io->io_hdr.flags & CTL_FLAG_ABORT))
11801 		return (CTL_ACTION_SKIP);
11802 
11803 	/*
11804 	 * Ordered tags have to block until all items ahead of them have
11805 	 * completed.  If we get called with an ordered tag, we always
11806 	 * block, if something else is ahead of us in the queue.
11807 	 */
11808 	if ((pending_io->scsiio.tag_type == CTL_TAG_ORDERED) &&
11809 	    (ooa_io != NULL))
11810 		return (CTL_ACTION_BLOCK);
11811 
11812 	serialize_row = ctl_serialize_table[pending_io->scsiio.seridx];
11813 
11814 	/*
11815 	 * Run back along the OOA queue, starting with the current
11816 	 * blocked I/O and going through every I/O before it on the
11817 	 * queue.  If starting_io is NULL, we'll just end up returning
11818 	 * CTL_ACTION_PASS.
11819 	 */
11820 	for (; ooa_io != NULL;
11821 	     ooa_io = (union ctl_io *)LIST_NEXT(&ooa_io->io_hdr, ooa_links)) {
11822 		action = ctl_check_for_blockage(lun, pending_io, serialize_row,
11823 		    ooa_io);
11824 		if (action != CTL_ACTION_PASS) {
11825 			*starting_io = ooa_io;
11826 			return (action);
11827 		}
11828 	}
11829 
11830 	*starting_io = NULL;
11831 	return (CTL_ACTION_PASS);
11832 }
11833 
11834 /*
11835  * Try to unblock the specified I/O.
11836  *
11837  * skip parameter allows explicitly skip present blocker of the I/O,
11838  * starting from the previous one on OOA queue.  It can be used when
11839  * we know for sure that the blocker I/O does no longer count.
11840  */
11841 static void
11842 ctl_scsi_try_unblock_io(struct ctl_lun *lun, union ctl_io *io, bool skip)
11843 {
11844 	struct ctl_softc *softc = lun->ctl_softc;
11845 	union ctl_io *bio, *obio;
11846 	const struct ctl_cmd_entry *entry;
11847 	union ctl_ha_msg msg_info;
11848 	ctl_action action;
11849 
11850 	CTL_IO_ASSERT(io, SCSI);
11851 
11852 	mtx_assert(&lun->lun_lock, MA_OWNED);
11853 
11854 	if (io->io_hdr.blocker == NULL)
11855 		return;
11856 
11857 	obio = bio = io->io_hdr.blocker;
11858 	if (skip)
11859 		bio = (union ctl_io *)LIST_NEXT(&bio->io_hdr, ooa_links);
11860 	action = ctl_check_ooa(lun, io, &bio);
11861 	if (action == CTL_ACTION_BLOCK) {
11862 		/* Still blocked, but may be by different I/O now. */
11863 		if (bio != obio) {
11864 			TAILQ_REMOVE(&obio->io_hdr.blocked_queue,
11865 			    &io->io_hdr, blocked_links);
11866 			TAILQ_INSERT_TAIL(&bio->io_hdr.blocked_queue,
11867 			    &io->io_hdr, blocked_links);
11868 			io->io_hdr.blocker = bio;
11869 		}
11870 		return;
11871 	}
11872 
11873 	/* No longer blocked, one way or another. */
11874 	TAILQ_REMOVE(&obio->io_hdr.blocked_queue, &io->io_hdr, blocked_links);
11875 	io->io_hdr.blocker = NULL;
11876 
11877 	switch (action) {
11878 	case CTL_ACTION_PASS:
11879 	case CTL_ACTION_SKIP:
11880 
11881 		/* Serializing commands from the other SC retire there. */
11882 		if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) &&
11883 		    (softc->ha_mode != CTL_HA_MODE_XFER)) {
11884 			io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11885 			msg_info.hdr.original_sc = io->io_hdr.remote_io;
11886 			msg_info.hdr.serializing_sc = io;
11887 			msg_info.hdr.msg_type = CTL_MSG_R2R;
11888 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11889 			    sizeof(msg_info.hdr), M_NOWAIT);
11890 			break;
11891 		}
11892 
11893 		/*
11894 		 * Check this I/O for LUN state changes that may have happened
11895 		 * while this command was blocked. The LUN state may have been
11896 		 * changed by a command ahead of us in the queue.
11897 		 */
11898 		entry = ctl_get_cmd_entry(&io->scsiio, NULL);
11899 		if (ctl_scsiio_lun_check(lun, entry, &io->scsiio) != 0) {
11900 			ctl_done(io);
11901 			break;
11902 		}
11903 
11904 		io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11905 		ctl_enqueue_rtr(io);
11906 		break;
11907 	default:
11908 		__assert_unreachable();
11909 	case CTL_ACTION_OVERLAP:
11910 		ctl_set_overlapped_cmd(&io->scsiio);
11911 		goto error;
11912 	case CTL_ACTION_OVERLAP_TAG:
11913 		ctl_set_overlapped_tag(&io->scsiio,
11914 		    io->scsiio.tag_num & 0xff);
11915 error:
11916 		/* Serializing commands from the other SC are done here. */
11917 		if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) &&
11918 		    (softc->ha_mode != CTL_HA_MODE_XFER)) {
11919 			ctl_try_unblock_others(lun, io, TRUE);
11920 			LIST_REMOVE(&io->io_hdr, ooa_links);
11921 
11922 			ctl_copy_sense_data_back(io, &msg_info);
11923 			msg_info.hdr.original_sc = io->io_hdr.remote_io;
11924 			msg_info.hdr.serializing_sc = NULL;
11925 			msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
11926 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11927 			    sizeof(msg_info.scsi), M_WAITOK);
11928 			ctl_free_io(io);
11929 			break;
11930 		}
11931 
11932 		ctl_done(io);
11933 		break;
11934 	}
11935 }
11936 
11937 static void
11938 ctl_nvme_try_unblock_io(struct ctl_lun *lun, union ctl_io *io, bool skip)
11939 {
11940 	union ctl_io *bio;
11941 	const struct ctl_nvme_cmd_entry *entry;
11942 
11943 	CTL_IO_ASSERT(io, NVME, NVME_ADMIN);
11944 
11945 	mtx_assert(&lun->lun_lock, MA_OWNED);
11946 
11947 	if (io->io_hdr.blocker == NULL)
11948 		return;
11949 
11950 	/*
11951 	 * If this is the second half of a fused operation, it should
11952 	 * be the only io on the blocked list.  If the first half
11953 	 * failed, complete the second half with an appropriate error.
11954 	 */
11955 	bio = io->io_hdr.blocker;
11956 	if (NVMEV(NVME_CMD_FUSE, io->nvmeio.cmd.fuse) == NVME_FUSE_SECOND) {
11957 		MPASS(io ==
11958 		    (union ctl_io *)TAILQ_FIRST(&bio->io_hdr.blocked_queue));
11959 		MPASS(TAILQ_NEXT(&io->io_hdr, blocked_links) == NULL);
11960 
11961 		TAILQ_REMOVE(&bio->io_hdr.blocked_queue, &io->io_hdr,
11962 		    blocked_links);
11963 		if (bio->io_hdr.status != CTL_SUCCESS) {
11964 			ctl_nvme_set_failed_fused_command(&io->nvmeio);
11965 			ctl_done(io);
11966 			return;
11967 		}
11968 	} else {
11969 		/*
11970 		 * This must be a command that was blocked on the
11971 		 * second half of a fused operation.
11972 		 */
11973 		MPASS(NVMEV(NVME_CMD_FUSE, bio->nvmeio.cmd.fuse) ==
11974 		    NVME_FUSE_SECOND);
11975 		TAILQ_REMOVE(&bio->io_hdr.blocked_queue, &io->io_hdr,
11976 		    blocked_links);
11977 	}
11978 
11979 	entry = ctl_nvme_get_cmd_entry(&io->nvmeio);
11980 	if (ctl_nvmeio_lun_check(lun, entry, &io->nvmeio) != 0) {
11981 		ctl_done(io);
11982 		return;
11983 	}
11984 
11985 	io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11986 	ctl_enqueue_rtr(io);
11987 }
11988 
11989 static void
11990 ctl_try_unblock_io(struct ctl_lun *lun, union ctl_io *io, bool skip)
11991 {
11992 	switch (io->io_hdr.io_type) {
11993 	case CTL_IO_SCSI:
11994 		return (ctl_scsi_try_unblock_io(lun, io, skip));
11995 	case CTL_IO_NVME:
11996 	case CTL_IO_NVME_ADMIN:
11997 		return (ctl_nvme_try_unblock_io(lun, io, skip));
11998 	default:
11999 		__assert_unreachable();
12000 	}
12001 }
12002 
12003 /*
12004  * Try to unblock I/Os blocked by the specified I/O.
12005  *
12006  * skip parameter allows explicitly skip the specified I/O as blocker,
12007  * starting from the previous one on the OOA queue.  It can be used when
12008  * we know for sure that the specified I/O does no longer count (done).
12009  * It has to be still on OOA queue though so that we know where to start.
12010  */
12011 static void
12012 ctl_try_unblock_others(struct ctl_lun *lun, union ctl_io *bio, bool skip)
12013 {
12014 	union ctl_io *io, *next_io;
12015 
12016 	mtx_assert(&lun->lun_lock, MA_OWNED);
12017 
12018 	for (io = (union ctl_io *)TAILQ_FIRST(&bio->io_hdr.blocked_queue);
12019 	     io != NULL; io = next_io) {
12020 		next_io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr, blocked_links);
12021 
12022 		KASSERT(io->io_hdr.blocker != NULL,
12023 		    ("I/O %p on blocked list without blocker", io));
12024 		ctl_try_unblock_io(lun, io, skip);
12025 	}
12026 	KASSERT(!skip || TAILQ_EMPTY(&bio->io_hdr.blocked_queue),
12027 	    ("blocked_queue is not empty after skipping %p", bio));
12028 }
12029 
12030 /*
12031  * This routine (with one exception) checks LUN flags that can be set by
12032  * commands ahead of us in the OOA queue.  These flags have to be checked
12033  * when a command initially comes in, and when we pull a command off the
12034  * blocked queue and are preparing to execute it.  The reason we have to
12035  * check these flags for commands on the blocked queue is that the LUN
12036  * state may have been changed by a command ahead of us while we're on the
12037  * blocked queue.
12038  *
12039  * Ordering is somewhat important with these checks, so please pay
12040  * careful attention to the placement of any new checks.
12041  */
12042 static int
12043 ctl_scsiio_lun_check(struct ctl_lun *lun,
12044     const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
12045 {
12046 	struct ctl_softc *softc = lun->ctl_softc;
12047 	int retval;
12048 	uint32_t residx;
12049 
12050 	retval = 0;
12051 
12052 	mtx_assert(&lun->lun_lock, MA_OWNED);
12053 
12054 	/*
12055 	 * If this shelf is a secondary shelf controller, we may have to
12056 	 * reject some commands disallowed by HA mode and link state.
12057 	 */
12058 	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
12059 		if (softc->ha_link == CTL_HA_LINK_OFFLINE &&
12060 		    (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
12061 			ctl_set_lun_unavail(ctsio);
12062 			retval = 1;
12063 			goto bailout;
12064 		}
12065 		if ((lun->flags & CTL_LUN_PEER_SC_PRIMARY) == 0 &&
12066 		    (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
12067 			ctl_set_lun_transit(ctsio);
12068 			retval = 1;
12069 			goto bailout;
12070 		}
12071 		if (softc->ha_mode == CTL_HA_MODE_ACT_STBY &&
12072 		    (entry->flags & CTL_CMD_FLAG_OK_ON_STANDBY) == 0) {
12073 			ctl_set_lun_standby(ctsio);
12074 			retval = 1;
12075 			goto bailout;
12076 		}
12077 
12078 		/* The rest of checks are only done on executing side */
12079 		if (softc->ha_mode == CTL_HA_MODE_XFER)
12080 			goto bailout;
12081 	}
12082 
12083 	if (entry->pattern & CTL_LUN_PAT_WRITE) {
12084 		if (lun->be_lun->flags & CTL_LUN_FLAG_READONLY) {
12085 			ctl_set_hw_write_protected(ctsio);
12086 			retval = 1;
12087 			goto bailout;
12088 		}
12089 		if ((lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0) {
12090 			ctl_set_sense(ctsio, /*current_error*/ 1,
12091 			    /*sense_key*/ SSD_KEY_DATA_PROTECT,
12092 			    /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
12093 			retval = 1;
12094 			goto bailout;
12095 		}
12096 	}
12097 
12098 	/*
12099 	 * Check for a reservation conflict.  If this command isn't allowed
12100 	 * even on reserved LUNs, and if this initiator isn't the one who
12101 	 * reserved us, reject the command with a reservation conflict.
12102 	 */
12103 	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
12104 	if ((lun->flags & CTL_LUN_RESERVED)
12105 	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
12106 		if (lun->res_idx != residx) {
12107 			ctl_set_reservation_conflict(ctsio);
12108 			retval = 1;
12109 			goto bailout;
12110 		}
12111 	}
12112 
12113 	if ((lun->flags & CTL_LUN_PR_RESERVED) == 0 ||
12114 	    (entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV)) {
12115 		/* No reservation or command is allowed. */;
12116 	} else if ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_WRESV) &&
12117 	    (lun->pr_res_type == SPR_TYPE_WR_EX ||
12118 	     lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
12119 	     lun->pr_res_type == SPR_TYPE_WR_EX_AR)) {
12120 		/* The command is allowed for Write Exclusive resv. */;
12121 	} else {
12122 		/*
12123 		 * if we aren't registered or it's a res holder type
12124 		 * reservation and this isn't the res holder then set a
12125 		 * conflict.
12126 		 */
12127 		if (ctl_get_prkey(lun, residx) == 0 ||
12128 		    (residx != lun->pr_res_idx && lun->pr_res_type < 4)) {
12129 			ctl_set_reservation_conflict(ctsio);
12130 			retval = 1;
12131 			goto bailout;
12132 		}
12133 	}
12134 
12135 	if ((entry->flags & CTL_CMD_FLAG_OK_ON_NO_MEDIA) == 0) {
12136 		if (lun->flags & CTL_LUN_EJECTED)
12137 			ctl_set_lun_ejected(ctsio);
12138 		else if (lun->flags & CTL_LUN_NO_MEDIA) {
12139 			if (lun->flags & CTL_LUN_REMOVABLE)
12140 				ctl_set_lun_no_media(ctsio);
12141 			else
12142 				ctl_set_lun_int_reqd(ctsio);
12143 		} else if (lun->flags & CTL_LUN_STOPPED)
12144 			ctl_set_lun_stopped(ctsio);
12145 		else
12146 			goto bailout;
12147 		retval = 1;
12148 		goto bailout;
12149 	}
12150 
12151 bailout:
12152 	return (retval);
12153 }
12154 
12155 static void
12156 ctl_failover_io(union ctl_io *io, int have_lock)
12157 {
12158 	CTL_IO_ASSERT(io, SCSI);
12159 
12160 	ctl_set_busy(&io->scsiio);
12161 	ctl_done(io);
12162 }
12163 
12164 static void
12165 ctl_failover_lun(union ctl_io *rio)
12166 {
12167 	struct ctl_softc *softc = CTL_SOFTC(rio);
12168 	struct ctl_lun *lun;
12169 	struct ctl_io_hdr *io, *next_io;
12170 	uint32_t targ_lun;
12171 
12172 	targ_lun = rio->io_hdr.nexus.targ_mapped_lun;
12173 	CTL_DEBUG_PRINT(("FAILOVER for lun %u\n", targ_lun));
12174 
12175 	/* Find and lock the LUN. */
12176 	mtx_lock(&softc->ctl_lock);
12177 	if (targ_lun > ctl_max_luns ||
12178 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12179 		mtx_unlock(&softc->ctl_lock);
12180 		return;
12181 	}
12182 	mtx_lock(&lun->lun_lock);
12183 	mtx_unlock(&softc->ctl_lock);
12184 	if (lun->flags & CTL_LUN_DISABLED) {
12185 		mtx_unlock(&lun->lun_lock);
12186 		return;
12187 	}
12188 
12189 	if (softc->ha_mode == CTL_HA_MODE_XFER) {
12190 		LIST_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
12191 			/* We are master */
12192 			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
12193 				if (io->flags & CTL_FLAG_IO_ACTIVE) {
12194 					io->flags |= CTL_FLAG_ABORT |
12195 					    CTL_FLAG_FAILOVER;
12196 					ctl_try_unblock_io(lun,
12197 					    (union ctl_io *)io, FALSE);
12198 				} else { /* This can be only due to DATAMOVE */
12199 					io->msg_type = CTL_MSG_DATAMOVE_DONE;
12200 					io->flags &= ~CTL_FLAG_DMA_INPROG;
12201 					io->flags |= CTL_FLAG_IO_ACTIVE;
12202 					io->port_status = 31340;
12203 					ctl_enqueue_isc((union ctl_io *)io);
12204 				}
12205 			} else
12206 			/* We are slave */
12207 			if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
12208 				io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
12209 				if (io->flags & CTL_FLAG_IO_ACTIVE) {
12210 					io->flags |= CTL_FLAG_FAILOVER;
12211 				} else {
12212 					ctl_set_busy(&((union ctl_io *)io)->
12213 					    scsiio);
12214 					ctl_done((union ctl_io *)io);
12215 				}
12216 			}
12217 		}
12218 	} else { /* SERIALIZE modes */
12219 		LIST_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
12220 			/* We are master */
12221 			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
12222 				if (io->blocker != NULL) {
12223 					TAILQ_REMOVE(&io->blocker->io_hdr.blocked_queue,
12224 					    io, blocked_links);
12225 					io->blocker = NULL;
12226 				}
12227 				ctl_try_unblock_others(lun, (union ctl_io *)io,
12228 				    TRUE);
12229 				LIST_REMOVE(io, ooa_links);
12230 				ctl_free_io((union ctl_io *)io);
12231 			} else
12232 			/* We are slave */
12233 			if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
12234 				io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
12235 				if (!(io->flags & CTL_FLAG_IO_ACTIVE)) {
12236 					ctl_set_busy(&((union ctl_io *)io)->
12237 					    scsiio);
12238 					ctl_done((union ctl_io *)io);
12239 				}
12240 			}
12241 		}
12242 	}
12243 	mtx_unlock(&lun->lun_lock);
12244 }
12245 
12246 static void
12247 ctl_scsiio_precheck(struct ctl_scsiio *ctsio)
12248 {
12249 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
12250 	struct ctl_lun *lun;
12251 	const struct ctl_cmd_entry *entry;
12252 	union ctl_io *bio;
12253 	uint32_t initidx, targ_lun;
12254 
12255 	lun = NULL;
12256 	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
12257 	if (targ_lun < ctl_max_luns)
12258 		lun = softc->ctl_luns[targ_lun];
12259 	if (lun) {
12260 		/*
12261 		 * If the LUN is invalid, pretend that it doesn't exist.
12262 		 * It will go away as soon as all pending I/O has been
12263 		 * completed.
12264 		 */
12265 		mtx_lock(&lun->lun_lock);
12266 		if (lun->flags & CTL_LUN_DISABLED) {
12267 			mtx_unlock(&lun->lun_lock);
12268 			lun = NULL;
12269 		}
12270 	}
12271 	CTL_LUN(ctsio) = lun;
12272 	if (lun) {
12273 		CTL_BACKEND_LUN(ctsio) = lun->be_lun;
12274 
12275 		/*
12276 		 * Every I/O goes into the OOA queue for a particular LUN,
12277 		 * and stays there until completion.
12278 		 */
12279 #ifdef CTL_TIME_IO
12280 		if (LIST_EMPTY(&lun->ooa_queue))
12281 			lun->idle_time += getsbinuptime() - lun->last_busy;
12282 #endif
12283 		LIST_INSERT_HEAD(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
12284 	}
12285 
12286 	/* Get command entry and return error if it is unsuppotyed. */
12287 	entry = ctl_validate_command(ctsio);
12288 	if (entry == NULL) {
12289 		if (lun)
12290 			mtx_unlock(&lun->lun_lock);
12291 		return;
12292 	}
12293 
12294 	ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
12295 	ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
12296 
12297 	/*
12298 	 * Check to see whether we can send this command to LUNs that don't
12299 	 * exist.  This should pretty much only be the case for inquiry
12300 	 * and request sense.  Further checks, below, really require having
12301 	 * a LUN, so we can't really check the command anymore.  Just put
12302 	 * it on the rtr queue.
12303 	 */
12304 	if (lun == NULL) {
12305 		if (entry->flags & CTL_CMD_FLAG_OK_ON_NO_LUN) {
12306 			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12307 			ctl_enqueue_rtr((union ctl_io *)ctsio);
12308 			return;
12309 		}
12310 
12311 		ctl_set_unsupported_lun(ctsio);
12312 		ctl_done((union ctl_io *)ctsio);
12313 		CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
12314 		return;
12315 	} else {
12316 		/*
12317 		 * Make sure we support this particular command on this LUN.
12318 		 * e.g., we don't support writes to the control LUN.
12319 		 */
12320 		if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
12321 			mtx_unlock(&lun->lun_lock);
12322 			ctl_set_invalid_opcode(ctsio);
12323 			ctl_done((union ctl_io *)ctsio);
12324 			return;
12325 		}
12326 	}
12327 
12328 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
12329 
12330 	/*
12331 	 * If we've got a request sense, it'll clear the contingent
12332 	 * allegiance condition.  Otherwise, if we have a CA condition for
12333 	 * this initiator, clear it, because it sent down a command other
12334 	 * than request sense.
12335 	 */
12336 	if (ctsio->cdb[0] != REQUEST_SENSE) {
12337 		struct scsi_sense_data *ps;
12338 
12339 		ps = lun->pending_sense[initidx / CTL_MAX_INIT_PER_PORT];
12340 		if (ps != NULL)
12341 			ps[initidx % CTL_MAX_INIT_PER_PORT].error_code = 0;
12342 	}
12343 
12344 	/*
12345 	 * If the command has this flag set, it handles its own unit
12346 	 * attention reporting, we shouldn't do anything.  Otherwise we
12347 	 * check for any pending unit attentions, and send them back to the
12348 	 * initiator.  We only do this when a command initially comes in,
12349 	 * not when we pull it off the blocked queue.
12350 	 *
12351 	 * According to SAM-3, section 5.3.2, the order that things get
12352 	 * presented back to the host is basically unit attentions caused
12353 	 * by some sort of reset event, busy status, reservation conflicts
12354 	 * or task set full, and finally any other status.
12355 	 *
12356 	 * One issue here is that some of the unit attentions we report
12357 	 * don't fall into the "reset" category (e.g. "reported luns data
12358 	 * has changed").  So reporting it here, before the reservation
12359 	 * check, may be technically wrong.  I guess the only thing to do
12360 	 * would be to check for and report the reset events here, and then
12361 	 * check for the other unit attention types after we check for a
12362 	 * reservation conflict.
12363 	 *
12364 	 * XXX KDM need to fix this
12365 	 */
12366 	if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
12367 		ctl_ua_type ua_type;
12368 		u_int sense_len = 0;
12369 
12370 		ua_type = ctl_build_ua(lun, initidx, &ctsio->sense_data,
12371 		    &sense_len, SSD_TYPE_NONE);
12372 		if (ua_type != CTL_UA_NONE) {
12373 			mtx_unlock(&lun->lun_lock);
12374 			ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
12375 			ctsio->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12376 			ctsio->sense_len = sense_len;
12377 			ctl_done((union ctl_io *)ctsio);
12378 			return;
12379 		}
12380 	}
12381 
12382 	if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
12383 		mtx_unlock(&lun->lun_lock);
12384 		ctl_done((union ctl_io *)ctsio);
12385 		return;
12386 	}
12387 
12388 	/*
12389 	 * XXX CHD this is where we want to send IO to other side if
12390 	 * this LUN is secondary on this SC. We will need to make a copy
12391 	 * of the IO and flag the IO on this side as SENT_2OTHER and the flag
12392 	 * the copy we send as FROM_OTHER.
12393 	 * We also need to stuff the address of the original IO so we can
12394 	 * find it easily. Something similar will need be done on the other
12395 	 * side so when we are done we can find the copy.
12396 	 */
12397 	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
12398 	    (lun->flags & CTL_LUN_PEER_SC_PRIMARY) != 0 &&
12399 	    (entry->flags & CTL_CMD_FLAG_RUN_HERE) == 0) {
12400 		union ctl_ha_msg msg_info;
12401 		int isc_retval;
12402 
12403 		ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
12404 		ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12405 		mtx_unlock(&lun->lun_lock);
12406 
12407 		msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
12408 		msg_info.hdr.original_sc = (union ctl_io *)ctsio;
12409 		msg_info.hdr.serializing_sc = NULL;
12410 		msg_info.hdr.nexus = ctsio->io_hdr.nexus;
12411 		msg_info.scsi.tag_num = ctsio->tag_num;
12412 		msg_info.scsi.tag_type = ctsio->tag_type;
12413 		memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
12414 		msg_info.scsi.cdb_len = ctsio->cdb_len;
12415 		msg_info.scsi.priority = ctsio->priority;
12416 
12417 		if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12418 		    sizeof(msg_info.scsi) - sizeof(msg_info.scsi.sense_data),
12419 		    M_WAITOK)) > CTL_HA_STATUS_SUCCESS) {
12420 			ctsio->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
12421 			ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
12422 			ctl_set_busy(ctsio);
12423 			ctl_done((union ctl_io *)ctsio);
12424 			return;
12425 		}
12426 		return;
12427 	}
12428 
12429 	bio = (union ctl_io *)LIST_NEXT(&ctsio->io_hdr, ooa_links);
12430 	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio, &bio)) {
12431 	case CTL_ACTION_PASS:
12432 	case CTL_ACTION_SKIP:
12433 		ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12434 		mtx_unlock(&lun->lun_lock);
12435 		ctl_enqueue_rtr((union ctl_io *)ctsio);
12436 		break;
12437 	case CTL_ACTION_BLOCK:
12438 		ctsio->io_hdr.blocker = bio;
12439 		TAILQ_INSERT_TAIL(&bio->io_hdr.blocked_queue, &ctsio->io_hdr,
12440 				  blocked_links);
12441 		mtx_unlock(&lun->lun_lock);
12442 		break;
12443 	case CTL_ACTION_OVERLAP:
12444 		mtx_unlock(&lun->lun_lock);
12445 		ctl_set_overlapped_cmd(ctsio);
12446 		ctl_done((union ctl_io *)ctsio);
12447 		break;
12448 	case CTL_ACTION_OVERLAP_TAG:
12449 		mtx_unlock(&lun->lun_lock);
12450 		ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
12451 		ctl_done((union ctl_io *)ctsio);
12452 		break;
12453 	default:
12454 		__assert_unreachable();
12455 	}
12456 }
12457 
12458 const struct ctl_cmd_entry *
12459 ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
12460 {
12461 	const struct ctl_cmd_entry *entry;
12462 	int service_action;
12463 
12464 	entry = &ctl_cmd_table[ctsio->cdb[0]];
12465 	if (sa)
12466 		*sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
12467 	if (entry->flags & CTL_CMD_FLAG_SA5) {
12468 		service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
12469 		entry = &((const struct ctl_cmd_entry *)
12470 		    entry->execute)[service_action];
12471 	}
12472 	return (entry);
12473 }
12474 
12475 const struct ctl_cmd_entry *
12476 ctl_validate_command(struct ctl_scsiio *ctsio)
12477 {
12478 	const struct ctl_cmd_entry *entry;
12479 	int i, sa;
12480 	uint8_t diff;
12481 
12482 	entry = ctl_get_cmd_entry(ctsio, &sa);
12483 	ctsio->seridx = entry->seridx;
12484 	if (entry->execute == NULL) {
12485 		if (sa)
12486 			ctl_set_invalid_field(ctsio,
12487 					      /*sks_valid*/ 1,
12488 					      /*command*/ 1,
12489 					      /*field*/ 1,
12490 					      /*bit_valid*/ 1,
12491 					      /*bit*/ 4);
12492 		else
12493 			ctl_set_invalid_opcode(ctsio);
12494 		ctl_done((union ctl_io *)ctsio);
12495 		return (NULL);
12496 	}
12497 	KASSERT(entry->length > 0,
12498 	    ("Not defined length for command 0x%02x/0x%02x",
12499 	     ctsio->cdb[0], ctsio->cdb[1]));
12500 	for (i = 1; i < entry->length; i++) {
12501 		diff = ctsio->cdb[i] & ~entry->usage[i - 1];
12502 		if (diff == 0)
12503 			continue;
12504 		ctl_set_invalid_field(ctsio,
12505 				      /*sks_valid*/ 1,
12506 				      /*command*/ 1,
12507 				      /*field*/ i,
12508 				      /*bit_valid*/ 1,
12509 				      /*bit*/ fls(diff) - 1);
12510 		ctl_done((union ctl_io *)ctsio);
12511 		return (NULL);
12512 	}
12513 	return (entry);
12514 }
12515 
12516 static int
12517 ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
12518 {
12519 
12520 	switch (lun_type) {
12521 	case T_DIRECT:
12522 		if ((entry->flags & CTL_CMD_FLAG_OK_ON_DIRECT) == 0)
12523 			return (0);
12524 		break;
12525 	case T_PROCESSOR:
12526 		if ((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0)
12527 			return (0);
12528 		break;
12529 	case T_CDROM:
12530 		if ((entry->flags & CTL_CMD_FLAG_OK_ON_CDROM) == 0)
12531 			return (0);
12532 		break;
12533 	default:
12534 		return (0);
12535 	}
12536 	return (1);
12537 }
12538 
12539 static int
12540 ctl_scsiio(struct ctl_scsiio *ctsio)
12541 {
12542 	int retval;
12543 	const struct ctl_cmd_entry *entry;
12544 
12545 	retval = CTL_RETVAL_COMPLETE;
12546 
12547 	CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
12548 
12549 	entry = ctl_get_cmd_entry(ctsio, NULL);
12550 
12551 	/*
12552 	 * If this I/O has been aborted, just send it straight to
12553 	 * ctl_done() without executing it.
12554 	 */
12555 	if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
12556 		ctl_done((union ctl_io *)ctsio);
12557 		goto bailout;
12558 	}
12559 
12560 	/*
12561 	 * All the checks should have been handled by ctl_scsiio_precheck().
12562 	 * We should be clear now to just execute the I/O.
12563 	 */
12564 	retval = entry->execute(ctsio);
12565 
12566 bailout:
12567 	return (retval);
12568 }
12569 
12570 static int
12571 ctl_target_reset(union ctl_io *io)
12572 {
12573 	struct ctl_softc *softc = CTL_SOFTC(io);
12574 	struct ctl_port *port = CTL_PORT(io);
12575 	struct ctl_lun *lun;
12576 	uint32_t initidx;
12577 	ctl_ua_type ua_type;
12578 
12579 	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12580 		union ctl_ha_msg msg_info;
12581 
12582 		msg_info.hdr.nexus = io->io_hdr.nexus;
12583 		msg_info.task.task_action = io->taskio.task_action;
12584 		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12585 		msg_info.hdr.original_sc = NULL;
12586 		msg_info.hdr.serializing_sc = NULL;
12587 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12588 		    sizeof(msg_info.task), M_WAITOK);
12589 	}
12590 
12591 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
12592 	if (io->taskio.task_action == CTL_TASK_TARGET_RESET)
12593 		ua_type = CTL_UA_TARG_RESET;
12594 	else
12595 		ua_type = CTL_UA_BUS_RESET;
12596 	mtx_lock(&softc->ctl_lock);
12597 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
12598 		if (port != NULL &&
12599 		    ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
12600 			continue;
12601 		ctl_do_lun_reset(lun, initidx, ua_type);
12602 	}
12603 	mtx_unlock(&softc->ctl_lock);
12604 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12605 	return (0);
12606 }
12607 
12608 /*
12609  * The LUN should always be set.  The I/O is optional, and is used to
12610  * distinguish between I/Os sent by this initiator, and by other
12611  * initiators.  We set unit attention for initiators other than this one.
12612  * SAM-3 is vague on this point.  It does say that a unit attention should
12613  * be established for other initiators when a LUN is reset (see section
12614  * 5.7.3), but it doesn't specifically say that the unit attention should
12615  * be established for this particular initiator when a LUN is reset.  Here
12616  * is the relevant text, from SAM-3 rev 8:
12617  *
12618  * 5.7.2 When a SCSI initiator port aborts its own tasks
12619  *
12620  * When a SCSI initiator port causes its own task(s) to be aborted, no
12621  * notification that the task(s) have been aborted shall be returned to
12622  * the SCSI initiator port other than the completion response for the
12623  * command or task management function action that caused the task(s) to
12624  * be aborted and notification(s) associated with related effects of the
12625  * action (e.g., a reset unit attention condition).
12626  *
12627  * XXX KDM for now, we're setting unit attention for all initiators.
12628  */
12629 static void
12630 ctl_do_lun_reset(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua_type)
12631 {
12632 	struct ctl_io_hdr *xioh;
12633 	int i;
12634 
12635 	mtx_lock(&lun->lun_lock);
12636 	/* Abort tasks. */
12637 	LIST_FOREACH(xioh, &lun->ooa_queue, ooa_links) {
12638 		xioh->flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
12639 		ctl_try_unblock_io(lun, (union ctl_io *)xioh, FALSE);
12640 	}
12641 	/* Clear CA. */
12642 	for (i = 0; i < ctl_max_ports; i++) {
12643 		free(lun->pending_sense[i], M_CTL);
12644 		lun->pending_sense[i] = NULL;
12645 	}
12646 	/* Clear reservation. */
12647 	lun->flags &= ~CTL_LUN_RESERVED;
12648 	/* Clear prevent media removal. */
12649 	if (lun->prevent) {
12650 		for (i = 0; i < CTL_MAX_INITIATORS; i++)
12651 			ctl_clear_mask(lun->prevent, i);
12652 		lun->prevent_count = 0;
12653 	}
12654 	/* Clear TPC status */
12655 	ctl_tpc_lun_clear(lun, -1);
12656 	/* Establish UA. */
12657 #if 0
12658 	ctl_est_ua_all(lun, initidx, ua_type);
12659 #else
12660 	ctl_est_ua_all(lun, -1, ua_type);
12661 #endif
12662 	mtx_unlock(&lun->lun_lock);
12663 }
12664 
12665 static int
12666 ctl_lun_reset(union ctl_io *io)
12667 {
12668 	struct ctl_softc *softc = CTL_SOFTC(io);
12669 	struct ctl_lun *lun;
12670 	uint32_t targ_lun, initidx;
12671 
12672 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12673 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
12674 	mtx_lock(&softc->ctl_lock);
12675 	if (targ_lun >= ctl_max_luns ||
12676 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12677 		mtx_unlock(&softc->ctl_lock);
12678 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12679 		return (1);
12680 	}
12681 	ctl_do_lun_reset(lun, initidx, CTL_UA_LUN_RESET);
12682 	mtx_unlock(&softc->ctl_lock);
12683 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12684 
12685 	if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0) {
12686 		union ctl_ha_msg msg_info;
12687 
12688 		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12689 		msg_info.hdr.nexus = io->io_hdr.nexus;
12690 		msg_info.task.task_action = CTL_TASK_LUN_RESET;
12691 		msg_info.hdr.original_sc = NULL;
12692 		msg_info.hdr.serializing_sc = NULL;
12693 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12694 		    sizeof(msg_info.task), M_WAITOK);
12695 	}
12696 	return (0);
12697 }
12698 
12699 static void
12700 ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
12701     int other_sc)
12702 {
12703 	struct ctl_io_hdr *xioh;
12704 
12705 	mtx_assert(&lun->lun_lock, MA_OWNED);
12706 
12707 	/*
12708 	 * Run through the OOA queue and attempt to find the given I/O.
12709 	 * The target port, initiator ID, tag type and tag number have to
12710 	 * match the values that we got from the initiator.  If we have an
12711 	 * untagged command to abort, simply abort the first untagged command
12712 	 * we come to.  We only allow one untagged command at a time of course.
12713 	 */
12714 	LIST_FOREACH(xioh, &lun->ooa_queue, ooa_links) {
12715 		union ctl_io *xio = (union ctl_io *)xioh;
12716 
12717 		if ((targ_port == UINT32_MAX ||
12718 		     targ_port == xioh->nexus.targ_port) &&
12719 		    (init_id == UINT32_MAX ||
12720 		     init_id == xioh->nexus.initid)) {
12721 			if (targ_port != xioh->nexus.targ_port ||
12722 			    init_id != xioh->nexus.initid)
12723 				xioh->flags |= CTL_FLAG_ABORT_STATUS;
12724 			xioh->flags |= CTL_FLAG_ABORT;
12725 			if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12726 				union ctl_ha_msg msg_info;
12727 
12728 				CTL_IO_ASSERT(xio, SCSI);
12729 				msg_info.hdr.nexus = xioh->nexus;
12730 				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
12731 				msg_info.task.tag_num = xio->scsiio.tag_num;
12732 				msg_info.task.tag_type = xio->scsiio.tag_type;
12733 				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12734 				msg_info.hdr.original_sc = NULL;
12735 				msg_info.hdr.serializing_sc = NULL;
12736 				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12737 				    sizeof(msg_info.task), M_NOWAIT);
12738 			}
12739 			ctl_try_unblock_io(lun, xio, FALSE);
12740 		}
12741 	}
12742 }
12743 
12744 static int
12745 ctl_abort_task_set(union ctl_io *io)
12746 {
12747 	struct ctl_softc *softc = CTL_SOFTC(io);
12748 	struct ctl_lun *lun;
12749 	uint32_t targ_lun;
12750 
12751 	/*
12752 	 * Look up the LUN.
12753 	 */
12754 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12755 	mtx_lock(&softc->ctl_lock);
12756 	if (targ_lun >= ctl_max_luns ||
12757 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12758 		mtx_unlock(&softc->ctl_lock);
12759 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12760 		return (1);
12761 	}
12762 
12763 	mtx_lock(&lun->lun_lock);
12764 	mtx_unlock(&softc->ctl_lock);
12765 	if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
12766 		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12767 		    io->io_hdr.nexus.initid,
12768 		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12769 	} else { /* CTL_TASK_CLEAR_TASK_SET */
12770 		ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
12771 		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12772 	}
12773 	mtx_unlock(&lun->lun_lock);
12774 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12775 	return (0);
12776 }
12777 
12778 static void
12779 ctl_i_t_nexus_loss(struct ctl_softc *softc, uint32_t initidx,
12780     ctl_ua_type ua_type)
12781 {
12782 	struct ctl_lun *lun;
12783 	struct scsi_sense_data *ps;
12784 	uint32_t p, i;
12785 
12786 	p = initidx / CTL_MAX_INIT_PER_PORT;
12787 	i = initidx % CTL_MAX_INIT_PER_PORT;
12788 	mtx_lock(&softc->ctl_lock);
12789 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
12790 		mtx_lock(&lun->lun_lock);
12791 		/* Abort tasks. */
12792 		ctl_abort_tasks_lun(lun, p, i, 1);
12793 		/* Clear CA. */
12794 		ps = lun->pending_sense[p];
12795 		if (ps != NULL)
12796 			ps[i].error_code = 0;
12797 		/* Clear reservation. */
12798 		if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == initidx))
12799 			lun->flags &= ~CTL_LUN_RESERVED;
12800 		/* Clear prevent media removal. */
12801 		if (lun->prevent && ctl_is_set(lun->prevent, initidx)) {
12802 			ctl_clear_mask(lun->prevent, initidx);
12803 			lun->prevent_count--;
12804 		}
12805 		/* Clear TPC status */
12806 		ctl_tpc_lun_clear(lun, initidx);
12807 		/* Establish UA. */
12808 		ctl_est_ua(lun, initidx, ua_type);
12809 		mtx_unlock(&lun->lun_lock);
12810 	}
12811 	mtx_unlock(&softc->ctl_lock);
12812 }
12813 
12814 static int
12815 ctl_i_t_nexus_reset(union ctl_io *io)
12816 {
12817 	struct ctl_softc *softc = CTL_SOFTC(io);
12818 	uint32_t initidx;
12819 
12820 	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12821 		union ctl_ha_msg msg_info;
12822 
12823 		msg_info.hdr.nexus = io->io_hdr.nexus;
12824 		msg_info.task.task_action = CTL_TASK_I_T_NEXUS_RESET;
12825 		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12826 		msg_info.hdr.original_sc = NULL;
12827 		msg_info.hdr.serializing_sc = NULL;
12828 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12829 		    sizeof(msg_info.task), M_WAITOK);
12830 	}
12831 
12832 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
12833 	ctl_i_t_nexus_loss(softc, initidx, CTL_UA_I_T_NEXUS_LOSS);
12834 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12835 	return (0);
12836 }
12837 
12838 static int
12839 ctl_abort_task(union ctl_io *io)
12840 {
12841 	struct ctl_softc *softc = CTL_SOFTC(io);
12842 	struct ctl_io_hdr *xioh;
12843 	struct ctl_lun *lun;
12844 	uint32_t targ_lun;
12845 
12846 	/*
12847 	 * Look up the LUN.
12848 	 */
12849 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12850 	mtx_lock(&softc->ctl_lock);
12851 	if (targ_lun >= ctl_max_luns ||
12852 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12853 		mtx_unlock(&softc->ctl_lock);
12854 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12855 		return (1);
12856 	}
12857 
12858 	mtx_lock(&lun->lun_lock);
12859 	mtx_unlock(&softc->ctl_lock);
12860 	/*
12861 	 * Run through the OOA queue and attempt to find the given I/O.
12862 	 * The target port, initiator ID, tag type and tag number have to
12863 	 * match the values that we got from the initiator.  If we have an
12864 	 * untagged command to abort, simply abort the first untagged command
12865 	 * we come to.  We only allow one untagged command at a time of course.
12866 	 */
12867 	LIST_FOREACH(xioh, &lun->ooa_queue, ooa_links) {
12868 		union ctl_io *xio = (union ctl_io *)xioh;
12869 
12870 		CTL_IO_ASSERT(xio, SCSI);
12871 		if ((xioh->nexus.targ_port != io->io_hdr.nexus.targ_port)
12872 		 || (xioh->nexus.initid != io->io_hdr.nexus.initid)
12873 		 || (xioh->flags & CTL_FLAG_ABORT))
12874 			continue;
12875 
12876 		/*
12877 		 * If the abort says that the task is untagged, the
12878 		 * task in the queue must be untagged.  Otherwise,
12879 		 * we just check to see whether the tag numbers
12880 		 * match.  This is because the QLogic firmware
12881 		 * doesn't pass back the tag type in an abort
12882 		 * request.
12883 		 */
12884 #if 0
12885 		if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
12886 		  && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
12887 		 || (xio->scsiio.tag_num == io->taskio.tag_num)) {
12888 #else
12889 		/*
12890 		 * XXX KDM we've got problems with FC, because it
12891 		 * doesn't send down a tag type with aborts.  So we
12892 		 * can only really go by the tag number...
12893 		 * This may cause problems with parallel SCSI.
12894 		 * Need to figure that out!!
12895 		 */
12896 		if (xio->scsiio.tag_num == io->taskio.tag_num) {
12897 #endif
12898 			xioh->flags |= CTL_FLAG_ABORT;
12899 			if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0 &&
12900 			    !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12901 				union ctl_ha_msg msg_info;
12902 
12903 				msg_info.hdr.nexus = io->io_hdr.nexus;
12904 				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
12905 				msg_info.task.tag_num = io->taskio.tag_num;
12906 				msg_info.task.tag_type = io->taskio.tag_type;
12907 				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12908 				msg_info.hdr.original_sc = NULL;
12909 				msg_info.hdr.serializing_sc = NULL;
12910 				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12911 				    sizeof(msg_info.task), M_NOWAIT);
12912 			}
12913 			ctl_try_unblock_io(lun, xio, FALSE);
12914 		}
12915 	}
12916 	mtx_unlock(&lun->lun_lock);
12917 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12918 	return (0);
12919 }
12920 
12921 static int
12922 ctl_query_task(union ctl_io *io, int task_set)
12923 {
12924 	struct ctl_softc *softc = CTL_SOFTC(io);
12925 	struct ctl_io_hdr *xioh;
12926 	struct ctl_lun *lun;
12927 	int found = 0;
12928 	uint32_t targ_lun;
12929 
12930 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12931 	mtx_lock(&softc->ctl_lock);
12932 	if (targ_lun >= ctl_max_luns ||
12933 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12934 		mtx_unlock(&softc->ctl_lock);
12935 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12936 		return (1);
12937 	}
12938 	mtx_lock(&lun->lun_lock);
12939 	mtx_unlock(&softc->ctl_lock);
12940 	LIST_FOREACH(xioh, &lun->ooa_queue, ooa_links) {
12941 		union ctl_io *xio = (union ctl_io *)xioh;
12942 
12943 		CTL_IO_ASSERT(xio, SCSI);
12944 		if ((xioh->nexus.targ_port != io->io_hdr.nexus.targ_port)
12945 		 || (xioh->nexus.initid != io->io_hdr.nexus.initid)
12946 		 || (xioh->flags & CTL_FLAG_ABORT))
12947 			continue;
12948 
12949 		if (task_set || xio->scsiio.tag_num == io->taskio.tag_num) {
12950 			found = 1;
12951 			break;
12952 		}
12953 	}
12954 	mtx_unlock(&lun->lun_lock);
12955 	if (found)
12956 		io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12957 	else
12958 		io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12959 	return (0);
12960 }
12961 
12962 static int
12963 ctl_query_async_event(union ctl_io *io)
12964 {
12965 	struct ctl_softc *softc = CTL_SOFTC(io);
12966 	struct ctl_lun *lun;
12967 	ctl_ua_type ua;
12968 	uint32_t targ_lun, initidx;
12969 
12970 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12971 	mtx_lock(&softc->ctl_lock);
12972 	if (targ_lun >= ctl_max_luns ||
12973 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12974 		mtx_unlock(&softc->ctl_lock);
12975 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12976 		return (1);
12977 	}
12978 	mtx_lock(&lun->lun_lock);
12979 	mtx_unlock(&softc->ctl_lock);
12980 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
12981 	ua = ctl_build_qae(lun, initidx, io->taskio.task_resp);
12982 	mtx_unlock(&lun->lun_lock);
12983 	if (ua != CTL_UA_NONE)
12984 		io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12985 	else
12986 		io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12987 	return (0);
12988 }
12989 
12990 static void
12991 ctl_run_task(union ctl_io *io)
12992 {
12993 	int retval = 1;
12994 
12995 	CTL_DEBUG_PRINT(("ctl_run_task\n"));
12996 	KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12997 	    ("ctl_run_task: Unextected io_type %d\n", io->io_hdr.io_type));
12998 	io->taskio.task_status = CTL_TASK_FUNCTION_NOT_SUPPORTED;
12999 	bzero(io->taskio.task_resp, sizeof(io->taskio.task_resp));
13000 	switch (io->taskio.task_action) {
13001 	case CTL_TASK_ABORT_TASK:
13002 		retval = ctl_abort_task(io);
13003 		break;
13004 	case CTL_TASK_ABORT_TASK_SET:
13005 	case CTL_TASK_CLEAR_TASK_SET:
13006 		retval = ctl_abort_task_set(io);
13007 		break;
13008 	case CTL_TASK_CLEAR_ACA:
13009 		break;
13010 	case CTL_TASK_I_T_NEXUS_RESET:
13011 		retval = ctl_i_t_nexus_reset(io);
13012 		break;
13013 	case CTL_TASK_LUN_RESET:
13014 		retval = ctl_lun_reset(io);
13015 		break;
13016 	case CTL_TASK_TARGET_RESET:
13017 	case CTL_TASK_BUS_RESET:
13018 		retval = ctl_target_reset(io);
13019 		break;
13020 	case CTL_TASK_PORT_LOGIN:
13021 		break;
13022 	case CTL_TASK_PORT_LOGOUT:
13023 		break;
13024 	case CTL_TASK_QUERY_TASK:
13025 		retval = ctl_query_task(io, 0);
13026 		break;
13027 	case CTL_TASK_QUERY_TASK_SET:
13028 		retval = ctl_query_task(io, 1);
13029 		break;
13030 	case CTL_TASK_QUERY_ASYNC_EVENT:
13031 		retval = ctl_query_async_event(io);
13032 		break;
13033 	default:
13034 		printf("%s: got unknown task management event %d\n",
13035 		       __func__, io->taskio.task_action);
13036 		break;
13037 	}
13038 	if (retval == 0)
13039 		io->io_hdr.status = CTL_SUCCESS;
13040 	else
13041 		io->io_hdr.status = CTL_ERROR;
13042 	ctl_done(io);
13043 }
13044 
13045 /*
13046  * For HA operation.  Handle commands that come in from the other
13047  * controller.
13048  */
13049 static void
13050 ctl_handle_isc(union ctl_io *io)
13051 {
13052 	struct ctl_softc *softc = CTL_SOFTC(io);
13053 	struct ctl_lun *lun;
13054 	const struct ctl_cmd_entry *entry;
13055 	uint32_t targ_lun;
13056 
13057 	CTL_IO_ASSERT(io, SCSI);
13058 
13059 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
13060 	switch (io->io_hdr.msg_type) {
13061 	case CTL_MSG_SERIALIZE:
13062 		ctl_serialize_other_sc_cmd(&io->scsiio);
13063 		break;
13064 	case CTL_MSG_R2R:		/* Only used in SER_ONLY mode. */
13065 		entry = ctl_get_cmd_entry(&io->scsiio, NULL);
13066 		if (targ_lun >= ctl_max_luns ||
13067 		    (lun = softc->ctl_luns[targ_lun]) == NULL) {
13068 			ctl_done(io);
13069 			break;
13070 		}
13071 		mtx_lock(&lun->lun_lock);
13072 		if (ctl_scsiio_lun_check(lun, entry, &io->scsiio) != 0) {
13073 			mtx_unlock(&lun->lun_lock);
13074 			ctl_done(io);
13075 			break;
13076 		}
13077 		io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
13078 		mtx_unlock(&lun->lun_lock);
13079 		ctl_enqueue_rtr(io);
13080 		break;
13081 	case CTL_MSG_FINISH_IO:
13082 		if (softc->ha_mode == CTL_HA_MODE_XFER) {
13083 			ctl_done(io);
13084 			break;
13085 		}
13086 		if (targ_lun >= ctl_max_luns ||
13087 		    (lun = softc->ctl_luns[targ_lun]) == NULL) {
13088 			ctl_free_io(io);
13089 			break;
13090 		}
13091 		mtx_lock(&lun->lun_lock);
13092 		ctl_try_unblock_others(lun, io, TRUE);
13093 		LIST_REMOVE(&io->io_hdr, ooa_links);
13094 		mtx_unlock(&lun->lun_lock);
13095 		ctl_free_io(io);
13096 		break;
13097 	case CTL_MSG_PERS_ACTION:
13098 		ctl_hndl_per_res_out_on_other_sc(io);
13099 		ctl_free_io(io);
13100 		break;
13101 	case CTL_MSG_BAD_JUJU:
13102 		ctl_done(io);
13103 		break;
13104 	case CTL_MSG_DATAMOVE:		/* Only used in XFER mode */
13105 		ctl_datamove_remote(io);
13106 		break;
13107 	case CTL_MSG_DATAMOVE_DONE:	/* Only used in XFER mode */
13108 		ctl_datamove_done(io, false);
13109 		break;
13110 	case CTL_MSG_FAILOVER:
13111 		ctl_failover_lun(io);
13112 		ctl_free_io(io);
13113 		break;
13114 	default:
13115 		printf("%s: Invalid message type %d\n",
13116 		       __func__, io->io_hdr.msg_type);
13117 		ctl_free_io(io);
13118 		break;
13119 	}
13120 
13121 }
13122 
13123 /*
13124  * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
13125  * there is no match.
13126  */
13127 static ctl_lun_error_pattern
13128 ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
13129 {
13130 	const struct ctl_cmd_entry *entry;
13131 	ctl_lun_error_pattern filtered_pattern, pattern;
13132 
13133 	pattern = desc->error_pattern;
13134 
13135 	/*
13136 	 * XXX KDM we need more data passed into this function to match a
13137 	 * custom pattern, and we actually need to implement custom pattern
13138 	 * matching.
13139 	 */
13140 	if (pattern & CTL_LUN_PAT_CMD)
13141 		return (CTL_LUN_PAT_CMD);
13142 
13143 	if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
13144 		return (CTL_LUN_PAT_ANY);
13145 
13146 	entry = ctl_get_cmd_entry(ctsio, NULL);
13147 
13148 	filtered_pattern = entry->pattern & pattern;
13149 
13150 	/*
13151 	 * If the user requested specific flags in the pattern (e.g.
13152 	 * CTL_LUN_PAT_RANGE), make sure the command supports all of those
13153 	 * flags.
13154 	 *
13155 	 * If the user did not specify any flags, it doesn't matter whether
13156 	 * or not the command supports the flags.
13157 	 */
13158 	if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
13159 	     (pattern & ~CTL_LUN_PAT_MASK))
13160 		return (CTL_LUN_PAT_NONE);
13161 
13162 	/*
13163 	 * If the user asked for a range check, see if the requested LBA
13164 	 * range overlaps with this command's LBA range.
13165 	 */
13166 	if (filtered_pattern & CTL_LUN_PAT_RANGE) {
13167 		uint64_t lba1;
13168 		uint64_t len1;
13169 		ctl_action action;
13170 		int retval;
13171 
13172 		retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
13173 		if (retval != 0)
13174 			return (CTL_LUN_PAT_NONE);
13175 
13176 		action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
13177 					      desc->lba_range.len, FALSE);
13178 		/*
13179 		 * A "pass" means that the LBA ranges don't overlap, so
13180 		 * this doesn't match the user's range criteria.
13181 		 */
13182 		if (action == CTL_ACTION_PASS)
13183 			return (CTL_LUN_PAT_NONE);
13184 	}
13185 
13186 	return (filtered_pattern);
13187 }
13188 
13189 static void
13190 ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
13191 {
13192 	struct ctl_error_desc *desc, *desc2;
13193 
13194 	CTL_IO_ASSERT(io, SCSI);
13195 
13196 	mtx_assert(&lun->lun_lock, MA_OWNED);
13197 
13198 	STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
13199 		ctl_lun_error_pattern pattern;
13200 		/*
13201 		 * Check to see whether this particular command matches
13202 		 * the pattern in the descriptor.
13203 		 */
13204 		pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
13205 		if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
13206 			continue;
13207 
13208 		switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
13209 		case CTL_LUN_INJ_ABORTED:
13210 			ctl_set_aborted(&io->scsiio);
13211 			break;
13212 		case CTL_LUN_INJ_MEDIUM_ERR:
13213 			ctl_set_medium_error(&io->scsiio,
13214 			    (io->io_hdr.flags & CTL_FLAG_DATA_MASK) !=
13215 			     CTL_FLAG_DATA_OUT);
13216 			break;
13217 		case CTL_LUN_INJ_UA:
13218 			/* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
13219 			 * OCCURRED */
13220 			ctl_set_ua(&io->scsiio, 0x29, 0x00);
13221 			break;
13222 		case CTL_LUN_INJ_CUSTOM:
13223 			/*
13224 			 * We're assuming the user knows what he is doing.
13225 			 * Just copy the sense information without doing
13226 			 * checks.
13227 			 */
13228 			bcopy(&desc->custom_sense, &io->scsiio.sense_data,
13229 			      MIN(sizeof(desc->custom_sense),
13230 				  sizeof(io->scsiio.sense_data)));
13231 			io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
13232 			io->scsiio.sense_len = SSD_FULL_SIZE;
13233 			io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
13234 			break;
13235 		case CTL_LUN_INJ_NONE:
13236 		default:
13237 			/*
13238 			 * If this is an error injection type we don't know
13239 			 * about, clear the continuous flag (if it is set)
13240 			 * so it will get deleted below.
13241 			 */
13242 			desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
13243 			break;
13244 		}
13245 		/*
13246 		 * By default, each error injection action is a one-shot
13247 		 */
13248 		if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
13249 			continue;
13250 
13251 		STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
13252 
13253 		free(desc, M_CTL);
13254 	}
13255 }
13256 
13257 #ifdef CTL_IO_DELAY
13258 static void
13259 ctl_datamove_timer_wakeup(void *arg)
13260 {
13261 	union ctl_io *io;
13262 
13263 	io = (union ctl_io *)arg;
13264 
13265 	ctl_datamove(io);
13266 }
13267 #endif /* CTL_IO_DELAY */
13268 
13269 static void
13270 ctl_datamove_done_process(union ctl_io *io)
13271 {
13272 #ifdef CTL_TIME_IO
13273 	struct bintime cur_bt;
13274 
13275 	getbinuptime(&cur_bt);
13276 	bintime_sub(&cur_bt, &io->io_hdr.dma_start_bt);
13277 	bintime_add(&io->io_hdr.dma_bt, &cur_bt);
13278 #endif
13279 	io->io_hdr.num_dmas++;
13280 
13281 	if ((io->io_hdr.port_status != 0) &&
13282 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
13283 	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
13284 		switch (io->io_hdr.io_type) {
13285 		case CTL_IO_SCSI:
13286 			ctl_set_internal_failure(&io->scsiio, /*sks_valid*/ 1,
13287 			    /*retry_count*/ io->io_hdr.port_status);
13288 			break;
13289 		case CTL_IO_NVME:
13290 		case CTL_IO_NVME_ADMIN:
13291 			if (io->io_hdr.flags & CTL_FLAG_ABORT)
13292 				ctl_nvme_set_command_aborted(&io->nvmeio);
13293 			else
13294 				ctl_nvme_set_data_transfer_error(&io->nvmeio);
13295 			break;
13296 		default:
13297 			__assert_unreachable();
13298 		}
13299 	} else if (ctl_kern_data_resid(io) != 0 &&
13300 	    (io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT &&
13301 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
13302 	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
13303 		switch (io->io_hdr.io_type) {
13304 		case CTL_IO_SCSI:
13305 			ctl_set_invalid_field_ciu(&io->scsiio);
13306 			break;
13307 		case CTL_IO_NVME:
13308 		case CTL_IO_NVME_ADMIN:
13309 			ctl_nvme_set_data_transfer_error(&io->nvmeio);
13310 			break;
13311 		default:
13312 			__assert_unreachable();
13313 		}
13314 	} else if (ctl_debug & CTL_DEBUG_CDB_DATA)
13315 		ctl_data_print(io);
13316 }
13317 
13318 void
13319 ctl_datamove_done(union ctl_io *io, bool samethr)
13320 {
13321 
13322 	ctl_datamove_done_process(io);
13323 	ctl_be_move_done(io, samethr);
13324 }
13325 
13326 void
13327 ctl_datamove(union ctl_io *io)
13328 {
13329 	void (*fe_datamove)(union ctl_io *io);
13330 
13331 	mtx_assert(&((struct ctl_softc *)CTL_SOFTC(io))->ctl_lock, MA_NOTOWNED);
13332 
13333 	CTL_DEBUG_PRINT(("ctl_datamove\n"));
13334 
13335 	/* No data transferred yet.  Frontend must update this when done. */
13336 	ctl_set_kern_data_resid(io, ctl_kern_data_len(io));
13337 
13338 #ifdef CTL_TIME_IO
13339 	getbinuptime(&io->io_hdr.dma_start_bt);
13340 #endif /* CTL_TIME_IO */
13341 
13342 #ifdef CTL_IO_DELAY
13343 	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13344 		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13345 	} else {
13346 		struct ctl_lun *lun;
13347 
13348 		lun = CTL_LUN(io);
13349 		if ((lun != NULL)
13350 		 && (lun->delay_info.datamove_delay > 0)) {
13351 			callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
13352 			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
13353 			callout_reset(&io->io_hdr.delay_callout,
13354 				      lun->delay_info.datamove_delay * hz,
13355 				      ctl_datamove_timer_wakeup, io);
13356 			if (lun->delay_info.datamove_type ==
13357 			    CTL_DELAY_TYPE_ONESHOT)
13358 				lun->delay_info.datamove_delay = 0;
13359 			return;
13360 		}
13361 	}
13362 #endif
13363 
13364 	/*
13365 	 * This command has been aborted.  Set the port status, so we fail
13366 	 * the data move.
13367 	 */
13368 	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
13369 		switch (io->io_hdr.io_type) {
13370 		case CTL_IO_SCSI:
13371 			printf("ctl_datamove: tag 0x%jx on (%u:%u:%u) aborted\n",
13372 			    io->scsiio.tag_num, io->io_hdr.nexus.initid,
13373 			    io->io_hdr.nexus.targ_port,
13374 			    io->io_hdr.nexus.targ_lun);
13375 			break;
13376 		case CTL_IO_NVME:
13377 		case CTL_IO_NVME_ADMIN:
13378 			printf("ctl_datamove: CID 0x%x on (%u:%u:%u) aborted\n",
13379 			    le16toh(io->nvmeio.cmd.cid),
13380 			    io->io_hdr.nexus.initid, io->io_hdr.nexus.targ_port,
13381 			    io->io_hdr.nexus.targ_lun);
13382 			break;
13383 		default:
13384 			__assert_unreachable();
13385 		}
13386 		io->io_hdr.port_status = 31337;
13387 		ctl_datamove_done_process(io);
13388 		ctl_be_move_done(io, true);
13389 		return;
13390 	}
13391 
13392 	/* Don't confuse frontend with zero length data move. */
13393 	if (ctl_kern_data_len(io) == 0) {
13394 		ctl_datamove_done_process(io);
13395 		ctl_be_move_done(io, true);
13396 		return;
13397 	}
13398 
13399 	fe_datamove = CTL_PORT(io)->fe_datamove;
13400 	fe_datamove(io);
13401 }
13402 
13403 static void
13404 ctl_send_datamove_done(union ctl_io *io, int have_lock)
13405 {
13406 	union ctl_ha_msg msg;
13407 #ifdef CTL_TIME_IO
13408 	struct bintime cur_bt;
13409 #endif
13410 
13411 	CTL_IO_ASSERT(io, SCSI);
13412 
13413 	memset(&msg, 0, sizeof(msg));
13414 	msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
13415 	msg.hdr.original_sc = io;
13416 	msg.hdr.serializing_sc = io->io_hdr.remote_io;
13417 	msg.hdr.nexus = io->io_hdr.nexus;
13418 	msg.hdr.status = io->io_hdr.status;
13419 	msg.scsi.kern_data_resid = io->scsiio.kern_data_resid;
13420 	msg.scsi.tag_num = io->scsiio.tag_num;
13421 	msg.scsi.tag_type = io->scsiio.tag_type;
13422 	msg.scsi.scsi_status = io->scsiio.scsi_status;
13423 	memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
13424 	       io->scsiio.sense_len);
13425 	msg.scsi.sense_len = io->scsiio.sense_len;
13426 	msg.scsi.port_status = io->io_hdr.port_status;
13427 	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
13428 	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13429 		ctl_failover_io(io, /*have_lock*/ have_lock);
13430 		return;
13431 	}
13432 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13433 	    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
13434 	    msg.scsi.sense_len, M_WAITOK);
13435 
13436 #ifdef CTL_TIME_IO
13437 	getbinuptime(&cur_bt);
13438 	bintime_sub(&cur_bt, &io->io_hdr.dma_start_bt);
13439 	bintime_add(&io->io_hdr.dma_bt, &cur_bt);
13440 #endif
13441 	io->io_hdr.num_dmas++;
13442 }
13443 
13444 /*
13445  * The DMA to the remote side is done, now we need to tell the other side
13446  * we're done so it can continue with its data movement.
13447  */
13448 static void
13449 ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
13450 {
13451 	union ctl_io *io;
13452 	uint32_t i;
13453 
13454 	io = rq->context;
13455 	CTL_IO_ASSERT(io, SCSI);
13456 
13457 	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
13458 		printf("%s: ISC DMA write failed with error %d", __func__,
13459 		       rq->ret);
13460 		ctl_set_internal_failure(&io->scsiio,
13461 					 /*sks_valid*/ 1,
13462 					 /*retry_count*/ rq->ret);
13463 	}
13464 
13465 	ctl_dt_req_free(rq);
13466 
13467 	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13468 		free(CTL_LSGLT(io)[i].addr, M_CTL);
13469 	free(CTL_RSGL(io), M_CTL);
13470 	CTL_RSGL(io) = NULL;
13471 	CTL_LSGL(io) = NULL;
13472 
13473 	/*
13474 	 * The data is in local and remote memory, so now we need to send
13475 	 * status (good or back) back to the other side.
13476 	 */
13477 	ctl_send_datamove_done(io, /*have_lock*/ 0);
13478 }
13479 
13480 /*
13481  * We've moved the data from the host/controller into local memory.  Now we
13482  * need to push it over to the remote controller's memory.
13483  */
13484 static int
13485 ctl_datamove_remote_dm_write_cb(union ctl_io *io, bool samethr)
13486 {
13487 	int retval;
13488 
13489 	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
13490 					  ctl_datamove_remote_write_cb);
13491 	return (retval);
13492 }
13493 
13494 static void
13495 ctl_datamove_remote_write(union ctl_io *io)
13496 {
13497 	int retval;
13498 	void (*fe_datamove)(union ctl_io *io);
13499 
13500 	CTL_IO_ASSERT(io, SCSI);
13501 
13502 	/*
13503 	 * - Get the data from the host/HBA into local memory.
13504 	 * - DMA memory from the local controller to the remote controller.
13505 	 * - Send status back to the remote controller.
13506 	 */
13507 
13508 	retval = ctl_datamove_remote_sgl_setup(io);
13509 	if (retval != 0)
13510 		return;
13511 
13512 	/* Switch the pointer over so the FETD knows what to do */
13513 	io->scsiio.kern_data_ptr = (uint8_t *)CTL_LSGL(io);
13514 
13515 	/*
13516 	 * Use a custom move done callback, since we need to send completion
13517 	 * back to the other controller, not to the backend on this side.
13518 	 */
13519 	io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
13520 
13521 	fe_datamove = CTL_PORT(io)->fe_datamove;
13522 	fe_datamove(io);
13523 }
13524 
13525 static int
13526 ctl_datamove_remote_dm_read_cb(union ctl_io *io, bool samethr)
13527 {
13528 	uint32_t i;
13529 
13530 	CTL_IO_ASSERT(io, SCSI);
13531 
13532 	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13533 		free(CTL_LSGLT(io)[i].addr, M_CTL);
13534 	free(CTL_RSGL(io), M_CTL);
13535 	CTL_RSGL(io) = NULL;
13536 	CTL_LSGL(io) = NULL;
13537 
13538 	/*
13539 	 * The read is done, now we need to send status (good or bad) back
13540 	 * to the other side.
13541 	 */
13542 	ctl_send_datamove_done(io, /*have_lock*/ 0);
13543 
13544 	return (0);
13545 }
13546 
13547 static void
13548 ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
13549 {
13550 	union ctl_io *io;
13551 	void (*fe_datamove)(union ctl_io *io);
13552 
13553 	io = rq->context;
13554 	CTL_IO_ASSERT(io, SCSI);
13555 
13556 	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
13557 		printf("%s: ISC DMA read failed with error %d\n", __func__,
13558 		       rq->ret);
13559 		ctl_set_internal_failure(&io->scsiio,
13560 					 /*sks_valid*/ 1,
13561 					 /*retry_count*/ rq->ret);
13562 	}
13563 
13564 	ctl_dt_req_free(rq);
13565 
13566 	/* Switch the pointer over so the FETD knows what to do */
13567 	io->scsiio.kern_data_ptr = (uint8_t *)CTL_LSGL(io);
13568 
13569 	/*
13570 	 * Use a custom move done callback, since we need to send completion
13571 	 * back to the other controller, not to the backend on this side.
13572 	 */
13573 	io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
13574 
13575 	/* XXX KDM add checks like the ones in ctl_datamove? */
13576 
13577 	fe_datamove = CTL_PORT(io)->fe_datamove;
13578 	fe_datamove(io);
13579 }
13580 
13581 static int
13582 ctl_datamove_remote_sgl_setup(union ctl_io *io)
13583 {
13584 	struct ctl_sg_entry *local_sglist;
13585 	uint32_t len_to_go;
13586 	int retval;
13587 	int i;
13588 
13589 	CTL_IO_ASSERT(io, SCSI);
13590 
13591 	retval = 0;
13592 	local_sglist = CTL_LSGL(io);
13593 	len_to_go = io->scsiio.kern_data_len;
13594 
13595 	/*
13596 	 * The difficult thing here is that the size of the various
13597 	 * S/G segments may be different than the size from the
13598 	 * remote controller.  That'll make it harder when DMAing
13599 	 * the data back to the other side.
13600 	 */
13601 	for (i = 0; len_to_go > 0; i++) {
13602 		local_sglist[i].len = MIN(len_to_go, CTL_HA_DATAMOVE_SEGMENT);
13603 		local_sglist[i].addr =
13604 		    malloc(local_sglist[i].len, M_CTL, M_WAITOK);
13605 
13606 		len_to_go -= local_sglist[i].len;
13607 	}
13608 	/*
13609 	 * Reset the number of S/G entries accordingly.  The original
13610 	 * number of S/G entries is available in rem_sg_entries.
13611 	 */
13612 	io->scsiio.kern_sg_entries = i;
13613 
13614 	return (retval);
13615 }
13616 
13617 static int
13618 ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
13619 			 ctl_ha_dt_cb callback)
13620 {
13621 	struct ctl_ha_dt_req *rq;
13622 	struct ctl_sg_entry *remote_sglist, *local_sglist;
13623 	uint32_t local_used, remote_used, total_used;
13624 	int i, j, isc_ret;
13625 
13626 	rq = ctl_dt_req_alloc();
13627 
13628 	CTL_IO_ASSERT(io, SCSI);
13629 
13630 	/*
13631 	 * If we failed to allocate the request, and if the DMA didn't fail
13632 	 * anyway, set busy status.  This is just a resource allocation
13633 	 * failure.
13634 	 */
13635 	if ((rq == NULL)
13636 	 && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
13637 	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS))
13638 		ctl_set_busy(&io->scsiio);
13639 
13640 	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
13641 	    (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) {
13642 		if (rq != NULL)
13643 			ctl_dt_req_free(rq);
13644 
13645 		/*
13646 		 * The data move failed.  We need to return status back
13647 		 * to the other controller.  No point in trying to DMA
13648 		 * data to the remote controller.
13649 		 */
13650 
13651 		ctl_send_datamove_done(io, /*have_lock*/ 0);
13652 
13653 		return (1);
13654 	}
13655 
13656 	local_sglist = CTL_LSGL(io);
13657 	remote_sglist = CTL_RSGL(io);
13658 	local_used = 0;
13659 	remote_used = 0;
13660 	total_used = 0;
13661 
13662 	/*
13663 	 * Pull/push the data over the wire from/to the other controller.
13664 	 * This takes into account the possibility that the local and
13665 	 * remote sglists may not be identical in terms of the size of
13666 	 * the elements and the number of elements.
13667 	 *
13668 	 * One fundamental assumption here is that the length allocated for
13669 	 * both the local and remote sglists is identical.  Otherwise, we've
13670 	 * essentially got a coding error of some sort.
13671 	 */
13672 	isc_ret = CTL_HA_STATUS_SUCCESS;
13673 	for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
13674 		uint32_t cur_len;
13675 		uint8_t *tmp_ptr;
13676 
13677 		rq->command = command;
13678 		rq->context = io;
13679 
13680 		/*
13681 		 * Both pointers should be aligned.  But it is possible
13682 		 * that the allocation length is not.  They should both
13683 		 * also have enough slack left over at the end, though,
13684 		 * to round up to the next 8 byte boundary.
13685 		 */
13686 		cur_len = MIN(local_sglist[i].len - local_used,
13687 			      remote_sglist[j].len - remote_used);
13688 		rq->size = cur_len;
13689 
13690 		tmp_ptr = (uint8_t *)local_sglist[i].addr;
13691 		tmp_ptr += local_used;
13692 
13693 #if 0
13694 		/* Use physical addresses when talking to ISC hardware */
13695 		if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
13696 			/* XXX KDM use busdma */
13697 			rq->local = vtophys(tmp_ptr);
13698 		} else
13699 			rq->local = tmp_ptr;
13700 #else
13701 		KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
13702 		    ("HA does not support BUS_ADDR"));
13703 		rq->local = tmp_ptr;
13704 #endif
13705 
13706 		tmp_ptr = (uint8_t *)remote_sglist[j].addr;
13707 		tmp_ptr += remote_used;
13708 		rq->remote = tmp_ptr;
13709 
13710 		rq->callback = NULL;
13711 
13712 		local_used += cur_len;
13713 		if (local_used >= local_sglist[i].len) {
13714 			i++;
13715 			local_used = 0;
13716 		}
13717 
13718 		remote_used += cur_len;
13719 		if (remote_used >= remote_sglist[j].len) {
13720 			j++;
13721 			remote_used = 0;
13722 		}
13723 		total_used += cur_len;
13724 
13725 		if (total_used >= io->scsiio.kern_data_len)
13726 			rq->callback = callback;
13727 
13728 		isc_ret = ctl_dt_single(rq);
13729 		if (isc_ret > CTL_HA_STATUS_SUCCESS)
13730 			break;
13731 	}
13732 	if (isc_ret != CTL_HA_STATUS_WAIT) {
13733 		rq->ret = isc_ret;
13734 		callback(rq);
13735 	}
13736 
13737 	return (0);
13738 }
13739 
13740 static void
13741 ctl_datamove_remote_read(union ctl_io *io)
13742 {
13743 	int retval;
13744 	uint32_t i;
13745 
13746 	/*
13747 	 * This will send an error to the other controller in the case of a
13748 	 * failure.
13749 	 */
13750 	retval = ctl_datamove_remote_sgl_setup(io);
13751 	if (retval != 0)
13752 		return;
13753 
13754 	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
13755 					  ctl_datamove_remote_read_cb);
13756 	if (retval != 0) {
13757 		/*
13758 		 * Make sure we free memory if there was an error..  The
13759 		 * ctl_datamove_remote_xfer() function will send the
13760 		 * datamove done message, or call the callback with an
13761 		 * error if there is a problem.
13762 		 */
13763 		for (i = 0; i < ctl_kern_sg_entries(io); i++)
13764 			free(CTL_LSGLT(io)[i].addr, M_CTL);
13765 		free(CTL_RSGL(io), M_CTL);
13766 		CTL_RSGL(io) = NULL;
13767 		CTL_LSGL(io) = NULL;
13768 	}
13769 }
13770 
13771 /*
13772  * Process a datamove request from the other controller.  This is used for
13773  * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
13774  * first.  Once that is complete, the data gets DMAed into the remote
13775  * controller's memory.  For reads, we DMA from the remote controller's
13776  * memory into our memory first, and then move it out to the FETD.
13777  */
13778 static void
13779 ctl_datamove_remote(union ctl_io *io)
13780 {
13781 	CTL_IO_ASSERT(io, SCSI);
13782 
13783 	mtx_assert(&((struct ctl_softc *)CTL_SOFTC(io))->ctl_lock, MA_NOTOWNED);
13784 
13785 	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13786 		ctl_failover_io(io, /*have_lock*/ 0);
13787 		return;
13788 	}
13789 
13790 	/*
13791 	 * Note that we look for an aborted I/O here, but don't do some of
13792 	 * the other checks that ctl_datamove() normally does.
13793 	 * We don't need to run the datamove delay code, since that should
13794 	 * have been done if need be on the other controller.
13795 	 */
13796 	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
13797 		printf("%s: tag 0x%jx on (%u:%u:%u) aborted\n", __func__,
13798 		       io->scsiio.tag_num, io->io_hdr.nexus.initid,
13799 		       io->io_hdr.nexus.targ_port,
13800 		       io->io_hdr.nexus.targ_lun);
13801 		io->io_hdr.port_status = 31338;
13802 		ctl_send_datamove_done(io, /*have_lock*/ 0);
13803 		return;
13804 	}
13805 
13806 	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT)
13807 		ctl_datamove_remote_write(io);
13808 	else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
13809 		ctl_datamove_remote_read(io);
13810 	else {
13811 		io->io_hdr.port_status = 31339;
13812 		ctl_send_datamove_done(io, /*have_lock*/ 0);
13813 	}
13814 }
13815 
13816 static void
13817 ctl_process_done(union ctl_io *io)
13818 {
13819 	struct ctl_softc *softc = CTL_SOFTC(io);
13820 	struct ctl_port *port = CTL_PORT(io);
13821 	struct ctl_lun *lun = CTL_LUN(io);
13822 	void (*fe_done)(union ctl_io *io);
13823 	union ctl_ha_msg msg;
13824 
13825 	CTL_DEBUG_PRINT(("ctl_process_done\n"));
13826 	fe_done = port->fe_done;
13827 
13828 #ifdef CTL_TIME_IO
13829 	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
13830 		char str[256];
13831 		char path_str[64];
13832 		struct sbuf sb;
13833 
13834 		ctl_scsi_path_string(&io->io_hdr, path_str, sizeof(path_str));
13835 		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13836 
13837 		ctl_io_sbuf(io, &sb);
13838 		sbuf_cat(&sb, path_str);
13839 		sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
13840 			    (intmax_t)time_uptime - io->io_hdr.start_time);
13841 		sbuf_finish(&sb);
13842 		printf("%s", sbuf_data(&sb));
13843 	}
13844 #endif /* CTL_TIME_IO */
13845 
13846 	switch (io->io_hdr.io_type) {
13847 	case CTL_IO_SCSI:
13848 	case CTL_IO_NVME:
13849 	case CTL_IO_NVME_ADMIN:
13850 		break;
13851 	case CTL_IO_TASK:
13852 		if (ctl_debug & CTL_DEBUG_INFO)
13853 			ctl_io_error_print(io, NULL);
13854 		fe_done(io);
13855 		return;
13856 	default:
13857 		panic("%s: Invalid CTL I/O type %d\n",
13858 		    __func__, io->io_hdr.io_type);
13859 	}
13860 
13861 	if (lun == NULL) {
13862 		CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13863 				 io->io_hdr.nexus.targ_mapped_lun));
13864 		goto bailout;
13865 	}
13866 
13867 	mtx_lock(&lun->lun_lock);
13868 
13869 	/*
13870 	 * Check to see if we have any informational exception and status
13871 	 * of this command can be modified to report it in form of either
13872 	 * RECOVERED ERROR or NO SENSE, depending on MRIE mode page field.
13873 	 */
13874 	if (lun->ie_reported == 0 && lun->ie_asc != 0 &&
13875 	    io->io_hdr.status == CTL_SUCCESS &&
13876 	    (io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0) {
13877 		uint8_t mrie = lun->MODE_IE.mrie;
13878 		uint8_t per = ((lun->MODE_RWER.byte3 & SMS_RWER_PER) ||
13879 		    (lun->MODE_VER.byte3 & SMS_VER_PER));
13880 
13881 		CTL_IO_ASSERT(io, SCSI);
13882 		if (((mrie == SIEP_MRIE_REC_COND && per) ||
13883 		     mrie == SIEP_MRIE_REC_UNCOND ||
13884 		     mrie == SIEP_MRIE_NO_SENSE) &&
13885 		    (ctl_get_cmd_entry(&io->scsiio, NULL)->flags &
13886 		     CTL_CMD_FLAG_NO_SENSE) == 0) {
13887 			ctl_set_sense(&io->scsiio,
13888 			      /*current_error*/ 1,
13889 			      /*sense_key*/ (mrie == SIEP_MRIE_NO_SENSE) ?
13890 			        SSD_KEY_NO_SENSE : SSD_KEY_RECOVERED_ERROR,
13891 			      /*asc*/ lun->ie_asc,
13892 			      /*ascq*/ lun->ie_ascq,
13893 			      SSD_ELEM_NONE);
13894 			lun->ie_reported = 1;
13895 		}
13896 	} else if (lun->ie_reported < 0)
13897 		lun->ie_reported = 0;
13898 
13899 	/*
13900 	 * Check to see if we have any errors to inject here.  We only
13901 	 * inject errors for commands that don't already have errors set.
13902 	 */
13903 	if (!STAILQ_EMPTY(&lun->error_list) &&
13904 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS) &&
13905 	    ((io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0))
13906 		ctl_inject_error(lun, io);
13907 
13908 	/*
13909 	 * XXX KDM how do we treat commands that aren't completed
13910 	 * successfully?
13911 	 *
13912 	 * XXX KDM should we also track I/O latency?
13913 	 */
13914 	if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13915 	    (io->io_hdr.io_type == CTL_IO_SCSI ||
13916 	    io->io_hdr.io_type == CTL_IO_NVME ||
13917 	    io->io_hdr.io_type == CTL_IO_NVME_ADMIN)) {
13918 		int type;
13919 #ifdef CTL_TIME_IO
13920 		struct bintime bt;
13921 
13922 		getbinuptime(&bt);
13923 		bintime_sub(&bt, &io->io_hdr.start_bt);
13924 #endif
13925 		if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13926 		    CTL_FLAG_DATA_IN)
13927 			type = CTL_STATS_READ;
13928 		else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13929 		    CTL_FLAG_DATA_OUT)
13930 			type = CTL_STATS_WRITE;
13931 		else
13932 			type = CTL_STATS_NO_IO;
13933 
13934 		lun->stats.bytes[type] += ctl_kern_total_len(io);
13935 		lun->stats.operations[type] ++;
13936 		lun->stats.dmas[type] += io->io_hdr.num_dmas;
13937 #ifdef CTL_TIME_IO
13938 		bintime_add(&lun->stats.dma_time[type], &io->io_hdr.dma_bt);
13939 		bintime_add(&lun->stats.time[type], &bt);
13940 #endif
13941 
13942 		mtx_lock(&port->port_lock);
13943 		port->stats.bytes[type] += ctl_kern_total_len(io);
13944 		port->stats.operations[type] ++;
13945 		port->stats.dmas[type] += io->io_hdr.num_dmas;
13946 #ifdef CTL_TIME_IO
13947 		bintime_add(&port->stats.dma_time[type], &io->io_hdr.dma_bt);
13948 		bintime_add(&port->stats.time[type], &bt);
13949 #endif
13950 		mtx_unlock(&port->port_lock);
13951 	}
13952 
13953 	/*
13954 	 * Run through the blocked queue of this I/O and see if anything
13955 	 * can be unblocked, now that this I/O is done and will be removed.
13956 	 * We need to do it before removal to have OOA position to start.
13957 	 */
13958 	ctl_try_unblock_others(lun, io, TRUE);
13959 
13960 	/*
13961 	 * Remove this from the OOA queue.
13962 	 */
13963 	LIST_REMOVE(&io->io_hdr, ooa_links);
13964 #ifdef CTL_TIME_IO
13965 	if (LIST_EMPTY(&lun->ooa_queue))
13966 		lun->last_busy = getsbinuptime();
13967 #endif
13968 
13969 	/*
13970 	 * If the LUN has been invalidated, free it if there is nothing
13971 	 * left on its OOA queue.
13972 	 */
13973 	if ((lun->flags & CTL_LUN_INVALID)
13974 	 && LIST_EMPTY(&lun->ooa_queue)) {
13975 		mtx_unlock(&lun->lun_lock);
13976 		ctl_free_lun(lun);
13977 	} else
13978 		mtx_unlock(&lun->lun_lock);
13979 
13980 bailout:
13981 
13982 	/*
13983 	 * If this command has been aborted, make sure we set the status
13984 	 * properly.  The FETD is responsible for freeing the I/O and doing
13985 	 * whatever it needs to do to clean up its state.
13986 	 */
13987 	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
13988 		switch (io->io_hdr.io_type) {
13989 		case CTL_IO_SCSI:
13990 			ctl_set_task_aborted(&io->scsiio);
13991 			break;
13992 		case CTL_IO_NVME:
13993 		case CTL_IO_NVME_ADMIN:
13994 			ctl_nvme_set_command_aborted(&io->nvmeio);
13995 			break;
13996 		default:
13997 			__assert_unreachable();
13998 		}
13999 	}
14000 
14001 	/*
14002 	 * If enabled, print command error status.
14003 	 */
14004 	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS &&
14005 	    (ctl_debug & CTL_DEBUG_INFO) != 0)
14006 		ctl_io_error_print(io, NULL);
14007 
14008 	/*
14009 	 * Tell the FETD or the other shelf controller we're done with this
14010 	 * command.  Note that only SCSI commands get to this point.  Task
14011 	 * management commands are completed above.
14012 	 */
14013 	if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
14014 	    (io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)) {
14015 		memset(&msg, 0, sizeof(msg));
14016 		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
14017 		msg.hdr.serializing_sc = io->io_hdr.remote_io;
14018 		msg.hdr.nexus = io->io_hdr.nexus;
14019 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
14020 		    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data),
14021 		    M_WAITOK);
14022 	}
14023 
14024 	fe_done(io);
14025 }
14026 
14027 /*
14028  * Front end should call this if it doesn't do autosense.  When the request
14029  * sense comes back in from the initiator, we'll dequeue this and send it.
14030  */
14031 int
14032 ctl_queue_sense(union ctl_io *io)
14033 {
14034 	struct ctl_softc *softc = CTL_SOFTC(io);
14035 	struct ctl_port *port = CTL_PORT(io);
14036 	struct ctl_lun *lun;
14037 	struct scsi_sense_data *ps;
14038 	uint32_t initidx, p, targ_lun;
14039 
14040 	CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
14041 	CTL_IO_ASSERT(io, SCSI);
14042 
14043 	targ_lun = ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
14044 
14045 	/*
14046 	 * LUN lookup will likely move to the ctl_work_thread() once we
14047 	 * have our new queueing infrastructure (that doesn't put things on
14048 	 * a per-LUN queue initially).  That is so that we can handle
14049 	 * things like an INQUIRY to a LUN that we don't have enabled.  We
14050 	 * can't deal with that right now.
14051 	 * If we don't have a LUN for this, just toss the sense information.
14052 	 */
14053 	mtx_lock(&softc->ctl_lock);
14054 	if (targ_lun >= ctl_max_luns ||
14055 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
14056 		mtx_unlock(&softc->ctl_lock);
14057 		goto bailout;
14058 	}
14059 	mtx_lock(&lun->lun_lock);
14060 	mtx_unlock(&softc->ctl_lock);
14061 
14062 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
14063 	p = initidx / CTL_MAX_INIT_PER_PORT;
14064 	if (lun->pending_sense[p] == NULL) {
14065 		lun->pending_sense[p] = malloc(sizeof(*ps) * CTL_MAX_INIT_PER_PORT,
14066 		    M_CTL, M_NOWAIT | M_ZERO);
14067 	}
14068 	if ((ps = lun->pending_sense[p]) != NULL) {
14069 		ps += initidx % CTL_MAX_INIT_PER_PORT;
14070 		memset(ps, 0, sizeof(*ps));
14071 		memcpy(ps, &io->scsiio.sense_data, io->scsiio.sense_len);
14072 	}
14073 	mtx_unlock(&lun->lun_lock);
14074 
14075 bailout:
14076 	ctl_free_io(io);
14077 	return (CTL_RETVAL_COMPLETE);
14078 }
14079 
14080 /*
14081  * Primary command inlet from frontend ports.  All SCSI and task I/O
14082  * requests must go through this function.
14083  */
14084 int
14085 ctl_queue(union ctl_io *io)
14086 {
14087 	struct ctl_port *port = CTL_PORT(io);
14088 
14089 	switch (io->io_hdr.io_type) {
14090 	case CTL_IO_SCSI:
14091 	case CTL_IO_TASK:
14092 		CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
14093 		break;
14094 	case CTL_IO_NVME:
14095 		CTL_DEBUG_PRINT(("ctl_queue nvme nvm cmd=%02X\n",
14096 		    io->nvmeio.cmd.opc));
14097 		break;
14098 	case CTL_IO_NVME_ADMIN:
14099 		CTL_DEBUG_PRINT(("ctl_queue nvme admin cmd=%02X\n",
14100 		    io->nvmeio.cmd.opc));
14101 		break;
14102 	default:
14103 		break;
14104 	}
14105 
14106 #ifdef CTL_TIME_IO
14107 	io->io_hdr.start_time = time_uptime;
14108 	getbinuptime(&io->io_hdr.start_bt);
14109 #endif /* CTL_TIME_IO */
14110 
14111 	/* Map FE-specific LUN ID into global one. */
14112 	io->io_hdr.nexus.targ_mapped_lun =
14113 	    ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
14114 
14115 	switch (io->io_hdr.io_type) {
14116 	case CTL_IO_SCSI:
14117 	case CTL_IO_TASK:
14118 	case CTL_IO_NVME:
14119 	case CTL_IO_NVME_ADMIN:
14120 		if (ctl_debug & CTL_DEBUG_CDB)
14121 			ctl_io_print(io);
14122 		ctl_enqueue_incoming(io);
14123 		break;
14124 	default:
14125 		printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
14126 		return (EINVAL);
14127 	}
14128 
14129 	return (CTL_RETVAL_COMPLETE);
14130 }
14131 
14132 int
14133 ctl_run(union ctl_io *io)
14134 {
14135 	struct ctl_port *port = CTL_PORT(io);
14136 
14137 	CTL_DEBUG_PRINT(("ctl_run cdb[0]=%02X\n", io->scsiio.cdb[0]));
14138 
14139 #ifdef CTL_TIME_IO
14140 	io->io_hdr.start_time = time_uptime;
14141 	getbinuptime(&io->io_hdr.start_bt);
14142 #endif /* CTL_TIME_IO */
14143 
14144 	/* Map FE-specific LUN ID into global one. */
14145 	io->io_hdr.nexus.targ_mapped_lun =
14146 	    ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
14147 
14148 	switch (io->io_hdr.io_type) {
14149 	case CTL_IO_SCSI:
14150 		if (ctl_debug & CTL_DEBUG_CDB)
14151 			ctl_io_print(io);
14152 		ctl_scsiio_precheck(&io->scsiio);
14153 		break;
14154 	case CTL_IO_TASK:
14155 		if (ctl_debug & CTL_DEBUG_CDB)
14156 			ctl_io_print(io);
14157 		ctl_run_task(io);
14158 		break;
14159 	case CTL_IO_NVME:
14160 	case CTL_IO_NVME_ADMIN:
14161 		if (ctl_debug & CTL_DEBUG_CDB)
14162 			ctl_io_print(io);
14163 		ctl_nvmeio_precheck(&io->nvmeio);
14164 		break;
14165 	default:
14166 		printf("ctl_run: unknown I/O type %d\n", io->io_hdr.io_type);
14167 		return (EINVAL);
14168 	}
14169 
14170 	return (CTL_RETVAL_COMPLETE);
14171 }
14172 
14173 #ifdef CTL_IO_DELAY
14174 static void
14175 ctl_done_timer_wakeup(void *arg)
14176 {
14177 	union ctl_io *io;
14178 
14179 	io = (union ctl_io *)arg;
14180 	ctl_done(io);
14181 }
14182 #endif /* CTL_IO_DELAY */
14183 
14184 void
14185 ctl_serseq_done(union ctl_io *io)
14186 {
14187 	struct ctl_lun *lun = CTL_LUN(io);
14188 
14189 	/* This is racy, but should not be a problem. */
14190 	if (!TAILQ_EMPTY(&io->io_hdr.blocked_queue)) {
14191 		mtx_lock(&lun->lun_lock);
14192 		io->io_hdr.flags |= CTL_FLAG_SERSEQ_DONE;
14193 		ctl_try_unblock_others(lun, io, FALSE);
14194 		mtx_unlock(&lun->lun_lock);
14195 	} else
14196 		io->io_hdr.flags |= CTL_FLAG_SERSEQ_DONE;
14197 }
14198 
14199 void
14200 ctl_done(union ctl_io *io)
14201 {
14202 
14203 	/*
14204 	 * Enable this to catch duplicate completion issues.
14205 	 */
14206 #if 0
14207 	if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
14208 		switch (io->io_hdr.io_type) {
14209 		case CTL_IO_SCSI:
14210 		case CTL_IO_TASK:
14211 			printf("%s: type %d msg %d cdb %x iptl: "
14212 			    "%u:%u:%u tag 0x%04lx "
14213 			    "flag %#x status %x\n",
14214 			    __func__,
14215 			    io->io_hdr.io_type,
14216 			    io->io_hdr.msg_type,
14217 			    io->scsiio.cdb[0],
14218 			    io->io_hdr.nexus.initid,
14219 			    io->io_hdr.nexus.targ_port,
14220 			    io->io_hdr.nexus.targ_lun,
14221 			    (io->io_hdr.io_type == CTL_IO_TASK) ?
14222 			    io->taskio.tag_num :
14223 			    io->scsiio.tag_num,
14224 			    io->io_hdr.flags,
14225 			    io->io_hdr.status);
14226 			break;
14227 		case CTL_IO_NVME:
14228 		case CTL_IO_NVME_ADMIN:
14229 			printf("%s: type %d msg %d opc %x iptl: "
14230 			    "%u:%u:%u cid 0x%04x "
14231 			    "flag %#x status %x\n",
14232 			    __func__,
14233 			    io->io_hdr.io_type,
14234 			    io->io_hdr.msg_type,
14235 			    io->nvmeio.cmd.opc,
14236 			    io->io_hdr.nexus.initid,
14237 			    io->io_hdr.nexus.targ_port,
14238 			    io->io_hdr.nexus.targ_lun,
14239 			    io->nvmeio.cmd.cid,
14240 			    io->io_hdr.flags,
14241 			    io->io_hdr.status);
14242 			break;
14243 		default:
14244 			printf("%s: type %d msg %d iptl: "
14245 			    "%u:%u:%u flag %#x status %x\n",
14246 			    __func__,
14247 			    io->io_hdr.io_type,
14248 			    io->io_hdr.msg_type,
14249 			    io->io_hdr.nexus.initid,
14250 			    io->io_hdr.nexus.targ_port,
14251 			    io->io_hdr.nexus.targ_lun,
14252 			    io->io_hdr.flags,
14253 			    io->io_hdr.status);
14254 			break;
14255 		}
14256 	} else
14257 		io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
14258 #endif
14259 
14260 	/*
14261 	 * This is an internal copy of an I/O, and should not go through
14262 	 * the normal done processing logic.
14263 	 */
14264 	if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
14265 		return;
14266 
14267 #ifdef CTL_IO_DELAY
14268 	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
14269 		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
14270 	} else {
14271 		struct ctl_lun *lun = CTL_LUN(io);
14272 
14273 		if ((lun != NULL)
14274 		 && (lun->delay_info.done_delay > 0)) {
14275 			callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
14276 			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
14277 			callout_reset(&io->io_hdr.delay_callout,
14278 				      lun->delay_info.done_delay * hz,
14279 				      ctl_done_timer_wakeup, io);
14280 			if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
14281 				lun->delay_info.done_delay = 0;
14282 			return;
14283 		}
14284 	}
14285 #endif /* CTL_IO_DELAY */
14286 
14287 	ctl_enqueue_done(io);
14288 }
14289 
14290 static void
14291 ctl_work_thread(void *arg)
14292 {
14293 	struct ctl_thread *thr = (struct ctl_thread *)arg;
14294 	struct ctl_softc *softc = thr->ctl_softc;
14295 	union ctl_io *io;
14296 	int retval;
14297 
14298 	CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
14299 	thread_lock(curthread);
14300 	sched_prio(curthread, PUSER - 1);
14301 	thread_unlock(curthread);
14302 
14303 	while (!softc->shutdown) {
14304 		/*
14305 		 * We handle the queues in this order:
14306 		 * - ISC
14307 		 * - done queue (to free up resources, unblock other commands)
14308 		 * - incoming queue
14309 		 * - RtR queue
14310 		 *
14311 		 * If those queues are empty, we break out of the loop and
14312 		 * go to sleep.
14313 		 */
14314 		mtx_lock(&thr->queue_lock);
14315 		io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
14316 		if (io != NULL) {
14317 			STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
14318 			mtx_unlock(&thr->queue_lock);
14319 			ctl_handle_isc(io);
14320 			continue;
14321 		}
14322 		io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
14323 		if (io != NULL) {
14324 			STAILQ_REMOVE_HEAD(&thr->done_queue, links);
14325 			/* clear any blocked commands, call fe_done */
14326 			mtx_unlock(&thr->queue_lock);
14327 			ctl_process_done(io);
14328 			continue;
14329 		}
14330 		io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
14331 		if (io != NULL) {
14332 			STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
14333 			mtx_unlock(&thr->queue_lock);
14334 			switch (io->io_hdr.io_type) {
14335 			case CTL_IO_TASK:
14336 				ctl_run_task(io);
14337 				break;
14338 			case CTL_IO_SCSI:
14339 				ctl_scsiio_precheck(&io->scsiio);
14340 				break;
14341 			case CTL_IO_NVME:
14342 			case CTL_IO_NVME_ADMIN:
14343 				ctl_nvmeio_precheck(&io->nvmeio);
14344 				break;
14345 			default:
14346 				__assert_unreachable();
14347 			}
14348 			continue;
14349 		}
14350 		io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
14351 		if (io != NULL) {
14352 			STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
14353 			mtx_unlock(&thr->queue_lock);
14354 			switch (io->io_hdr.io_type) {
14355 			case CTL_IO_SCSI:
14356 				retval = ctl_scsiio(&io->scsiio);
14357 				if (retval != CTL_RETVAL_COMPLETE)
14358 					CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
14359 				break;
14360 			case CTL_IO_NVME:
14361 			case CTL_IO_NVME_ADMIN:
14362 				retval = ctl_nvmeio(&io->nvmeio);
14363 				if (retval != CTL_RETVAL_COMPLETE)
14364 					CTL_DEBUG_PRINT(("ctl_nvmeio failed\n"));
14365 				break;
14366 			default:
14367 				__assert_unreachable();
14368 			}
14369 			continue;
14370 		}
14371 
14372 		/* Sleep until we have something to do. */
14373 		mtx_sleep(thr, &thr->queue_lock, PDROP, "-", 0);
14374 	}
14375 	thr->thread = NULL;
14376 	kthread_exit();
14377 }
14378 
14379 static void
14380 ctl_thresh_thread(void *arg)
14381 {
14382 	struct ctl_softc *softc = (struct ctl_softc *)arg;
14383 	struct ctl_lun *lun;
14384 	struct ctl_logical_block_provisioning_page *page;
14385 	const char *attr;
14386 	union ctl_ha_msg msg;
14387 	uint64_t thres, val;
14388 	int i, e, set;
14389 
14390 	CTL_DEBUG_PRINT(("ctl_thresh_thread starting\n"));
14391 	thread_lock(curthread);
14392 	sched_prio(curthread, PUSER - 1);
14393 	thread_unlock(curthread);
14394 
14395 	while (!softc->shutdown) {
14396 		mtx_lock(&softc->ctl_lock);
14397 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
14398 			if ((lun->flags & CTL_LUN_DISABLED) ||
14399 			    (lun->flags & CTL_LUN_NO_MEDIA) ||
14400 			    lun->backend->lun_attr == NULL)
14401 				continue;
14402 			if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
14403 			    softc->ha_mode == CTL_HA_MODE_XFER)
14404 				continue;
14405 			if ((lun->MODE_RWER.byte8 & SMS_RWER_LBPERE) == 0)
14406 				continue;
14407 			e = 0;
14408 			page = &lun->MODE_LBP;
14409 			for (i = 0; i < CTL_NUM_LBP_THRESH; i++) {
14410 				if ((page->descr[i].flags & SLBPPD_ENABLED) == 0)
14411 					continue;
14412 				thres = scsi_4btoul(page->descr[i].count);
14413 				thres <<= CTL_LBP_EXPONENT;
14414 				switch (page->descr[i].resource) {
14415 				case 0x01:
14416 					attr = "blocksavail";
14417 					break;
14418 				case 0x02:
14419 					attr = "blocksused";
14420 					break;
14421 				case 0xf1:
14422 					attr = "poolblocksavail";
14423 					break;
14424 				case 0xf2:
14425 					attr = "poolblocksused";
14426 					break;
14427 				default:
14428 					continue;
14429 				}
14430 				mtx_unlock(&softc->ctl_lock); // XXX
14431 				val = lun->backend->lun_attr(lun->be_lun, attr);
14432 				mtx_lock(&softc->ctl_lock);
14433 				if (val == UINT64_MAX)
14434 					continue;
14435 				if ((page->descr[i].flags & SLBPPD_ARMING_MASK)
14436 				    == SLBPPD_ARMING_INC)
14437 					e = (val >= thres);
14438 				else
14439 					e = (val <= thres);
14440 				if (e)
14441 					break;
14442 			}
14443 			mtx_lock(&lun->lun_lock);
14444 			if (e) {
14445 				scsi_u64to8b((uint8_t *)&page->descr[i] -
14446 				    (uint8_t *)page, lun->ua_tpt_info);
14447 				if (lun->lasttpt == 0 ||
14448 				    time_uptime - lun->lasttpt >= CTL_LBP_UA_PERIOD) {
14449 					lun->lasttpt = time_uptime;
14450 					ctl_est_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
14451 					set = 1;
14452 				} else
14453 					set = 0;
14454 			} else {
14455 				lun->lasttpt = 0;
14456 				ctl_clr_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
14457 				set = -1;
14458 			}
14459 			mtx_unlock(&lun->lun_lock);
14460 			if (set != 0 &&
14461 			    lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
14462 				/* Send msg to other side. */
14463 				bzero(&msg.ua, sizeof(msg.ua));
14464 				msg.hdr.msg_type = CTL_MSG_UA;
14465 				msg.hdr.nexus.initid = -1;
14466 				msg.hdr.nexus.targ_port = -1;
14467 				msg.hdr.nexus.targ_lun = lun->lun;
14468 				msg.hdr.nexus.targ_mapped_lun = lun->lun;
14469 				msg.ua.ua_all = 1;
14470 				msg.ua.ua_set = (set > 0);
14471 				msg.ua.ua_type = CTL_UA_THIN_PROV_THRES;
14472 				memcpy(msg.ua.ua_info, lun->ua_tpt_info, 8);
14473 				mtx_unlock(&softc->ctl_lock); // XXX
14474 				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
14475 				    sizeof(msg.ua), M_WAITOK);
14476 				mtx_lock(&softc->ctl_lock);
14477 			}
14478 		}
14479 		mtx_sleep(&softc->thresh_thread, &softc->ctl_lock,
14480 		    PDROP, "-", CTL_LBP_PERIOD * hz);
14481 	}
14482 	softc->thresh_thread = NULL;
14483 	kthread_exit();
14484 }
14485 
14486 static void
14487 ctl_enqueue_incoming(union ctl_io *io)
14488 {
14489 	struct ctl_softc *softc = CTL_SOFTC(io);
14490 	struct ctl_thread *thr;
14491 	u_int idx;
14492 
14493 	idx = (io->io_hdr.nexus.targ_port * 127 +
14494 	       io->io_hdr.nexus.initid) % worker_threads;
14495 	thr = &softc->threads[idx];
14496 	mtx_lock(&thr->queue_lock);
14497 	STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
14498 	mtx_unlock(&thr->queue_lock);
14499 	wakeup(thr);
14500 }
14501 
14502 static void
14503 ctl_enqueue_rtr(union ctl_io *io)
14504 {
14505 	struct ctl_softc *softc = CTL_SOFTC(io);
14506 	struct ctl_thread *thr;
14507 
14508 	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14509 	mtx_lock(&thr->queue_lock);
14510 	STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
14511 	mtx_unlock(&thr->queue_lock);
14512 	wakeup(thr);
14513 }
14514 
14515 static void
14516 ctl_enqueue_done(union ctl_io *io)
14517 {
14518 	struct ctl_softc *softc = CTL_SOFTC(io);
14519 	struct ctl_thread *thr;
14520 
14521 	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14522 	mtx_lock(&thr->queue_lock);
14523 	STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
14524 	mtx_unlock(&thr->queue_lock);
14525 	wakeup(thr);
14526 }
14527 
14528 static void
14529 ctl_enqueue_isc(union ctl_io *io)
14530 {
14531 	struct ctl_softc *softc = CTL_SOFTC(io);
14532 	struct ctl_thread *thr;
14533 
14534 	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14535 	mtx_lock(&thr->queue_lock);
14536 	STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
14537 	mtx_unlock(&thr->queue_lock);
14538 	wakeup(thr);
14539 }
14540 
14541 /*
14542  *  vim: ts=8
14543  */
14544