xref: /freebsd/sys/cam/ctl/ctl.c (revision 6be3386466ab79a84b48429ae66244f21526d3df)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
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/cdefs.h>
48 __FBSDID("$FreeBSD$");
49 
50 #include <sys/param.h>
51 #include <sys/systm.h>
52 #include <sys/ctype.h>
53 #include <sys/kernel.h>
54 #include <sys/types.h>
55 #include <sys/kthread.h>
56 #include <sys/bio.h>
57 #include <sys/fcntl.h>
58 #include <sys/lock.h>
59 #include <sys/module.h>
60 #include <sys/mutex.h>
61 #include <sys/condvar.h>
62 #include <sys/malloc.h>
63 #include <sys/conf.h>
64 #include <sys/ioccom.h>
65 #include <sys/queue.h>
66 #include <sys/sbuf.h>
67 #include <sys/smp.h>
68 #include <sys/endian.h>
69 #include <sys/proc.h>
70 #include <sys/sched.h>
71 #include <sys/sysctl.h>
72 #include <sys/nv.h>
73 #include <sys/dnv.h>
74 #include <vm/uma.h>
75 
76 #include <cam/cam.h>
77 #include <cam/scsi/scsi_all.h>
78 #include <cam/scsi/scsi_cd.h>
79 #include <cam/scsi/scsi_da.h>
80 #include <cam/ctl/ctl_io.h>
81 #include <cam/ctl/ctl.h>
82 #include <cam/ctl/ctl_frontend.h>
83 #include <cam/ctl/ctl_util.h>
84 #include <cam/ctl/ctl_backend.h>
85 #include <cam/ctl/ctl_ioctl.h>
86 #include <cam/ctl/ctl_ha.h>
87 #include <cam/ctl/ctl_private.h>
88 #include <cam/ctl/ctl_debug.h>
89 #include <cam/ctl/ctl_scsi_all.h>
90 #include <cam/ctl/ctl_error.h>
91 
92 struct ctl_softc *control_softc = NULL;
93 
94 /*
95  * Template mode pages.
96  */
97 
98 /*
99  * Note that these are default values only.  The actual values will be
100  * filled in when the user does a mode sense.
101  */
102 const static struct scsi_da_rw_recovery_page rw_er_page_default = {
103 	/*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
104 	/*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
105 	/*byte3*/SMS_RWER_AWRE|SMS_RWER_ARRE,
106 	/*read_retry_count*/0,
107 	/*correction_span*/0,
108 	/*head_offset_count*/0,
109 	/*data_strobe_offset_cnt*/0,
110 	/*byte8*/SMS_RWER_LBPERE,
111 	/*write_retry_count*/0,
112 	/*reserved2*/0,
113 	/*recovery_time_limit*/{0, 0},
114 };
115 
116 const static struct scsi_da_rw_recovery_page rw_er_page_changeable = {
117 	/*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
118 	/*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
119 	/*byte3*/SMS_RWER_PER,
120 	/*read_retry_count*/0,
121 	/*correction_span*/0,
122 	/*head_offset_count*/0,
123 	/*data_strobe_offset_cnt*/0,
124 	/*byte8*/SMS_RWER_LBPERE,
125 	/*write_retry_count*/0,
126 	/*reserved2*/0,
127 	/*recovery_time_limit*/{0, 0},
128 };
129 
130 const static struct scsi_format_page format_page_default = {
131 	/*page_code*/SMS_FORMAT_DEVICE_PAGE,
132 	/*page_length*/sizeof(struct scsi_format_page) - 2,
133 	/*tracks_per_zone*/ {0, 0},
134 	/*alt_sectors_per_zone*/ {0, 0},
135 	/*alt_tracks_per_zone*/ {0, 0},
136 	/*alt_tracks_per_lun*/ {0, 0},
137 	/*sectors_per_track*/ {(CTL_DEFAULT_SECTORS_PER_TRACK >> 8) & 0xff,
138 			        CTL_DEFAULT_SECTORS_PER_TRACK & 0xff},
139 	/*bytes_per_sector*/ {0, 0},
140 	/*interleave*/ {0, 0},
141 	/*track_skew*/ {0, 0},
142 	/*cylinder_skew*/ {0, 0},
143 	/*flags*/ SFP_HSEC,
144 	/*reserved*/ {0, 0, 0}
145 };
146 
147 const static struct scsi_format_page format_page_changeable = {
148 	/*page_code*/SMS_FORMAT_DEVICE_PAGE,
149 	/*page_length*/sizeof(struct scsi_format_page) - 2,
150 	/*tracks_per_zone*/ {0, 0},
151 	/*alt_sectors_per_zone*/ {0, 0},
152 	/*alt_tracks_per_zone*/ {0, 0},
153 	/*alt_tracks_per_lun*/ {0, 0},
154 	/*sectors_per_track*/ {0, 0},
155 	/*bytes_per_sector*/ {0, 0},
156 	/*interleave*/ {0, 0},
157 	/*track_skew*/ {0, 0},
158 	/*cylinder_skew*/ {0, 0},
159 	/*flags*/ 0,
160 	/*reserved*/ {0, 0, 0}
161 };
162 
163 const static struct scsi_rigid_disk_page rigid_disk_page_default = {
164 	/*page_code*/SMS_RIGID_DISK_PAGE,
165 	/*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
166 	/*cylinders*/ {0, 0, 0},
167 	/*heads*/ CTL_DEFAULT_HEADS,
168 	/*start_write_precomp*/ {0, 0, 0},
169 	/*start_reduced_current*/ {0, 0, 0},
170 	/*step_rate*/ {0, 0},
171 	/*landing_zone_cylinder*/ {0, 0, 0},
172 	/*rpl*/ SRDP_RPL_DISABLED,
173 	/*rotational_offset*/ 0,
174 	/*reserved1*/ 0,
175 	/*rotation_rate*/ {(CTL_DEFAULT_ROTATION_RATE >> 8) & 0xff,
176 			   CTL_DEFAULT_ROTATION_RATE & 0xff},
177 	/*reserved2*/ {0, 0}
178 };
179 
180 const static struct scsi_rigid_disk_page rigid_disk_page_changeable = {
181 	/*page_code*/SMS_RIGID_DISK_PAGE,
182 	/*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
183 	/*cylinders*/ {0, 0, 0},
184 	/*heads*/ 0,
185 	/*start_write_precomp*/ {0, 0, 0},
186 	/*start_reduced_current*/ {0, 0, 0},
187 	/*step_rate*/ {0, 0},
188 	/*landing_zone_cylinder*/ {0, 0, 0},
189 	/*rpl*/ 0,
190 	/*rotational_offset*/ 0,
191 	/*reserved1*/ 0,
192 	/*rotation_rate*/ {0, 0},
193 	/*reserved2*/ {0, 0}
194 };
195 
196 const static struct scsi_da_verify_recovery_page verify_er_page_default = {
197 	/*page_code*/SMS_VERIFY_ERROR_RECOVERY_PAGE,
198 	/*page_length*/sizeof(struct scsi_da_verify_recovery_page) - 2,
199 	/*byte3*/0,
200 	/*read_retry_count*/0,
201 	/*reserved*/{ 0, 0, 0, 0, 0, 0 },
202 	/*recovery_time_limit*/{0, 0},
203 };
204 
205 const static struct scsi_da_verify_recovery_page verify_er_page_changeable = {
206 	/*page_code*/SMS_VERIFY_ERROR_RECOVERY_PAGE,
207 	/*page_length*/sizeof(struct scsi_da_verify_recovery_page) - 2,
208 	/*byte3*/SMS_VER_PER,
209 	/*read_retry_count*/0,
210 	/*reserved*/{ 0, 0, 0, 0, 0, 0 },
211 	/*recovery_time_limit*/{0, 0},
212 };
213 
214 const static struct scsi_caching_page caching_page_default = {
215 	/*page_code*/SMS_CACHING_PAGE,
216 	/*page_length*/sizeof(struct scsi_caching_page) - 2,
217 	/*flags1*/ SCP_DISC | SCP_WCE,
218 	/*ret_priority*/ 0,
219 	/*disable_pf_transfer_len*/ {0xff, 0xff},
220 	/*min_prefetch*/ {0, 0},
221 	/*max_prefetch*/ {0xff, 0xff},
222 	/*max_pf_ceiling*/ {0xff, 0xff},
223 	/*flags2*/ 0,
224 	/*cache_segments*/ 0,
225 	/*cache_seg_size*/ {0, 0},
226 	/*reserved*/ 0,
227 	/*non_cache_seg_size*/ {0, 0, 0}
228 };
229 
230 const static struct scsi_caching_page caching_page_changeable = {
231 	/*page_code*/SMS_CACHING_PAGE,
232 	/*page_length*/sizeof(struct scsi_caching_page) - 2,
233 	/*flags1*/ SCP_WCE | SCP_RCD,
234 	/*ret_priority*/ 0,
235 	/*disable_pf_transfer_len*/ {0, 0},
236 	/*min_prefetch*/ {0, 0},
237 	/*max_prefetch*/ {0, 0},
238 	/*max_pf_ceiling*/ {0, 0},
239 	/*flags2*/ 0,
240 	/*cache_segments*/ 0,
241 	/*cache_seg_size*/ {0, 0},
242 	/*reserved*/ 0,
243 	/*non_cache_seg_size*/ {0, 0, 0}
244 };
245 
246 const static struct scsi_control_page control_page_default = {
247 	/*page_code*/SMS_CONTROL_MODE_PAGE,
248 	/*page_length*/sizeof(struct scsi_control_page) - 2,
249 	/*rlec*/0,
250 	/*queue_flags*/SCP_QUEUE_ALG_RESTRICTED,
251 	/*eca_and_aen*/0,
252 	/*flags4*/SCP_TAS,
253 	/*aen_holdoff_period*/{0, 0},
254 	/*busy_timeout_period*/{0, 0},
255 	/*extended_selftest_completion_time*/{0, 0}
256 };
257 
258 const static struct scsi_control_page control_page_changeable = {
259 	/*page_code*/SMS_CONTROL_MODE_PAGE,
260 	/*page_length*/sizeof(struct scsi_control_page) - 2,
261 	/*rlec*/SCP_DSENSE,
262 	/*queue_flags*/SCP_QUEUE_ALG_MASK | SCP_NUAR,
263 	/*eca_and_aen*/SCP_SWP,
264 	/*flags4*/0,
265 	/*aen_holdoff_period*/{0, 0},
266 	/*busy_timeout_period*/{0, 0},
267 	/*extended_selftest_completion_time*/{0, 0}
268 };
269 
270 #define CTL_CEM_LEN	(sizeof(struct scsi_control_ext_page) - 4)
271 
272 const static struct scsi_control_ext_page control_ext_page_default = {
273 	/*page_code*/SMS_CONTROL_MODE_PAGE | SMPH_SPF,
274 	/*subpage_code*/0x01,
275 	/*page_length*/{CTL_CEM_LEN >> 8, CTL_CEM_LEN},
276 	/*flags*/0,
277 	/*prio*/0,
278 	/*max_sense*/0
279 };
280 
281 const static struct scsi_control_ext_page control_ext_page_changeable = {
282 	/*page_code*/SMS_CONTROL_MODE_PAGE | SMPH_SPF,
283 	/*subpage_code*/0x01,
284 	/*page_length*/{CTL_CEM_LEN >> 8, CTL_CEM_LEN},
285 	/*flags*/0,
286 	/*prio*/0,
287 	/*max_sense*/0xff
288 };
289 
290 const static struct scsi_info_exceptions_page ie_page_default = {
291 	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
292 	/*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
293 	/*info_flags*/SIEP_FLAGS_EWASC,
294 	/*mrie*/SIEP_MRIE_NO,
295 	/*interval_timer*/{0, 0, 0, 0},
296 	/*report_count*/{0, 0, 0, 1}
297 };
298 
299 const static struct scsi_info_exceptions_page ie_page_changeable = {
300 	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
301 	/*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
302 	/*info_flags*/SIEP_FLAGS_EWASC | SIEP_FLAGS_DEXCPT | SIEP_FLAGS_TEST |
303 	    SIEP_FLAGS_LOGERR,
304 	/*mrie*/0x0f,
305 	/*interval_timer*/{0xff, 0xff, 0xff, 0xff},
306 	/*report_count*/{0xff, 0xff, 0xff, 0xff}
307 };
308 
309 #define CTL_LBPM_LEN	(sizeof(struct ctl_logical_block_provisioning_page) - 4)
310 
311 const static struct ctl_logical_block_provisioning_page lbp_page_default = {{
312 	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
313 	/*subpage_code*/0x02,
314 	/*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
315 	/*flags*/0,
316 	/*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
317 	/*descr*/{}},
318 	{{/*flags*/0,
319 	  /*resource*/0x01,
320 	  /*reserved*/{0, 0},
321 	  /*count*/{0, 0, 0, 0}},
322 	 {/*flags*/0,
323 	  /*resource*/0x02,
324 	  /*reserved*/{0, 0},
325 	  /*count*/{0, 0, 0, 0}},
326 	 {/*flags*/0,
327 	  /*resource*/0xf1,
328 	  /*reserved*/{0, 0},
329 	  /*count*/{0, 0, 0, 0}},
330 	 {/*flags*/0,
331 	  /*resource*/0xf2,
332 	  /*reserved*/{0, 0},
333 	  /*count*/{0, 0, 0, 0}}
334 	}
335 };
336 
337 const static struct ctl_logical_block_provisioning_page lbp_page_changeable = {{
338 	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
339 	/*subpage_code*/0x02,
340 	/*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
341 	/*flags*/SLBPP_SITUA,
342 	/*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
343 	/*descr*/{}},
344 	{{/*flags*/0,
345 	  /*resource*/0,
346 	  /*reserved*/{0, 0},
347 	  /*count*/{0, 0, 0, 0}},
348 	 {/*flags*/0,
349 	  /*resource*/0,
350 	  /*reserved*/{0, 0},
351 	  /*count*/{0, 0, 0, 0}},
352 	 {/*flags*/0,
353 	  /*resource*/0,
354 	  /*reserved*/{0, 0},
355 	  /*count*/{0, 0, 0, 0}},
356 	 {/*flags*/0,
357 	  /*resource*/0,
358 	  /*reserved*/{0, 0},
359 	  /*count*/{0, 0, 0, 0}}
360 	}
361 };
362 
363 const static struct scsi_cddvd_capabilities_page cddvd_page_default = {
364 	/*page_code*/SMS_CDDVD_CAPS_PAGE,
365 	/*page_length*/sizeof(struct scsi_cddvd_capabilities_page) - 2,
366 	/*caps1*/0x3f,
367 	/*caps2*/0x00,
368 	/*caps3*/0xf0,
369 	/*caps4*/0x00,
370 	/*caps5*/0x29,
371 	/*caps6*/0x00,
372 	/*obsolete*/{0, 0},
373 	/*nvol_levels*/{0, 0},
374 	/*buffer_size*/{8, 0},
375 	/*obsolete2*/{0, 0},
376 	/*reserved*/0,
377 	/*digital*/0,
378 	/*obsolete3*/0,
379 	/*copy_management*/0,
380 	/*reserved2*/0,
381 	/*rotation_control*/0,
382 	/*cur_write_speed*/0,
383 	/*num_speed_descr*/0,
384 };
385 
386 const static struct scsi_cddvd_capabilities_page cddvd_page_changeable = {
387 	/*page_code*/SMS_CDDVD_CAPS_PAGE,
388 	/*page_length*/sizeof(struct scsi_cddvd_capabilities_page) - 2,
389 	/*caps1*/0,
390 	/*caps2*/0,
391 	/*caps3*/0,
392 	/*caps4*/0,
393 	/*caps5*/0,
394 	/*caps6*/0,
395 	/*obsolete*/{0, 0},
396 	/*nvol_levels*/{0, 0},
397 	/*buffer_size*/{0, 0},
398 	/*obsolete2*/{0, 0},
399 	/*reserved*/0,
400 	/*digital*/0,
401 	/*obsolete3*/0,
402 	/*copy_management*/0,
403 	/*reserved2*/0,
404 	/*rotation_control*/0,
405 	/*cur_write_speed*/0,
406 	/*num_speed_descr*/0,
407 };
408 
409 SYSCTL_NODE(_kern_cam, OID_AUTO, ctl, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
410     "CAM Target Layer");
411 static int worker_threads = -1;
412 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, worker_threads, CTLFLAG_RDTUN,
413     &worker_threads, 1, "Number of worker threads");
414 static int ctl_debug = CTL_DEBUG_NONE;
415 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, debug, CTLFLAG_RWTUN,
416     &ctl_debug, 0, "Enabled debug flags");
417 static int ctl_lun_map_size = 1024;
418 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, lun_map_size, CTLFLAG_RWTUN,
419     &ctl_lun_map_size, 0, "Size of per-port LUN map (max LUN + 1)");
420 #ifdef  CTL_TIME_IO
421 static int ctl_time_io_secs = CTL_TIME_IO_DEFAULT_SECS;
422 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, time_io_secs, CTLFLAG_RWTUN,
423     &ctl_time_io_secs, 0, "Log requests taking more seconds");
424 #endif
425 
426 /*
427  * Maximum number of LUNs we support.  MUST be a power of 2.
428  */
429 #define	CTL_DEFAULT_MAX_LUNS	1024
430 static int ctl_max_luns = CTL_DEFAULT_MAX_LUNS;
431 TUNABLE_INT("kern.cam.ctl.max_luns", &ctl_max_luns);
432 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, max_luns, CTLFLAG_RDTUN,
433     &ctl_max_luns, CTL_DEFAULT_MAX_LUNS, "Maximum number of LUNs");
434 
435 /*
436  * Maximum number of ports registered at one time.
437  */
438 #define	CTL_DEFAULT_MAX_PORTS		256
439 static int ctl_max_ports = CTL_DEFAULT_MAX_PORTS;
440 TUNABLE_INT("kern.cam.ctl.max_ports", &ctl_max_ports);
441 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, max_ports, CTLFLAG_RDTUN,
442     &ctl_max_ports, CTL_DEFAULT_MAX_LUNS, "Maximum number of ports");
443 
444 /*
445  * Maximum number of initiators we support.
446  */
447 #define	CTL_MAX_INITIATORS	(CTL_MAX_INIT_PER_PORT * ctl_max_ports)
448 
449 /*
450  * Supported pages (0x00), Serial number (0x80), Device ID (0x83),
451  * Extended INQUIRY Data (0x86), Mode Page Policy (0x87),
452  * SCSI Ports (0x88), Third-party Copy (0x8F), SCSI Feature Sets (0x92),
453  * Block limits (0xB0), Block Device Characteristics (0xB1) and
454  * Logical Block Provisioning (0xB2)
455  */
456 #define SCSI_EVPD_NUM_SUPPORTED_PAGES	11
457 
458 static void ctl_isc_event_handler(ctl_ha_channel chanel, ctl_ha_event event,
459 				  int param);
460 static void ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest);
461 static void ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest);
462 static int ctl_init(void);
463 static int ctl_shutdown(void);
464 static int ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td);
465 static int ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td);
466 static void ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio);
467 static void ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
468 			      struct ctl_ooa *ooa_hdr,
469 			      struct ctl_ooa_entry *kern_entries);
470 static int ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
471 		     struct thread *td);
472 static int ctl_enable_lun(struct ctl_lun *lun);
473 static int ctl_disable_lun(struct ctl_lun *lun);
474 static int ctl_free_lun(struct ctl_lun *lun);
475 
476 static int ctl_do_mode_select(union ctl_io *io);
477 static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
478 			   uint64_t res_key, uint64_t sa_res_key,
479 			   uint8_t type, uint32_t residx,
480 			   struct ctl_scsiio *ctsio,
481 			   struct scsi_per_res_out *cdb,
482 			   struct scsi_per_res_out_parms* param);
483 static void ctl_pro_preempt_other(struct ctl_lun *lun,
484 				  union ctl_ha_msg *msg);
485 static void ctl_hndl_per_res_out_on_other_sc(union ctl_io *io);
486 static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
487 static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
488 static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
489 static int ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len);
490 static int ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len);
491 static int ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio,
492 					 int alloc_len);
493 static int ctl_inquiry_evpd_sfs(struct ctl_scsiio *ctsio, int alloc_len);
494 static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
495 					 int alloc_len);
496 static int ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len);
497 static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
498 static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
499 static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
500 static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len);
501 static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2,
502     bool seq);
503 static ctl_action ctl_seq_check(union ctl_io *io1, union ctl_io *io2);
504 static ctl_action ctl_check_for_blockage(struct ctl_lun *lun,
505     union ctl_io *pending_io, const uint8_t *serialize_row,
506     union ctl_io *ooa_io);
507 static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
508 				union ctl_io **starting_io);
509 static void ctl_try_unblock_io(struct ctl_lun *lun, union ctl_io *io,
510     bool skip);
511 static void ctl_try_unblock_others(struct ctl_lun *lun, union ctl_io *io,
512     bool skip);
513 static int ctl_scsiio_lun_check(struct ctl_lun *lun,
514 				const struct ctl_cmd_entry *entry,
515 				struct ctl_scsiio *ctsio);
516 static void ctl_failover_lun(union ctl_io *io);
517 static void ctl_scsiio_precheck(struct ctl_scsiio *ctsio);
518 static int ctl_scsiio(struct ctl_scsiio *ctsio);
519 
520 static int ctl_target_reset(union ctl_io *io);
521 static void ctl_do_lun_reset(struct ctl_lun *lun, uint32_t initidx,
522 			 ctl_ua_type ua_type);
523 static int ctl_lun_reset(union ctl_io *io);
524 static int ctl_abort_task(union ctl_io *io);
525 static int ctl_abort_task_set(union ctl_io *io);
526 static int ctl_query_task(union ctl_io *io, int task_set);
527 static void ctl_i_t_nexus_loss(struct ctl_softc *softc, uint32_t initidx,
528 			      ctl_ua_type ua_type);
529 static int ctl_i_t_nexus_reset(union ctl_io *io);
530 static int ctl_query_async_event(union ctl_io *io);
531 static void ctl_run_task(union ctl_io *io);
532 #ifdef CTL_IO_DELAY
533 static void ctl_datamove_timer_wakeup(void *arg);
534 static void ctl_done_timer_wakeup(void *arg);
535 #endif /* CTL_IO_DELAY */
536 
537 static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
538 static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
539 static int ctl_datamove_remote_dm_write_cb(union ctl_io *io, bool samethr);
540 static void ctl_datamove_remote_write(union ctl_io *io);
541 static int ctl_datamove_remote_dm_read_cb(union ctl_io *io, bool samethr);
542 static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
543 static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
544 static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
545 				    ctl_ha_dt_cb callback);
546 static void ctl_datamove_remote_read(union ctl_io *io);
547 static void ctl_datamove_remote(union ctl_io *io);
548 static void ctl_process_done(union ctl_io *io);
549 static void ctl_thresh_thread(void *arg);
550 static void ctl_work_thread(void *arg);
551 static void ctl_enqueue_incoming(union ctl_io *io);
552 static void ctl_enqueue_rtr(union ctl_io *io);
553 static void ctl_enqueue_done(union ctl_io *io);
554 static void ctl_enqueue_isc(union ctl_io *io);
555 static const struct ctl_cmd_entry *
556     ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa);
557 static const struct ctl_cmd_entry *
558     ctl_validate_command(struct ctl_scsiio *ctsio);
559 static int ctl_cmd_applicable(uint8_t lun_type,
560     const struct ctl_cmd_entry *entry);
561 static int ctl_ha_init(void);
562 static int ctl_ha_shutdown(void);
563 
564 static uint64_t ctl_get_prkey(struct ctl_lun *lun, uint32_t residx);
565 static void ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx);
566 static void ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx);
567 static void ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key);
568 
569 /*
570  * Load the serialization table.  This isn't very pretty, but is probably
571  * the easiest way to do it.
572  */
573 #include "ctl_ser_table.c"
574 
575 /*
576  * We only need to define open, close and ioctl routines for this driver.
577  */
578 static struct cdevsw ctl_cdevsw = {
579 	.d_version =	D_VERSION,
580 	.d_flags =	0,
581 	.d_open =	ctl_open,
582 	.d_close =	ctl_close,
583 	.d_ioctl =	ctl_ioctl,
584 	.d_name =	"ctl",
585 };
586 
587 MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
588 
589 static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
590 
591 static moduledata_t ctl_moduledata = {
592 	"ctl",
593 	ctl_module_event_handler,
594 	NULL
595 };
596 
597 DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
598 MODULE_VERSION(ctl, 1);
599 
600 static struct ctl_frontend ha_frontend =
601 {
602 	.name = "ha",
603 	.init = ctl_ha_init,
604 	.shutdown = ctl_ha_shutdown,
605 };
606 
607 static int
608 ctl_ha_init(void)
609 {
610 	struct ctl_softc *softc = control_softc;
611 
612 	if (ctl_pool_create(softc, "othersc", CTL_POOL_ENTRIES_OTHER_SC,
613 	                    &softc->othersc_pool) != 0)
614 		return (ENOMEM);
615 	if (ctl_ha_msg_init(softc) != CTL_HA_STATUS_SUCCESS) {
616 		ctl_pool_free(softc->othersc_pool);
617 		return (EIO);
618 	}
619 	if (ctl_ha_msg_register(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
620 	    != CTL_HA_STATUS_SUCCESS) {
621 		ctl_ha_msg_destroy(softc);
622 		ctl_pool_free(softc->othersc_pool);
623 		return (EIO);
624 	}
625 	return (0);
626 };
627 
628 static int
629 ctl_ha_shutdown(void)
630 {
631 	struct ctl_softc *softc = control_softc;
632 	struct ctl_port *port;
633 
634 	ctl_ha_msg_shutdown(softc);
635 	if (ctl_ha_msg_deregister(CTL_HA_CHAN_CTL) != CTL_HA_STATUS_SUCCESS)
636 		return (EIO);
637 	if (ctl_ha_msg_destroy(softc) != CTL_HA_STATUS_SUCCESS)
638 		return (EIO);
639 	ctl_pool_free(softc->othersc_pool);
640 	while ((port = STAILQ_FIRST(&ha_frontend.port_list)) != NULL) {
641 		ctl_port_deregister(port);
642 		free(port->port_name, M_CTL);
643 		free(port, M_CTL);
644 	}
645 	return (0);
646 };
647 
648 static void
649 ctl_ha_datamove(union ctl_io *io)
650 {
651 	struct ctl_lun *lun = CTL_LUN(io);
652 	struct ctl_sg_entry *sgl;
653 	union ctl_ha_msg msg;
654 	uint32_t sg_entries_sent;
655 	int do_sg_copy, i, j;
656 
657 	memset(&msg.dt, 0, sizeof(msg.dt));
658 	msg.hdr.msg_type = CTL_MSG_DATAMOVE;
659 	msg.hdr.original_sc = io->io_hdr.remote_io;
660 	msg.hdr.serializing_sc = io;
661 	msg.hdr.nexus = io->io_hdr.nexus;
662 	msg.hdr.status = io->io_hdr.status;
663 	msg.dt.flags = io->io_hdr.flags;
664 
665 	/*
666 	 * We convert everything into a S/G list here.  We can't
667 	 * pass by reference, only by value between controllers.
668 	 * So we can't pass a pointer to the S/G list, only as many
669 	 * S/G entries as we can fit in here.  If it's possible for
670 	 * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
671 	 * then we need to break this up into multiple transfers.
672 	 */
673 	if (io->scsiio.kern_sg_entries == 0) {
674 		msg.dt.kern_sg_entries = 1;
675 #if 0
676 		if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
677 			msg.dt.sg_list[0].addr = io->scsiio.kern_data_ptr;
678 		} else {
679 			/* XXX KDM use busdma here! */
680 			msg.dt.sg_list[0].addr =
681 			    (void *)vtophys(io->scsiio.kern_data_ptr);
682 		}
683 #else
684 		KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
685 		    ("HA does not support BUS_ADDR"));
686 		msg.dt.sg_list[0].addr = io->scsiio.kern_data_ptr;
687 #endif
688 		msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
689 		do_sg_copy = 0;
690 	} else {
691 		msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
692 		do_sg_copy = 1;
693 	}
694 
695 	msg.dt.kern_data_len = io->scsiio.kern_data_len;
696 	msg.dt.kern_total_len = io->scsiio.kern_total_len;
697 	msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
698 	msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
699 	msg.dt.sg_sequence = 0;
700 
701 	/*
702 	 * Loop until we've sent all of the S/G entries.  On the
703 	 * other end, we'll recompose these S/G entries into one
704 	 * contiguous list before processing.
705 	 */
706 	for (sg_entries_sent = 0; sg_entries_sent < msg.dt.kern_sg_entries;
707 	    msg.dt.sg_sequence++) {
708 		msg.dt.cur_sg_entries = MIN((sizeof(msg.dt.sg_list) /
709 		    sizeof(msg.dt.sg_list[0])),
710 		    msg.dt.kern_sg_entries - sg_entries_sent);
711 		if (do_sg_copy != 0) {
712 			sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
713 			for (i = sg_entries_sent, j = 0;
714 			     i < msg.dt.cur_sg_entries; i++, j++) {
715 #if 0
716 				if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
717 					msg.dt.sg_list[j].addr = sgl[i].addr;
718 				} else {
719 					/* XXX KDM use busdma here! */
720 					msg.dt.sg_list[j].addr =
721 					    (void *)vtophys(sgl[i].addr);
722 				}
723 #else
724 				KASSERT((io->io_hdr.flags &
725 				    CTL_FLAG_BUS_ADDR) == 0,
726 				    ("HA does not support BUS_ADDR"));
727 				msg.dt.sg_list[j].addr = sgl[i].addr;
728 #endif
729 				msg.dt.sg_list[j].len = sgl[i].len;
730 			}
731 		}
732 
733 		sg_entries_sent += msg.dt.cur_sg_entries;
734 		msg.dt.sg_last = (sg_entries_sent >= msg.dt.kern_sg_entries);
735 		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
736 		    sizeof(msg.dt) - sizeof(msg.dt.sg_list) +
737 		    sizeof(struct ctl_sg_entry) * msg.dt.cur_sg_entries,
738 		    M_WAITOK) > CTL_HA_STATUS_SUCCESS) {
739 			io->io_hdr.port_status = 31341;
740 			ctl_datamove_done(io, true);
741 			return;
742 		}
743 		msg.dt.sent_sg_entries = sg_entries_sent;
744 	}
745 
746 	/*
747 	 * Officially handover the request from us to peer.
748 	 * If failover has just happened, then we must return error.
749 	 * If failover happen just after, then it is not our problem.
750 	 */
751 	if (lun)
752 		mtx_lock(&lun->lun_lock);
753 	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
754 		if (lun)
755 			mtx_unlock(&lun->lun_lock);
756 		io->io_hdr.port_status = 31342;
757 		ctl_datamove_done(io, true);
758 		return;
759 	}
760 	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
761 	io->io_hdr.flags |= CTL_FLAG_DMA_INPROG;
762 	if (lun)
763 		mtx_unlock(&lun->lun_lock);
764 }
765 
766 static void
767 ctl_ha_done(union ctl_io *io)
768 {
769 	union ctl_ha_msg msg;
770 
771 	if (io->io_hdr.io_type == CTL_IO_SCSI) {
772 		memset(&msg, 0, sizeof(msg));
773 		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
774 		msg.hdr.original_sc = io->io_hdr.remote_io;
775 		msg.hdr.nexus = io->io_hdr.nexus;
776 		msg.hdr.status = io->io_hdr.status;
777 		msg.scsi.scsi_status = io->scsiio.scsi_status;
778 		msg.scsi.tag_num = io->scsiio.tag_num;
779 		msg.scsi.tag_type = io->scsiio.tag_type;
780 		msg.scsi.sense_len = io->scsiio.sense_len;
781 		memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
782 		    io->scsiio.sense_len);
783 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
784 		    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
785 		    msg.scsi.sense_len, M_WAITOK);
786 	}
787 	ctl_free_io(io);
788 }
789 
790 static void
791 ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
792 			    union ctl_ha_msg *msg_info)
793 {
794 	struct ctl_scsiio *ctsio;
795 
796 	if (msg_info->hdr.original_sc == NULL) {
797 		printf("%s: original_sc == NULL!\n", __func__);
798 		/* XXX KDM now what? */
799 		return;
800 	}
801 
802 	ctsio = &msg_info->hdr.original_sc->scsiio;
803 	ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
804 	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
805 	ctsio->io_hdr.status = msg_info->hdr.status;
806 	ctsio->scsi_status = msg_info->scsi.scsi_status;
807 	ctsio->sense_len = msg_info->scsi.sense_len;
808 	memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
809 	       msg_info->scsi.sense_len);
810 	ctl_enqueue_isc((union ctl_io *)ctsio);
811 }
812 
813 static void
814 ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
815 				union ctl_ha_msg *msg_info)
816 {
817 	struct ctl_scsiio *ctsio;
818 
819 	if (msg_info->hdr.serializing_sc == NULL) {
820 		printf("%s: serializing_sc == NULL!\n", __func__);
821 		/* XXX KDM now what? */
822 		return;
823 	}
824 
825 	ctsio = &msg_info->hdr.serializing_sc->scsiio;
826 	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
827 	ctl_enqueue_isc((union ctl_io *)ctsio);
828 }
829 
830 void
831 ctl_isc_announce_lun(struct ctl_lun *lun)
832 {
833 	struct ctl_softc *softc = lun->ctl_softc;
834 	union ctl_ha_msg *msg;
835 	struct ctl_ha_msg_lun_pr_key pr_key;
836 	int i, k;
837 
838 	if (softc->ha_link != CTL_HA_LINK_ONLINE)
839 		return;
840 	mtx_lock(&lun->lun_lock);
841 	i = sizeof(msg->lun);
842 	if (lun->lun_devid)
843 		i += lun->lun_devid->len;
844 	i += sizeof(pr_key) * lun->pr_key_count;
845 alloc:
846 	mtx_unlock(&lun->lun_lock);
847 	msg = malloc(i, M_CTL, M_WAITOK);
848 	mtx_lock(&lun->lun_lock);
849 	k = sizeof(msg->lun);
850 	if (lun->lun_devid)
851 		k += lun->lun_devid->len;
852 	k += sizeof(pr_key) * lun->pr_key_count;
853 	if (i < k) {
854 		free(msg, M_CTL);
855 		i = k;
856 		goto alloc;
857 	}
858 	bzero(&msg->lun, sizeof(msg->lun));
859 	msg->hdr.msg_type = CTL_MSG_LUN_SYNC;
860 	msg->hdr.nexus.targ_lun = lun->lun;
861 	msg->hdr.nexus.targ_mapped_lun = lun->lun;
862 	msg->lun.flags = lun->flags;
863 	msg->lun.pr_generation = lun->pr_generation;
864 	msg->lun.pr_res_idx = lun->pr_res_idx;
865 	msg->lun.pr_res_type = lun->pr_res_type;
866 	msg->lun.pr_key_count = lun->pr_key_count;
867 	i = 0;
868 	if (lun->lun_devid) {
869 		msg->lun.lun_devid_len = lun->lun_devid->len;
870 		memcpy(&msg->lun.data[i], lun->lun_devid->data,
871 		    msg->lun.lun_devid_len);
872 		i += msg->lun.lun_devid_len;
873 	}
874 	for (k = 0; k < CTL_MAX_INITIATORS; k++) {
875 		if ((pr_key.pr_key = ctl_get_prkey(lun, k)) == 0)
876 			continue;
877 		pr_key.pr_iid = k;
878 		memcpy(&msg->lun.data[i], &pr_key, sizeof(pr_key));
879 		i += sizeof(pr_key);
880 	}
881 	mtx_unlock(&lun->lun_lock);
882 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->port, sizeof(msg->port) + i,
883 	    M_WAITOK);
884 	free(msg, M_CTL);
885 
886 	if (lun->flags & CTL_LUN_PRIMARY_SC) {
887 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
888 			ctl_isc_announce_mode(lun, -1,
889 			    lun->mode_pages.index[i].page_code & SMPH_PC_MASK,
890 			    lun->mode_pages.index[i].subpage);
891 		}
892 	}
893 }
894 
895 void
896 ctl_isc_announce_port(struct ctl_port *port)
897 {
898 	struct ctl_softc *softc = port->ctl_softc;
899 	union ctl_ha_msg *msg;
900 	int i;
901 
902 	if (port->targ_port < softc->port_min ||
903 	    port->targ_port >= softc->port_max ||
904 	    softc->ha_link != CTL_HA_LINK_ONLINE)
905 		return;
906 	i = sizeof(msg->port) + strlen(port->port_name) + 1;
907 	if (port->lun_map)
908 		i += port->lun_map_size * sizeof(uint32_t);
909 	if (port->port_devid)
910 		i += port->port_devid->len;
911 	if (port->target_devid)
912 		i += port->target_devid->len;
913 	if (port->init_devid)
914 		i += port->init_devid->len;
915 	msg = malloc(i, M_CTL, M_WAITOK);
916 	bzero(&msg->port, sizeof(msg->port));
917 	msg->hdr.msg_type = CTL_MSG_PORT_SYNC;
918 	msg->hdr.nexus.targ_port = port->targ_port;
919 	msg->port.port_type = port->port_type;
920 	msg->port.physical_port = port->physical_port;
921 	msg->port.virtual_port = port->virtual_port;
922 	msg->port.status = port->status;
923 	i = 0;
924 	msg->port.name_len = sprintf(&msg->port.data[i],
925 	    "%d:%s", softc->ha_id, port->port_name) + 1;
926 	i += msg->port.name_len;
927 	if (port->lun_map) {
928 		msg->port.lun_map_len = port->lun_map_size * sizeof(uint32_t);
929 		memcpy(&msg->port.data[i], port->lun_map,
930 		    msg->port.lun_map_len);
931 		i += msg->port.lun_map_len;
932 	}
933 	if (port->port_devid) {
934 		msg->port.port_devid_len = port->port_devid->len;
935 		memcpy(&msg->port.data[i], port->port_devid->data,
936 		    msg->port.port_devid_len);
937 		i += msg->port.port_devid_len;
938 	}
939 	if (port->target_devid) {
940 		msg->port.target_devid_len = port->target_devid->len;
941 		memcpy(&msg->port.data[i], port->target_devid->data,
942 		    msg->port.target_devid_len);
943 		i += msg->port.target_devid_len;
944 	}
945 	if (port->init_devid) {
946 		msg->port.init_devid_len = port->init_devid->len;
947 		memcpy(&msg->port.data[i], port->init_devid->data,
948 		    msg->port.init_devid_len);
949 		i += msg->port.init_devid_len;
950 	}
951 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->port, sizeof(msg->port) + i,
952 	    M_WAITOK);
953 	free(msg, M_CTL);
954 }
955 
956 void
957 ctl_isc_announce_iid(struct ctl_port *port, int iid)
958 {
959 	struct ctl_softc *softc = port->ctl_softc;
960 	union ctl_ha_msg *msg;
961 	int i, l;
962 
963 	if (port->targ_port < softc->port_min ||
964 	    port->targ_port >= softc->port_max ||
965 	    softc->ha_link != CTL_HA_LINK_ONLINE)
966 		return;
967 	mtx_lock(&softc->ctl_lock);
968 	i = sizeof(msg->iid);
969 	l = 0;
970 	if (port->wwpn_iid[iid].name)
971 		l = strlen(port->wwpn_iid[iid].name) + 1;
972 	i += l;
973 	msg = malloc(i, M_CTL, M_NOWAIT);
974 	if (msg == NULL) {
975 		mtx_unlock(&softc->ctl_lock);
976 		return;
977 	}
978 	bzero(&msg->iid, sizeof(msg->iid));
979 	msg->hdr.msg_type = CTL_MSG_IID_SYNC;
980 	msg->hdr.nexus.targ_port = port->targ_port;
981 	msg->hdr.nexus.initid = iid;
982 	msg->iid.in_use = port->wwpn_iid[iid].in_use;
983 	msg->iid.name_len = l;
984 	msg->iid.wwpn = port->wwpn_iid[iid].wwpn;
985 	if (port->wwpn_iid[iid].name)
986 		strlcpy(msg->iid.data, port->wwpn_iid[iid].name, l);
987 	mtx_unlock(&softc->ctl_lock);
988 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->iid, i, M_NOWAIT);
989 	free(msg, M_CTL);
990 }
991 
992 void
993 ctl_isc_announce_mode(struct ctl_lun *lun, uint32_t initidx,
994     uint8_t page, uint8_t subpage)
995 {
996 	struct ctl_softc *softc = lun->ctl_softc;
997 	union ctl_ha_msg msg;
998 	u_int i;
999 
1000 	if (softc->ha_link != CTL_HA_LINK_ONLINE)
1001 		return;
1002 	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
1003 		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) ==
1004 		    page && lun->mode_pages.index[i].subpage == subpage)
1005 			break;
1006 	}
1007 	if (i == CTL_NUM_MODE_PAGES)
1008 		return;
1009 
1010 	/* Don't try to replicate pages not present on this device. */
1011 	if (lun->mode_pages.index[i].page_data == NULL)
1012 		return;
1013 
1014 	bzero(&msg.mode, sizeof(msg.mode));
1015 	msg.hdr.msg_type = CTL_MSG_MODE_SYNC;
1016 	msg.hdr.nexus.targ_port = initidx / CTL_MAX_INIT_PER_PORT;
1017 	msg.hdr.nexus.initid = initidx % CTL_MAX_INIT_PER_PORT;
1018 	msg.hdr.nexus.targ_lun = lun->lun;
1019 	msg.hdr.nexus.targ_mapped_lun = lun->lun;
1020 	msg.mode.page_code = page;
1021 	msg.mode.subpage = subpage;
1022 	msg.mode.page_len = lun->mode_pages.index[i].page_len;
1023 	memcpy(msg.mode.data, lun->mode_pages.index[i].page_data,
1024 	    msg.mode.page_len);
1025 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg.mode, sizeof(msg.mode),
1026 	    M_WAITOK);
1027 }
1028 
1029 static void
1030 ctl_isc_ha_link_up(struct ctl_softc *softc)
1031 {
1032 	struct ctl_port *port;
1033 	struct ctl_lun *lun;
1034 	union ctl_ha_msg msg;
1035 	int i;
1036 
1037 	/* Announce this node parameters to peer for validation. */
1038 	msg.login.msg_type = CTL_MSG_LOGIN;
1039 	msg.login.version = CTL_HA_VERSION;
1040 	msg.login.ha_mode = softc->ha_mode;
1041 	msg.login.ha_id = softc->ha_id;
1042 	msg.login.max_luns = ctl_max_luns;
1043 	msg.login.max_ports = ctl_max_ports;
1044 	msg.login.max_init_per_port = CTL_MAX_INIT_PER_PORT;
1045 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg.login, sizeof(msg.login),
1046 	    M_WAITOK);
1047 
1048 	STAILQ_FOREACH(port, &softc->port_list, links) {
1049 		ctl_isc_announce_port(port);
1050 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1051 			if (port->wwpn_iid[i].in_use)
1052 				ctl_isc_announce_iid(port, i);
1053 		}
1054 	}
1055 	STAILQ_FOREACH(lun, &softc->lun_list, links)
1056 		ctl_isc_announce_lun(lun);
1057 }
1058 
1059 static void
1060 ctl_isc_ha_link_down(struct ctl_softc *softc)
1061 {
1062 	struct ctl_port *port;
1063 	struct ctl_lun *lun;
1064 	union ctl_io *io;
1065 	int i;
1066 
1067 	mtx_lock(&softc->ctl_lock);
1068 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
1069 		mtx_lock(&lun->lun_lock);
1070 		if (lun->flags & CTL_LUN_PEER_SC_PRIMARY) {
1071 			lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
1072 			ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
1073 		}
1074 		mtx_unlock(&lun->lun_lock);
1075 
1076 		mtx_unlock(&softc->ctl_lock);
1077 		io = ctl_alloc_io(softc->othersc_pool);
1078 		mtx_lock(&softc->ctl_lock);
1079 		ctl_zero_io(io);
1080 		io->io_hdr.msg_type = CTL_MSG_FAILOVER;
1081 		io->io_hdr.nexus.targ_mapped_lun = lun->lun;
1082 		ctl_enqueue_isc(io);
1083 	}
1084 
1085 	STAILQ_FOREACH(port, &softc->port_list, links) {
1086 		if (port->targ_port >= softc->port_min &&
1087 		    port->targ_port < softc->port_max)
1088 			continue;
1089 		port->status &= ~CTL_PORT_STATUS_ONLINE;
1090 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1091 			port->wwpn_iid[i].in_use = 0;
1092 			free(port->wwpn_iid[i].name, M_CTL);
1093 			port->wwpn_iid[i].name = NULL;
1094 		}
1095 	}
1096 	mtx_unlock(&softc->ctl_lock);
1097 }
1098 
1099 static void
1100 ctl_isc_ua(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1101 {
1102 	struct ctl_lun *lun;
1103 	uint32_t iid = ctl_get_initindex(&msg->hdr.nexus);
1104 
1105 	mtx_lock(&softc->ctl_lock);
1106 	if (msg->hdr.nexus.targ_mapped_lun >= ctl_max_luns ||
1107 	    (lun = softc->ctl_luns[msg->hdr.nexus.targ_mapped_lun]) == NULL) {
1108 		mtx_unlock(&softc->ctl_lock);
1109 		return;
1110 	}
1111 	mtx_lock(&lun->lun_lock);
1112 	mtx_unlock(&softc->ctl_lock);
1113 	if (msg->ua.ua_type == CTL_UA_THIN_PROV_THRES && msg->ua.ua_set)
1114 		memcpy(lun->ua_tpt_info, msg->ua.ua_info, 8);
1115 	if (msg->ua.ua_all) {
1116 		if (msg->ua.ua_set)
1117 			ctl_est_ua_all(lun, iid, msg->ua.ua_type);
1118 		else
1119 			ctl_clr_ua_all(lun, iid, msg->ua.ua_type);
1120 	} else {
1121 		if (msg->ua.ua_set)
1122 			ctl_est_ua(lun, iid, msg->ua.ua_type);
1123 		else
1124 			ctl_clr_ua(lun, iid, msg->ua.ua_type);
1125 	}
1126 	mtx_unlock(&lun->lun_lock);
1127 }
1128 
1129 static void
1130 ctl_isc_lun_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1131 {
1132 	struct ctl_lun *lun;
1133 	struct ctl_ha_msg_lun_pr_key pr_key;
1134 	int i, k;
1135 	ctl_lun_flags oflags;
1136 	uint32_t targ_lun;
1137 
1138 	targ_lun = msg->hdr.nexus.targ_mapped_lun;
1139 	mtx_lock(&softc->ctl_lock);
1140 	if (targ_lun >= ctl_max_luns ||
1141 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
1142 		mtx_unlock(&softc->ctl_lock);
1143 		return;
1144 	}
1145 	mtx_lock(&lun->lun_lock);
1146 	mtx_unlock(&softc->ctl_lock);
1147 	if (lun->flags & CTL_LUN_DISABLED) {
1148 		mtx_unlock(&lun->lun_lock);
1149 		return;
1150 	}
1151 	i = (lun->lun_devid != NULL) ? lun->lun_devid->len : 0;
1152 	if (msg->lun.lun_devid_len != i || (i > 0 &&
1153 	    memcmp(&msg->lun.data[0], lun->lun_devid->data, i) != 0)) {
1154 		mtx_unlock(&lun->lun_lock);
1155 		printf("%s: Received conflicting HA LUN %d\n",
1156 		    __func__, targ_lun);
1157 		return;
1158 	} else {
1159 		/* Record whether peer is primary. */
1160 		oflags = lun->flags;
1161 		if ((msg->lun.flags & CTL_LUN_PRIMARY_SC) &&
1162 		    (msg->lun.flags & CTL_LUN_DISABLED) == 0)
1163 			lun->flags |= CTL_LUN_PEER_SC_PRIMARY;
1164 		else
1165 			lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
1166 		if (oflags != lun->flags)
1167 			ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
1168 
1169 		/* If peer is primary and we are not -- use data */
1170 		if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
1171 		    (lun->flags & CTL_LUN_PEER_SC_PRIMARY)) {
1172 			lun->pr_generation = msg->lun.pr_generation;
1173 			lun->pr_res_idx = msg->lun.pr_res_idx;
1174 			lun->pr_res_type = msg->lun.pr_res_type;
1175 			lun->pr_key_count = msg->lun.pr_key_count;
1176 			for (k = 0; k < CTL_MAX_INITIATORS; k++)
1177 				ctl_clr_prkey(lun, k);
1178 			for (k = 0; k < msg->lun.pr_key_count; k++) {
1179 				memcpy(&pr_key, &msg->lun.data[i],
1180 				    sizeof(pr_key));
1181 				ctl_alloc_prkey(lun, pr_key.pr_iid);
1182 				ctl_set_prkey(lun, pr_key.pr_iid,
1183 				    pr_key.pr_key);
1184 				i += sizeof(pr_key);
1185 			}
1186 		}
1187 
1188 		mtx_unlock(&lun->lun_lock);
1189 		CTL_DEBUG_PRINT(("%s: Known LUN %d, peer is %s\n",
1190 		    __func__, targ_lun,
1191 		    (msg->lun.flags & CTL_LUN_PRIMARY_SC) ?
1192 		    "primary" : "secondary"));
1193 
1194 		/* If we are primary but peer doesn't know -- notify */
1195 		if ((lun->flags & CTL_LUN_PRIMARY_SC) &&
1196 		    (msg->lun.flags & CTL_LUN_PEER_SC_PRIMARY) == 0)
1197 			ctl_isc_announce_lun(lun);
1198 	}
1199 }
1200 
1201 static void
1202 ctl_isc_port_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1203 {
1204 	struct ctl_port *port;
1205 	struct ctl_lun *lun;
1206 	int i, new;
1207 
1208 	port = softc->ctl_ports[msg->hdr.nexus.targ_port];
1209 	if (port == NULL) {
1210 		CTL_DEBUG_PRINT(("%s: New port %d\n", __func__,
1211 		    msg->hdr.nexus.targ_port));
1212 		new = 1;
1213 		port = malloc(sizeof(*port), M_CTL, M_WAITOK | M_ZERO);
1214 		port->frontend = &ha_frontend;
1215 		port->targ_port = msg->hdr.nexus.targ_port;
1216 		port->fe_datamove = ctl_ha_datamove;
1217 		port->fe_done = ctl_ha_done;
1218 	} else if (port->frontend == &ha_frontend) {
1219 		CTL_DEBUG_PRINT(("%s: Updated port %d\n", __func__,
1220 		    msg->hdr.nexus.targ_port));
1221 		new = 0;
1222 	} else {
1223 		printf("%s: Received conflicting HA port %d\n",
1224 		    __func__, msg->hdr.nexus.targ_port);
1225 		return;
1226 	}
1227 	port->port_type = msg->port.port_type;
1228 	port->physical_port = msg->port.physical_port;
1229 	port->virtual_port = msg->port.virtual_port;
1230 	port->status = msg->port.status;
1231 	i = 0;
1232 	free(port->port_name, M_CTL);
1233 	port->port_name = strndup(&msg->port.data[i], msg->port.name_len,
1234 	    M_CTL);
1235 	i += msg->port.name_len;
1236 	if (msg->port.lun_map_len != 0) {
1237 		if (port->lun_map == NULL ||
1238 		    port->lun_map_size * sizeof(uint32_t) <
1239 		    msg->port.lun_map_len) {
1240 			port->lun_map_size = 0;
1241 			free(port->lun_map, M_CTL);
1242 			port->lun_map = malloc(msg->port.lun_map_len,
1243 			    M_CTL, M_WAITOK);
1244 		}
1245 		memcpy(port->lun_map, &msg->port.data[i], msg->port.lun_map_len);
1246 		port->lun_map_size = msg->port.lun_map_len / sizeof(uint32_t);
1247 		i += msg->port.lun_map_len;
1248 	} else {
1249 		port->lun_map_size = 0;
1250 		free(port->lun_map, M_CTL);
1251 		port->lun_map = NULL;
1252 	}
1253 	if (msg->port.port_devid_len != 0) {
1254 		if (port->port_devid == NULL ||
1255 		    port->port_devid->len < msg->port.port_devid_len) {
1256 			free(port->port_devid, M_CTL);
1257 			port->port_devid = malloc(sizeof(struct ctl_devid) +
1258 			    msg->port.port_devid_len, M_CTL, M_WAITOK);
1259 		}
1260 		memcpy(port->port_devid->data, &msg->port.data[i],
1261 		    msg->port.port_devid_len);
1262 		port->port_devid->len = msg->port.port_devid_len;
1263 		i += msg->port.port_devid_len;
1264 	} else {
1265 		free(port->port_devid, M_CTL);
1266 		port->port_devid = NULL;
1267 	}
1268 	if (msg->port.target_devid_len != 0) {
1269 		if (port->target_devid == NULL ||
1270 		    port->target_devid->len < msg->port.target_devid_len) {
1271 			free(port->target_devid, M_CTL);
1272 			port->target_devid = malloc(sizeof(struct ctl_devid) +
1273 			    msg->port.target_devid_len, M_CTL, M_WAITOK);
1274 		}
1275 		memcpy(port->target_devid->data, &msg->port.data[i],
1276 		    msg->port.target_devid_len);
1277 		port->target_devid->len = msg->port.target_devid_len;
1278 		i += msg->port.target_devid_len;
1279 	} else {
1280 		free(port->target_devid, M_CTL);
1281 		port->target_devid = NULL;
1282 	}
1283 	if (msg->port.init_devid_len != 0) {
1284 		if (port->init_devid == NULL ||
1285 		    port->init_devid->len < msg->port.init_devid_len) {
1286 			free(port->init_devid, M_CTL);
1287 			port->init_devid = malloc(sizeof(struct ctl_devid) +
1288 			    msg->port.init_devid_len, M_CTL, M_WAITOK);
1289 		}
1290 		memcpy(port->init_devid->data, &msg->port.data[i],
1291 		    msg->port.init_devid_len);
1292 		port->init_devid->len = msg->port.init_devid_len;
1293 		i += msg->port.init_devid_len;
1294 	} else {
1295 		free(port->init_devid, M_CTL);
1296 		port->init_devid = NULL;
1297 	}
1298 	if (new) {
1299 		if (ctl_port_register(port) != 0) {
1300 			printf("%s: ctl_port_register() failed with error\n",
1301 			    __func__);
1302 		}
1303 	}
1304 	mtx_lock(&softc->ctl_lock);
1305 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
1306 		if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
1307 			continue;
1308 		mtx_lock(&lun->lun_lock);
1309 		ctl_est_ua_all(lun, -1, CTL_UA_INQ_CHANGE);
1310 		mtx_unlock(&lun->lun_lock);
1311 	}
1312 	mtx_unlock(&softc->ctl_lock);
1313 }
1314 
1315 static void
1316 ctl_isc_iid_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1317 {
1318 	struct ctl_port *port;
1319 	int iid;
1320 
1321 	port = softc->ctl_ports[msg->hdr.nexus.targ_port];
1322 	if (port == NULL) {
1323 		printf("%s: Received IID for unknown port %d\n",
1324 		    __func__, msg->hdr.nexus.targ_port);
1325 		return;
1326 	}
1327 	iid = msg->hdr.nexus.initid;
1328 	if (port->wwpn_iid[iid].in_use != 0 &&
1329 	    msg->iid.in_use == 0)
1330 		ctl_i_t_nexus_loss(softc, iid, CTL_UA_POWERON);
1331 	port->wwpn_iid[iid].in_use = msg->iid.in_use;
1332 	port->wwpn_iid[iid].wwpn = msg->iid.wwpn;
1333 	free(port->wwpn_iid[iid].name, M_CTL);
1334 	if (msg->iid.name_len) {
1335 		port->wwpn_iid[iid].name = strndup(&msg->iid.data[0],
1336 		    msg->iid.name_len, M_CTL);
1337 	} else
1338 		port->wwpn_iid[iid].name = NULL;
1339 }
1340 
1341 static void
1342 ctl_isc_login(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1343 {
1344 
1345 	if (msg->login.version != CTL_HA_VERSION) {
1346 		printf("CTL HA peers have different versions %d != %d\n",
1347 		    msg->login.version, CTL_HA_VERSION);
1348 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1349 		return;
1350 	}
1351 	if (msg->login.ha_mode != softc->ha_mode) {
1352 		printf("CTL HA peers have different ha_mode %d != %d\n",
1353 		    msg->login.ha_mode, softc->ha_mode);
1354 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1355 		return;
1356 	}
1357 	if (msg->login.ha_id == softc->ha_id) {
1358 		printf("CTL HA peers have same ha_id %d\n", msg->login.ha_id);
1359 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1360 		return;
1361 	}
1362 	if (msg->login.max_luns != ctl_max_luns ||
1363 	    msg->login.max_ports != ctl_max_ports ||
1364 	    msg->login.max_init_per_port != CTL_MAX_INIT_PER_PORT) {
1365 		printf("CTL HA peers have different limits\n");
1366 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1367 		return;
1368 	}
1369 }
1370 
1371 static void
1372 ctl_isc_mode_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1373 {
1374 	struct ctl_lun *lun;
1375 	u_int i;
1376 	uint32_t initidx, targ_lun;
1377 
1378 	targ_lun = msg->hdr.nexus.targ_mapped_lun;
1379 	mtx_lock(&softc->ctl_lock);
1380 	if (targ_lun >= ctl_max_luns ||
1381 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
1382 		mtx_unlock(&softc->ctl_lock);
1383 		return;
1384 	}
1385 	mtx_lock(&lun->lun_lock);
1386 	mtx_unlock(&softc->ctl_lock);
1387 	if (lun->flags & CTL_LUN_DISABLED) {
1388 		mtx_unlock(&lun->lun_lock);
1389 		return;
1390 	}
1391 	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
1392 		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) ==
1393 		    msg->mode.page_code &&
1394 		    lun->mode_pages.index[i].subpage == msg->mode.subpage)
1395 			break;
1396 	}
1397 	if (i == CTL_NUM_MODE_PAGES) {
1398 		mtx_unlock(&lun->lun_lock);
1399 		return;
1400 	}
1401 	memcpy(lun->mode_pages.index[i].page_data, msg->mode.data,
1402 	    lun->mode_pages.index[i].page_len);
1403 	initidx = ctl_get_initindex(&msg->hdr.nexus);
1404 	if (initidx != -1)
1405 		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
1406 	mtx_unlock(&lun->lun_lock);
1407 }
1408 
1409 /*
1410  * ISC (Inter Shelf Communication) event handler.  Events from the HA
1411  * subsystem come in here.
1412  */
1413 static void
1414 ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
1415 {
1416 	struct ctl_softc *softc = control_softc;
1417 	union ctl_io *io;
1418 	struct ctl_prio *presio;
1419 	ctl_ha_status isc_status;
1420 
1421 	CTL_DEBUG_PRINT(("CTL: Isc Msg event %d\n", event));
1422 	if (event == CTL_HA_EVT_MSG_RECV) {
1423 		union ctl_ha_msg *msg, msgbuf;
1424 
1425 		if (param > sizeof(msgbuf))
1426 			msg = malloc(param, M_CTL, M_WAITOK);
1427 		else
1428 			msg = &msgbuf;
1429 		isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, msg, param,
1430 		    M_WAITOK);
1431 		if (isc_status != CTL_HA_STATUS_SUCCESS) {
1432 			printf("%s: Error receiving message: %d\n",
1433 			    __func__, isc_status);
1434 			if (msg != &msgbuf)
1435 				free(msg, M_CTL);
1436 			return;
1437 		}
1438 
1439 		CTL_DEBUG_PRINT(("CTL: msg_type %d\n", msg->hdr.msg_type));
1440 		switch (msg->hdr.msg_type) {
1441 		case CTL_MSG_SERIALIZE:
1442 			io = ctl_alloc_io(softc->othersc_pool);
1443 			ctl_zero_io(io);
1444 			// populate ctsio from msg
1445 			io->io_hdr.io_type = CTL_IO_SCSI;
1446 			io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
1447 			io->io_hdr.remote_io = msg->hdr.original_sc;
1448 			io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
1449 					    CTL_FLAG_IO_ACTIVE;
1450 			/*
1451 			 * If we're in serialization-only mode, we don't
1452 			 * want to go through full done processing.  Thus
1453 			 * the COPY flag.
1454 			 *
1455 			 * XXX KDM add another flag that is more specific.
1456 			 */
1457 			if (softc->ha_mode != CTL_HA_MODE_XFER)
1458 				io->io_hdr.flags |= CTL_FLAG_INT_COPY;
1459 			io->io_hdr.nexus = msg->hdr.nexus;
1460 			io->scsiio.priority = msg->scsi.priority;
1461 			io->scsiio.tag_num = msg->scsi.tag_num;
1462 			io->scsiio.tag_type = msg->scsi.tag_type;
1463 #ifdef CTL_TIME_IO
1464 			io->io_hdr.start_time = time_uptime;
1465 			getbinuptime(&io->io_hdr.start_bt);
1466 #endif /* CTL_TIME_IO */
1467 			io->scsiio.cdb_len = msg->scsi.cdb_len;
1468 			memcpy(io->scsiio.cdb, msg->scsi.cdb,
1469 			       CTL_MAX_CDBLEN);
1470 			if (softc->ha_mode == CTL_HA_MODE_XFER) {
1471 				const struct ctl_cmd_entry *entry;
1472 
1473 				entry = ctl_get_cmd_entry(&io->scsiio, NULL);
1474 				io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
1475 				io->io_hdr.flags |=
1476 					entry->flags & CTL_FLAG_DATA_MASK;
1477 			}
1478 			ctl_enqueue_isc(io);
1479 			break;
1480 
1481 		/* Performed on the Originating SC, XFER mode only */
1482 		case CTL_MSG_DATAMOVE: {
1483 			struct ctl_sg_entry *sgl;
1484 			int i, j;
1485 
1486 			io = msg->hdr.original_sc;
1487 			if (io == NULL) {
1488 				printf("%s: original_sc == NULL!\n", __func__);
1489 				/* XXX KDM do something here */
1490 				break;
1491 			}
1492 			io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
1493 			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1494 			/*
1495 			 * Keep track of this, we need to send it back over
1496 			 * when the datamove is complete.
1497 			 */
1498 			io->io_hdr.remote_io = msg->hdr.serializing_sc;
1499 			if (msg->hdr.status == CTL_SUCCESS)
1500 				io->io_hdr.status = msg->hdr.status;
1501 
1502 			if (msg->dt.sg_sequence == 0) {
1503 #ifdef CTL_TIME_IO
1504 				getbinuptime(&io->io_hdr.dma_start_bt);
1505 #endif
1506 				i = msg->dt.kern_sg_entries +
1507 				    msg->dt.kern_data_len /
1508 				    CTL_HA_DATAMOVE_SEGMENT + 1;
1509 				sgl = malloc(sizeof(*sgl) * i, M_CTL,
1510 				    M_WAITOK | M_ZERO);
1511 				CTL_RSGL(io) = sgl;
1512 				CTL_LSGL(io) = &sgl[msg->dt.kern_sg_entries];
1513 
1514 				io->scsiio.kern_data_ptr = (uint8_t *)sgl;
1515 
1516 				io->scsiio.kern_sg_entries =
1517 					msg->dt.kern_sg_entries;
1518 				io->scsiio.rem_sg_entries =
1519 					msg->dt.kern_sg_entries;
1520 				io->scsiio.kern_data_len =
1521 					msg->dt.kern_data_len;
1522 				io->scsiio.kern_total_len =
1523 					msg->dt.kern_total_len;
1524 				io->scsiio.kern_data_resid =
1525 					msg->dt.kern_data_resid;
1526 				io->scsiio.kern_rel_offset =
1527 					msg->dt.kern_rel_offset;
1528 				io->io_hdr.flags &= ~CTL_FLAG_BUS_ADDR;
1529 				io->io_hdr.flags |= msg->dt.flags &
1530 				    CTL_FLAG_BUS_ADDR;
1531 			} else
1532 				sgl = (struct ctl_sg_entry *)
1533 					io->scsiio.kern_data_ptr;
1534 
1535 			for (i = msg->dt.sent_sg_entries, j = 0;
1536 			     i < (msg->dt.sent_sg_entries +
1537 			     msg->dt.cur_sg_entries); i++, j++) {
1538 				sgl[i].addr = msg->dt.sg_list[j].addr;
1539 				sgl[i].len = msg->dt.sg_list[j].len;
1540 			}
1541 
1542 			/*
1543 			 * If this is the last piece of the I/O, we've got
1544 			 * the full S/G list.  Queue processing in the thread.
1545 			 * Otherwise wait for the next piece.
1546 			 */
1547 			if (msg->dt.sg_last != 0)
1548 				ctl_enqueue_isc(io);
1549 			break;
1550 		}
1551 		/* Performed on the Serializing (primary) SC, XFER mode only */
1552 		case CTL_MSG_DATAMOVE_DONE: {
1553 			if (msg->hdr.serializing_sc == NULL) {
1554 				printf("%s: serializing_sc == NULL!\n",
1555 				       __func__);
1556 				/* XXX KDM now what? */
1557 				break;
1558 			}
1559 			/*
1560 			 * We grab the sense information here in case
1561 			 * there was a failure, so we can return status
1562 			 * back to the initiator.
1563 			 */
1564 			io = msg->hdr.serializing_sc;
1565 			io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
1566 			io->io_hdr.flags &= ~CTL_FLAG_DMA_INPROG;
1567 			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1568 			io->io_hdr.port_status = msg->scsi.port_status;
1569 			io->scsiio.kern_data_resid = msg->scsi.kern_data_resid;
1570 			if (msg->hdr.status != CTL_STATUS_NONE) {
1571 				io->io_hdr.status = msg->hdr.status;
1572 				io->scsiio.scsi_status = msg->scsi.scsi_status;
1573 				io->scsiio.sense_len = msg->scsi.sense_len;
1574 				memcpy(&io->scsiio.sense_data,
1575 				    &msg->scsi.sense_data,
1576 				    msg->scsi.sense_len);
1577 				if (msg->hdr.status == CTL_SUCCESS)
1578 					io->io_hdr.flags |= CTL_FLAG_STATUS_SENT;
1579 			}
1580 			ctl_enqueue_isc(io);
1581 			break;
1582 		}
1583 
1584 		/* Preformed on Originating SC, SER_ONLY mode */
1585 		case CTL_MSG_R2R:
1586 			io = msg->hdr.original_sc;
1587 			if (io == NULL) {
1588 				printf("%s: original_sc == NULL!\n",
1589 				    __func__);
1590 				break;
1591 			}
1592 			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1593 			io->io_hdr.msg_type = CTL_MSG_R2R;
1594 			io->io_hdr.remote_io = msg->hdr.serializing_sc;
1595 			ctl_enqueue_isc(io);
1596 			break;
1597 
1598 		/*
1599 		 * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
1600 		 * mode.
1601 		 * Performed on the Originating (i.e. secondary) SC in XFER
1602 		 * mode
1603 		 */
1604 		case CTL_MSG_FINISH_IO:
1605 			if (softc->ha_mode == CTL_HA_MODE_XFER)
1606 				ctl_isc_handler_finish_xfer(softc, msg);
1607 			else
1608 				ctl_isc_handler_finish_ser_only(softc, msg);
1609 			break;
1610 
1611 		/* Preformed on Originating SC */
1612 		case CTL_MSG_BAD_JUJU:
1613 			io = msg->hdr.original_sc;
1614 			if (io == NULL) {
1615 				printf("%s: Bad JUJU!, original_sc is NULL!\n",
1616 				       __func__);
1617 				break;
1618 			}
1619 			ctl_copy_sense_data(msg, io);
1620 			/*
1621 			 * IO should have already been cleaned up on other
1622 			 * SC so clear this flag so we won't send a message
1623 			 * back to finish the IO there.
1624 			 */
1625 			io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
1626 			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1627 
1628 			/* io = msg->hdr.serializing_sc; */
1629 			io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
1630 			ctl_enqueue_isc(io);
1631 			break;
1632 
1633 		/* Handle resets sent from the other side */
1634 		case CTL_MSG_MANAGE_TASKS: {
1635 			struct ctl_taskio *taskio;
1636 			taskio = (struct ctl_taskio *)ctl_alloc_io(
1637 			    softc->othersc_pool);
1638 			ctl_zero_io((union ctl_io *)taskio);
1639 			taskio->io_hdr.io_type = CTL_IO_TASK;
1640 			taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1641 			taskio->io_hdr.nexus = msg->hdr.nexus;
1642 			taskio->task_action = msg->task.task_action;
1643 			taskio->tag_num = msg->task.tag_num;
1644 			taskio->tag_type = msg->task.tag_type;
1645 #ifdef CTL_TIME_IO
1646 			taskio->io_hdr.start_time = time_uptime;
1647 			getbinuptime(&taskio->io_hdr.start_bt);
1648 #endif /* CTL_TIME_IO */
1649 			ctl_run_task((union ctl_io *)taskio);
1650 			break;
1651 		}
1652 		/* Persistent Reserve action which needs attention */
1653 		case CTL_MSG_PERS_ACTION:
1654 			presio = (struct ctl_prio *)ctl_alloc_io(
1655 			    softc->othersc_pool);
1656 			ctl_zero_io((union ctl_io *)presio);
1657 			presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
1658 			presio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1659 			presio->io_hdr.nexus = msg->hdr.nexus;
1660 			presio->pr_msg = msg->pr;
1661 			ctl_enqueue_isc((union ctl_io *)presio);
1662 			break;
1663 		case CTL_MSG_UA:
1664 			ctl_isc_ua(softc, msg, param);
1665 			break;
1666 		case CTL_MSG_PORT_SYNC:
1667 			ctl_isc_port_sync(softc, msg, param);
1668 			break;
1669 		case CTL_MSG_LUN_SYNC:
1670 			ctl_isc_lun_sync(softc, msg, param);
1671 			break;
1672 		case CTL_MSG_IID_SYNC:
1673 			ctl_isc_iid_sync(softc, msg, param);
1674 			break;
1675 		case CTL_MSG_LOGIN:
1676 			ctl_isc_login(softc, msg, param);
1677 			break;
1678 		case CTL_MSG_MODE_SYNC:
1679 			ctl_isc_mode_sync(softc, msg, param);
1680 			break;
1681 		default:
1682 			printf("Received HA message of unknown type %d\n",
1683 			    msg->hdr.msg_type);
1684 			ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1685 			break;
1686 		}
1687 		if (msg != &msgbuf)
1688 			free(msg, M_CTL);
1689 	} else if (event == CTL_HA_EVT_LINK_CHANGE) {
1690 		printf("CTL: HA link status changed from %d to %d\n",
1691 		    softc->ha_link, param);
1692 		if (param == softc->ha_link)
1693 			return;
1694 		if (softc->ha_link == CTL_HA_LINK_ONLINE) {
1695 			softc->ha_link = param;
1696 			ctl_isc_ha_link_down(softc);
1697 		} else {
1698 			softc->ha_link = param;
1699 			if (softc->ha_link == CTL_HA_LINK_ONLINE)
1700 				ctl_isc_ha_link_up(softc);
1701 		}
1702 		return;
1703 	} else {
1704 		printf("ctl_isc_event_handler: Unknown event %d\n", event);
1705 		return;
1706 	}
1707 }
1708 
1709 static void
1710 ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
1711 {
1712 
1713 	memcpy(&dest->scsiio.sense_data, &src->scsi.sense_data,
1714 	    src->scsi.sense_len);
1715 	dest->scsiio.scsi_status = src->scsi.scsi_status;
1716 	dest->scsiio.sense_len = src->scsi.sense_len;
1717 	dest->io_hdr.status = src->hdr.status;
1718 }
1719 
1720 static void
1721 ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest)
1722 {
1723 
1724 	memcpy(&dest->scsi.sense_data, &src->scsiio.sense_data,
1725 	    src->scsiio.sense_len);
1726 	dest->scsi.scsi_status = src->scsiio.scsi_status;
1727 	dest->scsi.sense_len = src->scsiio.sense_len;
1728 	dest->hdr.status = src->io_hdr.status;
1729 }
1730 
1731 void
1732 ctl_est_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1733 {
1734 	struct ctl_softc *softc = lun->ctl_softc;
1735 	ctl_ua_type *pu;
1736 
1737 	if (initidx < softc->init_min || initidx >= softc->init_max)
1738 		return;
1739 	mtx_assert(&lun->lun_lock, MA_OWNED);
1740 	pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1741 	if (pu == NULL)
1742 		return;
1743 	pu[initidx % CTL_MAX_INIT_PER_PORT] |= ua;
1744 }
1745 
1746 void
1747 ctl_est_ua_port(struct ctl_lun *lun, int port, uint32_t except, ctl_ua_type ua)
1748 {
1749 	int i;
1750 
1751 	mtx_assert(&lun->lun_lock, MA_OWNED);
1752 	if (lun->pending_ua[port] == NULL)
1753 		return;
1754 	for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1755 		if (port * CTL_MAX_INIT_PER_PORT + i == except)
1756 			continue;
1757 		lun->pending_ua[port][i] |= ua;
1758 	}
1759 }
1760 
1761 void
1762 ctl_est_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1763 {
1764 	struct ctl_softc *softc = lun->ctl_softc;
1765 	int i;
1766 
1767 	mtx_assert(&lun->lun_lock, MA_OWNED);
1768 	for (i = softc->port_min; i < softc->port_max; i++)
1769 		ctl_est_ua_port(lun, i, except, ua);
1770 }
1771 
1772 void
1773 ctl_clr_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1774 {
1775 	struct ctl_softc *softc = lun->ctl_softc;
1776 	ctl_ua_type *pu;
1777 
1778 	if (initidx < softc->init_min || initidx >= softc->init_max)
1779 		return;
1780 	mtx_assert(&lun->lun_lock, MA_OWNED);
1781 	pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1782 	if (pu == NULL)
1783 		return;
1784 	pu[initidx % CTL_MAX_INIT_PER_PORT] &= ~ua;
1785 }
1786 
1787 void
1788 ctl_clr_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1789 {
1790 	struct ctl_softc *softc = lun->ctl_softc;
1791 	int i, j;
1792 
1793 	mtx_assert(&lun->lun_lock, MA_OWNED);
1794 	for (i = softc->port_min; i < softc->port_max; i++) {
1795 		if (lun->pending_ua[i] == NULL)
1796 			continue;
1797 		for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
1798 			if (i * CTL_MAX_INIT_PER_PORT + j == except)
1799 				continue;
1800 			lun->pending_ua[i][j] &= ~ua;
1801 		}
1802 	}
1803 }
1804 
1805 void
1806 ctl_clr_ua_allluns(struct ctl_softc *ctl_softc, uint32_t initidx,
1807     ctl_ua_type ua_type)
1808 {
1809 	struct ctl_lun *lun;
1810 
1811 	mtx_assert(&ctl_softc->ctl_lock, MA_OWNED);
1812 	STAILQ_FOREACH(lun, &ctl_softc->lun_list, links) {
1813 		mtx_lock(&lun->lun_lock);
1814 		ctl_clr_ua(lun, initidx, ua_type);
1815 		mtx_unlock(&lun->lun_lock);
1816 	}
1817 }
1818 
1819 static int
1820 ctl_ha_role_sysctl(SYSCTL_HANDLER_ARGS)
1821 {
1822 	struct ctl_softc *softc = (struct ctl_softc *)arg1;
1823 	struct ctl_lun *lun;
1824 	struct ctl_lun_req ireq;
1825 	int error, value;
1826 
1827 	value = (softc->flags & CTL_FLAG_ACTIVE_SHELF) ? 0 : 1;
1828 	error = sysctl_handle_int(oidp, &value, 0, req);
1829 	if ((error != 0) || (req->newptr == NULL))
1830 		return (error);
1831 
1832 	mtx_lock(&softc->ctl_lock);
1833 	if (value == 0)
1834 		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1835 	else
1836 		softc->flags &= ~CTL_FLAG_ACTIVE_SHELF;
1837 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
1838 		mtx_unlock(&softc->ctl_lock);
1839 		bzero(&ireq, sizeof(ireq));
1840 		ireq.reqtype = CTL_LUNREQ_MODIFY;
1841 		ireq.reqdata.modify.lun_id = lun->lun;
1842 		lun->backend->ioctl(NULL, CTL_LUN_REQ, (caddr_t)&ireq, 0,
1843 		    curthread);
1844 		if (ireq.status != CTL_LUN_OK) {
1845 			printf("%s: CTL_LUNREQ_MODIFY returned %d '%s'\n",
1846 			    __func__, ireq.status, ireq.error_str);
1847 		}
1848 		mtx_lock(&softc->ctl_lock);
1849 	}
1850 	mtx_unlock(&softc->ctl_lock);
1851 	return (0);
1852 }
1853 
1854 static int
1855 ctl_init(void)
1856 {
1857 	struct make_dev_args args;
1858 	struct ctl_softc *softc;
1859 	int i, error;
1860 
1861 	softc = control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
1862 			       M_WAITOK | M_ZERO);
1863 
1864 	make_dev_args_init(&args);
1865 	args.mda_devsw = &ctl_cdevsw;
1866 	args.mda_uid = UID_ROOT;
1867 	args.mda_gid = GID_OPERATOR;
1868 	args.mda_mode = 0600;
1869 	args.mda_si_drv1 = softc;
1870 	args.mda_si_drv2 = NULL;
1871 	error = make_dev_s(&args, &softc->dev, "cam/ctl");
1872 	if (error != 0) {
1873 		free(softc, M_DEVBUF);
1874 		control_softc = NULL;
1875 		return (error);
1876 	}
1877 
1878 	sysctl_ctx_init(&softc->sysctl_ctx);
1879 	softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
1880 		SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
1881 		CTLFLAG_RD | CTLFLAG_MPSAFE, 0, "CAM Target Layer");
1882 
1883 	if (softc->sysctl_tree == NULL) {
1884 		printf("%s: unable to allocate sysctl tree\n", __func__);
1885 		destroy_dev(softc->dev);
1886 		free(softc, M_DEVBUF);
1887 		control_softc = NULL;
1888 		return (ENOMEM);
1889 	}
1890 
1891 	mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
1892 	softc->io_zone = uma_zcreate("CTL IO", sizeof(union ctl_io),
1893 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1894 	softc->flags = 0;
1895 
1896 	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1897 	    OID_AUTO, "ha_mode", CTLFLAG_RDTUN, (int *)&softc->ha_mode, 0,
1898 	    "HA mode (0 - act/stby, 1 - serialize only, 2 - xfer)");
1899 
1900 	if (ctl_max_luns <= 0 || powerof2(ctl_max_luns) == 0) {
1901 		printf("Bad value %d for kern.cam.ctl.max_luns, must be a power of two, using %d\n",
1902 		    ctl_max_luns, CTL_DEFAULT_MAX_LUNS);
1903 		ctl_max_luns = CTL_DEFAULT_MAX_LUNS;
1904 	}
1905 	softc->ctl_luns = malloc(sizeof(struct ctl_lun *) * ctl_max_luns,
1906 	    M_DEVBUF, M_WAITOK | M_ZERO);
1907 	softc->ctl_lun_mask = malloc(sizeof(uint32_t) *
1908 	    ((ctl_max_luns + 31) / 32), M_DEVBUF, M_WAITOK | M_ZERO);
1909 	if (ctl_max_ports <= 0 || powerof2(ctl_max_ports) == 0) {
1910 		printf("Bad value %d for kern.cam.ctl.max_ports, must be a power of two, using %d\n",
1911 		    ctl_max_ports, CTL_DEFAULT_MAX_PORTS);
1912 		ctl_max_ports = CTL_DEFAULT_MAX_PORTS;
1913 	}
1914 	softc->ctl_port_mask = malloc(sizeof(uint32_t) *
1915 	  ((ctl_max_ports + 31) / 32), M_DEVBUF, M_WAITOK | M_ZERO);
1916 	softc->ctl_ports = malloc(sizeof(struct ctl_port *) * ctl_max_ports,
1917 	     M_DEVBUF, M_WAITOK | M_ZERO);
1918 
1919 	/*
1920 	 * In Copan's HA scheme, the "master" and "slave" roles are
1921 	 * figured out through the slot the controller is in.  Although it
1922 	 * is an active/active system, someone has to be in charge.
1923 	 */
1924 	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1925 	    OID_AUTO, "ha_id", CTLFLAG_RDTUN, &softc->ha_id, 0,
1926 	    "HA head ID (0 - no HA)");
1927 	if (softc->ha_id == 0 || softc->ha_id > NUM_HA_SHELVES) {
1928 		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1929 		softc->is_single = 1;
1930 		softc->port_cnt = ctl_max_ports;
1931 		softc->port_min = 0;
1932 	} else {
1933 		softc->port_cnt = ctl_max_ports / NUM_HA_SHELVES;
1934 		softc->port_min = (softc->ha_id - 1) * softc->port_cnt;
1935 	}
1936 	softc->port_max = softc->port_min + softc->port_cnt;
1937 	softc->init_min = softc->port_min * CTL_MAX_INIT_PER_PORT;
1938 	softc->init_max = softc->port_max * CTL_MAX_INIT_PER_PORT;
1939 
1940 	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1941 	    OID_AUTO, "ha_link", CTLFLAG_RD, (int *)&softc->ha_link, 0,
1942 	    "HA link state (0 - offline, 1 - unknown, 2 - online)");
1943 
1944 	STAILQ_INIT(&softc->lun_list);
1945 	STAILQ_INIT(&softc->fe_list);
1946 	STAILQ_INIT(&softc->port_list);
1947 	STAILQ_INIT(&softc->be_list);
1948 	ctl_tpc_init(softc);
1949 
1950 	if (worker_threads <= 0)
1951 		worker_threads = max(1, mp_ncpus / 4);
1952 	if (worker_threads > CTL_MAX_THREADS)
1953 		worker_threads = CTL_MAX_THREADS;
1954 
1955 	for (i = 0; i < worker_threads; i++) {
1956 		struct ctl_thread *thr = &softc->threads[i];
1957 
1958 		mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1959 		thr->ctl_softc = softc;
1960 		STAILQ_INIT(&thr->incoming_queue);
1961 		STAILQ_INIT(&thr->rtr_queue);
1962 		STAILQ_INIT(&thr->done_queue);
1963 		STAILQ_INIT(&thr->isc_queue);
1964 
1965 		error = kproc_kthread_add(ctl_work_thread, thr,
1966 		    &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1967 		if (error != 0) {
1968 			printf("error creating CTL work thread!\n");
1969 			return (error);
1970 		}
1971 	}
1972 	error = kproc_kthread_add(ctl_thresh_thread, softc,
1973 	    &softc->ctl_proc, &softc->thresh_thread, 0, 0, "ctl", "thresh");
1974 	if (error != 0) {
1975 		printf("error creating CTL threshold thread!\n");
1976 		return (error);
1977 	}
1978 
1979 	SYSCTL_ADD_PROC(&softc->sysctl_ctx,SYSCTL_CHILDREN(softc->sysctl_tree),
1980 	    OID_AUTO, "ha_role",
1981 	    CTLTYPE_INT | CTLFLAG_RWTUN | CTLFLAG_NEEDGIANT,
1982 	    softc, 0, ctl_ha_role_sysctl, "I", "HA role for this head");
1983 
1984 	if (softc->is_single == 0) {
1985 		if (ctl_frontend_register(&ha_frontend) != 0)
1986 			softc->is_single = 1;
1987 	}
1988 	return (0);
1989 }
1990 
1991 static int
1992 ctl_shutdown(void)
1993 {
1994 	struct ctl_softc *softc = control_softc;
1995 	int i;
1996 
1997 	if (softc->is_single == 0)
1998 		ctl_frontend_deregister(&ha_frontend);
1999 
2000 	destroy_dev(softc->dev);
2001 
2002 	/* Shutdown CTL threads. */
2003 	softc->shutdown = 1;
2004 	for (i = 0; i < worker_threads; i++) {
2005 		struct ctl_thread *thr = &softc->threads[i];
2006 		while (thr->thread != NULL) {
2007 			wakeup(thr);
2008 			if (thr->thread != NULL)
2009 				pause("CTL thr shutdown", 1);
2010 		}
2011 		mtx_destroy(&thr->queue_lock);
2012 	}
2013 	while (softc->thresh_thread != NULL) {
2014 		wakeup(softc->thresh_thread);
2015 		if (softc->thresh_thread != NULL)
2016 			pause("CTL thr shutdown", 1);
2017 	}
2018 
2019 	ctl_tpc_shutdown(softc);
2020 	uma_zdestroy(softc->io_zone);
2021 	mtx_destroy(&softc->ctl_lock);
2022 
2023 	free(softc->ctl_luns, M_DEVBUF);
2024 	free(softc->ctl_lun_mask, M_DEVBUF);
2025 	free(softc->ctl_port_mask, M_DEVBUF);
2026 	free(softc->ctl_ports, M_DEVBUF);
2027 
2028 	sysctl_ctx_free(&softc->sysctl_ctx);
2029 
2030 	free(softc, M_DEVBUF);
2031 	control_softc = NULL;
2032 	return (0);
2033 }
2034 
2035 static int
2036 ctl_module_event_handler(module_t mod, int what, void *arg)
2037 {
2038 
2039 	switch (what) {
2040 	case MOD_LOAD:
2041 		return (ctl_init());
2042 	case MOD_UNLOAD:
2043 		return (ctl_shutdown());
2044 	default:
2045 		return (EOPNOTSUPP);
2046 	}
2047 }
2048 
2049 /*
2050  * XXX KDM should we do some access checks here?  Bump a reference count to
2051  * prevent a CTL module from being unloaded while someone has it open?
2052  */
2053 static int
2054 ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
2055 {
2056 	return (0);
2057 }
2058 
2059 static int
2060 ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
2061 {
2062 	return (0);
2063 }
2064 
2065 /*
2066  * Remove an initiator by port number and initiator ID.
2067  * Returns 0 for success, -1 for failure.
2068  */
2069 int
2070 ctl_remove_initiator(struct ctl_port *port, int iid)
2071 {
2072 	struct ctl_softc *softc = port->ctl_softc;
2073 	int last;
2074 
2075 	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
2076 
2077 	if (iid > CTL_MAX_INIT_PER_PORT) {
2078 		printf("%s: initiator ID %u > maximun %u!\n",
2079 		       __func__, iid, CTL_MAX_INIT_PER_PORT);
2080 		return (-1);
2081 	}
2082 
2083 	mtx_lock(&softc->ctl_lock);
2084 	last = (--port->wwpn_iid[iid].in_use == 0);
2085 	port->wwpn_iid[iid].last_use = time_uptime;
2086 	mtx_unlock(&softc->ctl_lock);
2087 	if (last)
2088 		ctl_i_t_nexus_loss(softc, iid, CTL_UA_POWERON);
2089 	ctl_isc_announce_iid(port, iid);
2090 
2091 	return (0);
2092 }
2093 
2094 /*
2095  * Add an initiator to the initiator map.
2096  * Returns iid for success, < 0 for failure.
2097  */
2098 int
2099 ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
2100 {
2101 	struct ctl_softc *softc = port->ctl_softc;
2102 	time_t best_time;
2103 	int i, best;
2104 
2105 	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
2106 
2107 	if (iid >= CTL_MAX_INIT_PER_PORT) {
2108 		printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
2109 		       __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
2110 		free(name, M_CTL);
2111 		return (-1);
2112 	}
2113 
2114 	mtx_lock(&softc->ctl_lock);
2115 
2116 	if (iid < 0 && (wwpn != 0 || name != NULL)) {
2117 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2118 			if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
2119 				iid = i;
2120 				break;
2121 			}
2122 			if (name != NULL && port->wwpn_iid[i].name != NULL &&
2123 			    strcmp(name, port->wwpn_iid[i].name) == 0) {
2124 				iid = i;
2125 				break;
2126 			}
2127 		}
2128 	}
2129 
2130 	if (iid < 0) {
2131 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2132 			if (port->wwpn_iid[i].in_use == 0 &&
2133 			    port->wwpn_iid[i].wwpn == 0 &&
2134 			    port->wwpn_iid[i].name == NULL) {
2135 				iid = i;
2136 				break;
2137 			}
2138 		}
2139 	}
2140 
2141 	if (iid < 0) {
2142 		best = -1;
2143 		best_time = INT32_MAX;
2144 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2145 			if (port->wwpn_iid[i].in_use == 0) {
2146 				if (port->wwpn_iid[i].last_use < best_time) {
2147 					best = i;
2148 					best_time = port->wwpn_iid[i].last_use;
2149 				}
2150 			}
2151 		}
2152 		iid = best;
2153 	}
2154 
2155 	if (iid < 0) {
2156 		mtx_unlock(&softc->ctl_lock);
2157 		free(name, M_CTL);
2158 		return (-2);
2159 	}
2160 
2161 	if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
2162 		/*
2163 		 * This is not an error yet.
2164 		 */
2165 		if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
2166 #if 0
2167 			printf("%s: port %d iid %u WWPN %#jx arrived"
2168 			    " again\n", __func__, port->targ_port,
2169 			    iid, (uintmax_t)wwpn);
2170 #endif
2171 			goto take;
2172 		}
2173 		if (name != NULL && port->wwpn_iid[iid].name != NULL &&
2174 		    strcmp(name, port->wwpn_iid[iid].name) == 0) {
2175 #if 0
2176 			printf("%s: port %d iid %u name '%s' arrived"
2177 			    " again\n", __func__, port->targ_port,
2178 			    iid, name);
2179 #endif
2180 			goto take;
2181 		}
2182 
2183 		/*
2184 		 * This is an error, but what do we do about it?  The
2185 		 * driver is telling us we have a new WWPN for this
2186 		 * initiator ID, so we pretty much need to use it.
2187 		 */
2188 		printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
2189 		    " but WWPN %#jx '%s' is still at that address\n",
2190 		    __func__, port->targ_port, iid, wwpn, name,
2191 		    (uintmax_t)port->wwpn_iid[iid].wwpn,
2192 		    port->wwpn_iid[iid].name);
2193 	}
2194 take:
2195 	free(port->wwpn_iid[iid].name, M_CTL);
2196 	port->wwpn_iid[iid].name = name;
2197 	port->wwpn_iid[iid].wwpn = wwpn;
2198 	port->wwpn_iid[iid].in_use++;
2199 	mtx_unlock(&softc->ctl_lock);
2200 	ctl_isc_announce_iid(port, iid);
2201 
2202 	return (iid);
2203 }
2204 
2205 static int
2206 ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
2207 {
2208 	int len;
2209 
2210 	switch (port->port_type) {
2211 	case CTL_PORT_FC:
2212 	{
2213 		struct scsi_transportid_fcp *id =
2214 		    (struct scsi_transportid_fcp *)buf;
2215 		if (port->wwpn_iid[iid].wwpn == 0)
2216 			return (0);
2217 		memset(id, 0, sizeof(*id));
2218 		id->format_protocol = SCSI_PROTO_FC;
2219 		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
2220 		return (sizeof(*id));
2221 	}
2222 	case CTL_PORT_ISCSI:
2223 	{
2224 		struct scsi_transportid_iscsi_port *id =
2225 		    (struct scsi_transportid_iscsi_port *)buf;
2226 		if (port->wwpn_iid[iid].name == NULL)
2227 			return (0);
2228 		memset(id, 0, 256);
2229 		id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
2230 		    SCSI_PROTO_ISCSI;
2231 		len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
2232 		len = roundup2(min(len, 252), 4);
2233 		scsi_ulto2b(len, id->additional_length);
2234 		return (sizeof(*id) + len);
2235 	}
2236 	case CTL_PORT_SAS:
2237 	{
2238 		struct scsi_transportid_sas *id =
2239 		    (struct scsi_transportid_sas *)buf;
2240 		if (port->wwpn_iid[iid].wwpn == 0)
2241 			return (0);
2242 		memset(id, 0, sizeof(*id));
2243 		id->format_protocol = SCSI_PROTO_SAS;
2244 		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
2245 		return (sizeof(*id));
2246 	}
2247 	default:
2248 	{
2249 		struct scsi_transportid_spi *id =
2250 		    (struct scsi_transportid_spi *)buf;
2251 		memset(id, 0, sizeof(*id));
2252 		id->format_protocol = SCSI_PROTO_SPI;
2253 		scsi_ulto2b(iid, id->scsi_addr);
2254 		scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
2255 		return (sizeof(*id));
2256 	}
2257 	}
2258 }
2259 
2260 /*
2261  * Serialize a command that went down the "wrong" side, and so was sent to
2262  * this controller for execution.  The logic is a little different than the
2263  * standard case in ctl_scsiio_precheck().  Errors in this case need to get
2264  * sent back to the other side, but in the success case, we execute the
2265  * command on this side (XFER mode) or tell the other side to execute it
2266  * (SER_ONLY mode).
2267  */
2268 static void
2269 ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
2270 {
2271 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
2272 	struct ctl_port *port = CTL_PORT(ctsio);
2273 	union ctl_ha_msg msg_info;
2274 	struct ctl_lun *lun;
2275 	const struct ctl_cmd_entry *entry;
2276 	union ctl_io *bio;
2277 	uint32_t targ_lun;
2278 
2279 	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
2280 
2281 	/* Make sure that we know about this port. */
2282 	if (port == NULL || (port->status & CTL_PORT_STATUS_ONLINE) == 0) {
2283 		ctl_set_internal_failure(ctsio, /*sks_valid*/ 0,
2284 					 /*retry_count*/ 1);
2285 		goto badjuju;
2286 	}
2287 
2288 	/* Make sure that we know about this LUN. */
2289 	mtx_lock(&softc->ctl_lock);
2290 	if (targ_lun >= ctl_max_luns ||
2291 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
2292 		mtx_unlock(&softc->ctl_lock);
2293 
2294 		/*
2295 		 * The other node would not send this request to us unless
2296 		 * received announce that we are primary node for this LUN.
2297 		 * If this LUN does not exist now, it is probably result of
2298 		 * a race, so respond to initiator in the most opaque way.
2299 		 */
2300 		ctl_set_busy(ctsio);
2301 		goto badjuju;
2302 	}
2303 	mtx_lock(&lun->lun_lock);
2304 	mtx_unlock(&softc->ctl_lock);
2305 
2306 	/*
2307 	 * If the LUN is invalid, pretend that it doesn't exist.
2308 	 * It will go away as soon as all pending I/Os completed.
2309 	 */
2310 	if (lun->flags & CTL_LUN_DISABLED) {
2311 		mtx_unlock(&lun->lun_lock);
2312 		ctl_set_busy(ctsio);
2313 		goto badjuju;
2314 	}
2315 
2316 	entry = ctl_get_cmd_entry(ctsio, NULL);
2317 	ctsio->seridx = entry->seridx;
2318 	if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
2319 		mtx_unlock(&lun->lun_lock);
2320 		goto badjuju;
2321 	}
2322 
2323 	CTL_LUN(ctsio) = lun;
2324 	CTL_BACKEND_LUN(ctsio) = lun->be_lun;
2325 
2326 	/*
2327 	 * Every I/O goes into the OOA queue for a
2328 	 * particular LUN, and stays there until completion.
2329 	 */
2330 #ifdef CTL_TIME_IO
2331 	if (LIST_EMPTY(&lun->ooa_queue))
2332 		lun->idle_time += getsbinuptime() - lun->last_busy;
2333 #endif
2334 	LIST_INSERT_HEAD(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2335 
2336 	bio = (union ctl_io *)LIST_NEXT(&ctsio->io_hdr, ooa_links);
2337 	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio, &bio)) {
2338 	case CTL_ACTION_PASS:
2339 	case CTL_ACTION_SKIP:
2340 		if (softc->ha_mode == CTL_HA_MODE_XFER) {
2341 			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
2342 			ctl_enqueue_rtr((union ctl_io *)ctsio);
2343 			mtx_unlock(&lun->lun_lock);
2344 		} else {
2345 			ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
2346 			mtx_unlock(&lun->lun_lock);
2347 
2348 			/* send msg back to other side */
2349 			msg_info.hdr.original_sc = ctsio->io_hdr.remote_io;
2350 			msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
2351 			msg_info.hdr.msg_type = CTL_MSG_R2R;
2352 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2353 			    sizeof(msg_info.hdr), M_WAITOK);
2354 		}
2355 		break;
2356 	case CTL_ACTION_BLOCK:
2357 		ctsio->io_hdr.blocker = bio;
2358 		TAILQ_INSERT_TAIL(&bio->io_hdr.blocked_queue, &ctsio->io_hdr,
2359 				  blocked_links);
2360 		mtx_unlock(&lun->lun_lock);
2361 		break;
2362 	case CTL_ACTION_OVERLAP:
2363 		LIST_REMOVE(&ctsio->io_hdr, ooa_links);
2364 		mtx_unlock(&lun->lun_lock);
2365 		ctl_set_overlapped_cmd(ctsio);
2366 		goto badjuju;
2367 	case CTL_ACTION_OVERLAP_TAG:
2368 		LIST_REMOVE(&ctsio->io_hdr, ooa_links);
2369 		mtx_unlock(&lun->lun_lock);
2370 		ctl_set_overlapped_tag(ctsio, ctsio->tag_num);
2371 badjuju:
2372 		ctl_copy_sense_data_back((union ctl_io *)ctsio, &msg_info);
2373 		msg_info.hdr.original_sc = ctsio->io_hdr.remote_io;
2374 		msg_info.hdr.serializing_sc = NULL;
2375 		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
2376 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2377 		    sizeof(msg_info.scsi), M_WAITOK);
2378 		ctl_free_io((union ctl_io *)ctsio);
2379 		break;
2380 	default:
2381 		__assert_unreachable();
2382 	}
2383 }
2384 
2385 /*
2386  * Returns 0 for success, errno for failure.
2387  */
2388 static void
2389 ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2390 		   struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2391 {
2392 	struct ctl_io_hdr *ioh;
2393 
2394 	mtx_lock(&lun->lun_lock);
2395 	ioh = LIST_FIRST(&lun->ooa_queue);
2396 	if (ioh == NULL) {
2397 		mtx_unlock(&lun->lun_lock);
2398 		return;
2399 	}
2400 	while (LIST_NEXT(ioh, ooa_links) != NULL)
2401 		ioh = LIST_NEXT(ioh, ooa_links);
2402 	for ( ; ioh; ioh = LIST_PREV(ioh, &lun->ooa_queue, ctl_io_hdr, ooa_links)) {
2403 		union ctl_io *io = (union ctl_io *)ioh;
2404 		struct ctl_ooa_entry *entry;
2405 
2406 		/*
2407 		 * If we've got more than we can fit, just count the
2408 		 * remaining entries.
2409 		 */
2410 		if (*cur_fill_num >= ooa_hdr->alloc_num) {
2411 			(*cur_fill_num)++;
2412 			continue;
2413 		}
2414 
2415 		entry = &kern_entries[*cur_fill_num];
2416 
2417 		entry->tag_num = io->scsiio.tag_num;
2418 		entry->lun_num = lun->lun;
2419 #ifdef CTL_TIME_IO
2420 		entry->start_bt = io->io_hdr.start_bt;
2421 #endif
2422 		bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2423 		entry->cdb_len = io->scsiio.cdb_len;
2424 		if (io->io_hdr.blocker != NULL)
2425 			entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2426 
2427 		if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2428 			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2429 
2430 		if (io->io_hdr.flags & CTL_FLAG_ABORT)
2431 			entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2432 
2433 		if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2434 			entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2435 
2436 		if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2437 			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2438 
2439 		if (io->io_hdr.flags & CTL_FLAG_STATUS_QUEUED)
2440 			entry->cmd_flags |= CTL_OOACMD_FLAG_STATUS_QUEUED;
2441 
2442 		if (io->io_hdr.flags & CTL_FLAG_STATUS_SENT)
2443 			entry->cmd_flags |= CTL_OOACMD_FLAG_STATUS_SENT;
2444 		(*cur_fill_num)++;
2445 	}
2446 	mtx_unlock(&lun->lun_lock);
2447 }
2448 
2449 /*
2450  * Escape characters that are illegal or not recommended in XML.
2451  */
2452 int
2453 ctl_sbuf_printf_esc(struct sbuf *sb, char *str, int size)
2454 {
2455 	char *end = str + size;
2456 	int retval;
2457 
2458 	retval = 0;
2459 
2460 	for (; *str && str < end; str++) {
2461 		switch (*str) {
2462 		case '&':
2463 			retval = sbuf_printf(sb, "&amp;");
2464 			break;
2465 		case '>':
2466 			retval = sbuf_printf(sb, "&gt;");
2467 			break;
2468 		case '<':
2469 			retval = sbuf_printf(sb, "&lt;");
2470 			break;
2471 		default:
2472 			retval = sbuf_putc(sb, *str);
2473 			break;
2474 		}
2475 
2476 		if (retval != 0)
2477 			break;
2478 	}
2479 
2480 	return (retval);
2481 }
2482 
2483 static void
2484 ctl_id_sbuf(struct ctl_devid *id, struct sbuf *sb)
2485 {
2486 	struct scsi_vpd_id_descriptor *desc;
2487 	int i;
2488 
2489 	if (id == NULL || id->len < 4)
2490 		return;
2491 	desc = (struct scsi_vpd_id_descriptor *)id->data;
2492 	switch (desc->id_type & SVPD_ID_TYPE_MASK) {
2493 	case SVPD_ID_TYPE_T10:
2494 		sbuf_printf(sb, "t10.");
2495 		break;
2496 	case SVPD_ID_TYPE_EUI64:
2497 		sbuf_printf(sb, "eui.");
2498 		break;
2499 	case SVPD_ID_TYPE_NAA:
2500 		sbuf_printf(sb, "naa.");
2501 		break;
2502 	case SVPD_ID_TYPE_SCSI_NAME:
2503 		break;
2504 	}
2505 	switch (desc->proto_codeset & SVPD_ID_CODESET_MASK) {
2506 	case SVPD_ID_CODESET_BINARY:
2507 		for (i = 0; i < desc->length; i++)
2508 			sbuf_printf(sb, "%02x", desc->identifier[i]);
2509 		break;
2510 	case SVPD_ID_CODESET_ASCII:
2511 		sbuf_printf(sb, "%.*s", (int)desc->length,
2512 		    (char *)desc->identifier);
2513 		break;
2514 	case SVPD_ID_CODESET_UTF8:
2515 		sbuf_printf(sb, "%s", (char *)desc->identifier);
2516 		break;
2517 	}
2518 }
2519 
2520 static int
2521 ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2522 	  struct thread *td)
2523 {
2524 	struct ctl_softc *softc = dev->si_drv1;
2525 	struct ctl_port *port;
2526 	struct ctl_lun *lun;
2527 	int retval;
2528 
2529 	retval = 0;
2530 
2531 	switch (cmd) {
2532 	case CTL_IO:
2533 		retval = ctl_ioctl_io(dev, cmd, addr, flag, td);
2534 		break;
2535 	case CTL_ENABLE_PORT:
2536 	case CTL_DISABLE_PORT:
2537 	case CTL_SET_PORT_WWNS: {
2538 		struct ctl_port *port;
2539 		struct ctl_port_entry *entry;
2540 
2541 		entry = (struct ctl_port_entry *)addr;
2542 
2543 		mtx_lock(&softc->ctl_lock);
2544 		STAILQ_FOREACH(port, &softc->port_list, links) {
2545 			int action, done;
2546 
2547 			if (port->targ_port < softc->port_min ||
2548 			    port->targ_port >= softc->port_max)
2549 				continue;
2550 
2551 			action = 0;
2552 			done = 0;
2553 			if ((entry->port_type == CTL_PORT_NONE)
2554 			 && (entry->targ_port == port->targ_port)) {
2555 				/*
2556 				 * If the user only wants to enable or
2557 				 * disable or set WWNs on a specific port,
2558 				 * do the operation and we're done.
2559 				 */
2560 				action = 1;
2561 				done = 1;
2562 			} else if (entry->port_type & port->port_type) {
2563 				/*
2564 				 * Compare the user's type mask with the
2565 				 * particular frontend type to see if we
2566 				 * have a match.
2567 				 */
2568 				action = 1;
2569 				done = 0;
2570 
2571 				/*
2572 				 * Make sure the user isn't trying to set
2573 				 * WWNs on multiple ports at the same time.
2574 				 */
2575 				if (cmd == CTL_SET_PORT_WWNS) {
2576 					printf("%s: Can't set WWNs on "
2577 					       "multiple ports\n", __func__);
2578 					retval = EINVAL;
2579 					break;
2580 				}
2581 			}
2582 			if (action == 0)
2583 				continue;
2584 
2585 			/*
2586 			 * XXX KDM we have to drop the lock here, because
2587 			 * the online/offline operations can potentially
2588 			 * block.  We need to reference count the frontends
2589 			 * so they can't go away,
2590 			 */
2591 			if (cmd == CTL_ENABLE_PORT) {
2592 				mtx_unlock(&softc->ctl_lock);
2593 				ctl_port_online(port);
2594 				mtx_lock(&softc->ctl_lock);
2595 			} else if (cmd == CTL_DISABLE_PORT) {
2596 				mtx_unlock(&softc->ctl_lock);
2597 				ctl_port_offline(port);
2598 				mtx_lock(&softc->ctl_lock);
2599 			} else if (cmd == CTL_SET_PORT_WWNS) {
2600 				ctl_port_set_wwns(port,
2601 				    (entry->flags & CTL_PORT_WWNN_VALID) ?
2602 				    1 : 0, entry->wwnn,
2603 				    (entry->flags & CTL_PORT_WWPN_VALID) ?
2604 				    1 : 0, entry->wwpn);
2605 			}
2606 			if (done != 0)
2607 				break;
2608 		}
2609 		mtx_unlock(&softc->ctl_lock);
2610 		break;
2611 	}
2612 	case CTL_GET_OOA: {
2613 		struct ctl_ooa *ooa_hdr;
2614 		struct ctl_ooa_entry *entries;
2615 		uint32_t cur_fill_num;
2616 
2617 		ooa_hdr = (struct ctl_ooa *)addr;
2618 
2619 		if ((ooa_hdr->alloc_len == 0)
2620 		 || (ooa_hdr->alloc_num == 0)) {
2621 			printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2622 			       "must be non-zero\n", __func__,
2623 			       ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2624 			retval = EINVAL;
2625 			break;
2626 		}
2627 
2628 		if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2629 		    sizeof(struct ctl_ooa_entry))) {
2630 			printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2631 			       "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2632 			       __func__, ooa_hdr->alloc_len,
2633 			       ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2634 			retval = EINVAL;
2635 			break;
2636 		}
2637 
2638 		entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2639 		if (entries == NULL) {
2640 			printf("%s: could not allocate %d bytes for OOA "
2641 			       "dump\n", __func__, ooa_hdr->alloc_len);
2642 			retval = ENOMEM;
2643 			break;
2644 		}
2645 
2646 		mtx_lock(&softc->ctl_lock);
2647 		if ((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0 &&
2648 		    (ooa_hdr->lun_num >= ctl_max_luns ||
2649 		     softc->ctl_luns[ooa_hdr->lun_num] == NULL)) {
2650 			mtx_unlock(&softc->ctl_lock);
2651 			free(entries, M_CTL);
2652 			printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2653 			       __func__, (uintmax_t)ooa_hdr->lun_num);
2654 			retval = EINVAL;
2655 			break;
2656 		}
2657 
2658 		cur_fill_num = 0;
2659 
2660 		if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2661 			STAILQ_FOREACH(lun, &softc->lun_list, links) {
2662 				ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2663 				    ooa_hdr, entries);
2664 			}
2665 		} else {
2666 			lun = softc->ctl_luns[ooa_hdr->lun_num];
2667 			ctl_ioctl_fill_ooa(lun, &cur_fill_num, ooa_hdr,
2668 			    entries);
2669 		}
2670 		mtx_unlock(&softc->ctl_lock);
2671 
2672 		ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2673 		ooa_hdr->fill_len = ooa_hdr->fill_num *
2674 			sizeof(struct ctl_ooa_entry);
2675 		retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2676 		if (retval != 0) {
2677 			printf("%s: error copying out %d bytes for OOA dump\n",
2678 			       __func__, ooa_hdr->fill_len);
2679 		}
2680 
2681 		getbinuptime(&ooa_hdr->cur_bt);
2682 
2683 		if (cur_fill_num > ooa_hdr->alloc_num) {
2684 			ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2685 			ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2686 		} else {
2687 			ooa_hdr->dropped_num = 0;
2688 			ooa_hdr->status = CTL_OOA_OK;
2689 		}
2690 
2691 		free(entries, M_CTL);
2692 		break;
2693 	}
2694 	case CTL_DELAY_IO: {
2695 		struct ctl_io_delay_info *delay_info;
2696 
2697 		delay_info = (struct ctl_io_delay_info *)addr;
2698 
2699 #ifdef CTL_IO_DELAY
2700 		mtx_lock(&softc->ctl_lock);
2701 		if (delay_info->lun_id >= ctl_max_luns ||
2702 		    (lun = softc->ctl_luns[delay_info->lun_id]) == NULL) {
2703 			mtx_unlock(&softc->ctl_lock);
2704 			delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2705 			break;
2706 		}
2707 		mtx_lock(&lun->lun_lock);
2708 		mtx_unlock(&softc->ctl_lock);
2709 		delay_info->status = CTL_DELAY_STATUS_OK;
2710 		switch (delay_info->delay_type) {
2711 		case CTL_DELAY_TYPE_CONT:
2712 		case CTL_DELAY_TYPE_ONESHOT:
2713 			break;
2714 		default:
2715 			delay_info->status = CTL_DELAY_STATUS_INVALID_TYPE;
2716 			break;
2717 		}
2718 		switch (delay_info->delay_loc) {
2719 		case CTL_DELAY_LOC_DATAMOVE:
2720 			lun->delay_info.datamove_type = delay_info->delay_type;
2721 			lun->delay_info.datamove_delay = delay_info->delay_secs;
2722 			break;
2723 		case CTL_DELAY_LOC_DONE:
2724 			lun->delay_info.done_type = delay_info->delay_type;
2725 			lun->delay_info.done_delay = delay_info->delay_secs;
2726 			break;
2727 		default:
2728 			delay_info->status = CTL_DELAY_STATUS_INVALID_LOC;
2729 			break;
2730 		}
2731 		mtx_unlock(&lun->lun_lock);
2732 #else
2733 		delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2734 #endif /* CTL_IO_DELAY */
2735 		break;
2736 	}
2737 	case CTL_ERROR_INJECT: {
2738 		struct ctl_error_desc *err_desc, *new_err_desc;
2739 
2740 		err_desc = (struct ctl_error_desc *)addr;
2741 
2742 		new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2743 				      M_WAITOK | M_ZERO);
2744 		bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2745 
2746 		mtx_lock(&softc->ctl_lock);
2747 		if (err_desc->lun_id >= ctl_max_luns ||
2748 		    (lun = softc->ctl_luns[err_desc->lun_id]) == NULL) {
2749 			mtx_unlock(&softc->ctl_lock);
2750 			free(new_err_desc, M_CTL);
2751 			printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
2752 			       __func__, (uintmax_t)err_desc->lun_id);
2753 			retval = EINVAL;
2754 			break;
2755 		}
2756 		mtx_lock(&lun->lun_lock);
2757 		mtx_unlock(&softc->ctl_lock);
2758 
2759 		/*
2760 		 * We could do some checking here to verify the validity
2761 		 * of the request, but given the complexity of error
2762 		 * injection requests, the checking logic would be fairly
2763 		 * complex.
2764 		 *
2765 		 * For now, if the request is invalid, it just won't get
2766 		 * executed and might get deleted.
2767 		 */
2768 		STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
2769 
2770 		/*
2771 		 * XXX KDM check to make sure the serial number is unique,
2772 		 * in case we somehow manage to wrap.  That shouldn't
2773 		 * happen for a very long time, but it's the right thing to
2774 		 * do.
2775 		 */
2776 		new_err_desc->serial = lun->error_serial;
2777 		err_desc->serial = lun->error_serial;
2778 		lun->error_serial++;
2779 
2780 		mtx_unlock(&lun->lun_lock);
2781 		break;
2782 	}
2783 	case CTL_ERROR_INJECT_DELETE: {
2784 		struct ctl_error_desc *delete_desc, *desc, *desc2;
2785 		int delete_done;
2786 
2787 		delete_desc = (struct ctl_error_desc *)addr;
2788 		delete_done = 0;
2789 
2790 		mtx_lock(&softc->ctl_lock);
2791 		if (delete_desc->lun_id >= ctl_max_luns ||
2792 		    (lun = softc->ctl_luns[delete_desc->lun_id]) == NULL) {
2793 			mtx_unlock(&softc->ctl_lock);
2794 			printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
2795 			       __func__, (uintmax_t)delete_desc->lun_id);
2796 			retval = EINVAL;
2797 			break;
2798 		}
2799 		mtx_lock(&lun->lun_lock);
2800 		mtx_unlock(&softc->ctl_lock);
2801 		STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
2802 			if (desc->serial != delete_desc->serial)
2803 				continue;
2804 
2805 			STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
2806 				      links);
2807 			free(desc, M_CTL);
2808 			delete_done = 1;
2809 		}
2810 		mtx_unlock(&lun->lun_lock);
2811 		if (delete_done == 0) {
2812 			printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
2813 			       "error serial %ju on LUN %u\n", __func__,
2814 			       delete_desc->serial, delete_desc->lun_id);
2815 			retval = EINVAL;
2816 			break;
2817 		}
2818 		break;
2819 	}
2820 	case CTL_DUMP_STRUCTS: {
2821 		int j, k;
2822 		struct ctl_port *port;
2823 		struct ctl_frontend *fe;
2824 
2825 		mtx_lock(&softc->ctl_lock);
2826 		printf("CTL Persistent Reservation information start:\n");
2827 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
2828 			mtx_lock(&lun->lun_lock);
2829 			if ((lun->flags & CTL_LUN_DISABLED) != 0) {
2830 				mtx_unlock(&lun->lun_lock);
2831 				continue;
2832 			}
2833 
2834 			for (j = 0; j < ctl_max_ports; j++) {
2835 				if (lun->pr_keys[j] == NULL)
2836 					continue;
2837 				for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
2838 					if (lun->pr_keys[j][k] == 0)
2839 						continue;
2840 					printf("  LUN %ju port %d iid %d key "
2841 					       "%#jx\n", lun->lun, j, k,
2842 					       (uintmax_t)lun->pr_keys[j][k]);
2843 				}
2844 			}
2845 			mtx_unlock(&lun->lun_lock);
2846 		}
2847 		printf("CTL Persistent Reservation information end\n");
2848 		printf("CTL Ports:\n");
2849 		STAILQ_FOREACH(port, &softc->port_list, links) {
2850 			printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
2851 			       "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
2852 			       port->frontend->name, port->port_type,
2853 			       port->physical_port, port->virtual_port,
2854 			       (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
2855 			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
2856 				if (port->wwpn_iid[j].in_use == 0 &&
2857 				    port->wwpn_iid[j].wwpn == 0 &&
2858 				    port->wwpn_iid[j].name == NULL)
2859 					continue;
2860 
2861 				printf("    iid %u use %d WWPN %#jx '%s'\n",
2862 				    j, port->wwpn_iid[j].in_use,
2863 				    (uintmax_t)port->wwpn_iid[j].wwpn,
2864 				    port->wwpn_iid[j].name);
2865 			}
2866 		}
2867 		printf("CTL Port information end\n");
2868 		mtx_unlock(&softc->ctl_lock);
2869 		/*
2870 		 * XXX KDM calling this without a lock.  We'd likely want
2871 		 * to drop the lock before calling the frontend's dump
2872 		 * routine anyway.
2873 		 */
2874 		printf("CTL Frontends:\n");
2875 		STAILQ_FOREACH(fe, &softc->fe_list, links) {
2876 			printf("  Frontend '%s'\n", fe->name);
2877 			if (fe->fe_dump != NULL)
2878 				fe->fe_dump();
2879 		}
2880 		printf("CTL Frontend information end\n");
2881 		break;
2882 	}
2883 	case CTL_LUN_REQ: {
2884 		struct ctl_lun_req *lun_req;
2885 		struct ctl_backend_driver *backend;
2886 		void *packed;
2887 		nvlist_t *tmp_args_nvl;
2888 		size_t packed_len;
2889 
2890 		lun_req = (struct ctl_lun_req *)addr;
2891 		tmp_args_nvl = lun_req->args_nvl;
2892 
2893 		backend = ctl_backend_find(lun_req->backend);
2894 		if (backend == NULL) {
2895 			lun_req->status = CTL_LUN_ERROR;
2896 			snprintf(lun_req->error_str,
2897 				 sizeof(lun_req->error_str),
2898 				 "Backend \"%s\" not found.",
2899 				 lun_req->backend);
2900 			break;
2901 		}
2902 
2903 		if (lun_req->args != NULL) {
2904 			packed = malloc(lun_req->args_len, M_CTL, M_WAITOK);
2905 			if (copyin(lun_req->args, packed, lun_req->args_len) != 0) {
2906 				free(packed, M_CTL);
2907 				lun_req->status = CTL_LUN_ERROR;
2908 				snprintf(lun_req->error_str, sizeof(lun_req->error_str),
2909 				    "Cannot copyin args.");
2910 				break;
2911 			}
2912 			lun_req->args_nvl = nvlist_unpack(packed,
2913 			    lun_req->args_len, 0);
2914 			free(packed, M_CTL);
2915 
2916 			if (lun_req->args_nvl == NULL) {
2917 				lun_req->status = CTL_LUN_ERROR;
2918 				snprintf(lun_req->error_str, sizeof(lun_req->error_str),
2919 				    "Cannot unpack args nvlist.");
2920 				break;
2921 			}
2922 		} else
2923 			lun_req->args_nvl = nvlist_create(0);
2924 
2925 		retval = backend->ioctl(dev, cmd, addr, flag, td);
2926 		nvlist_destroy(lun_req->args_nvl);
2927 		lun_req->args_nvl = tmp_args_nvl;
2928 
2929 		if (lun_req->result_nvl != NULL) {
2930 			if (lun_req->result != NULL) {
2931 				packed = nvlist_pack(lun_req->result_nvl,
2932 				    &packed_len);
2933 				if (packed == NULL) {
2934 					lun_req->status = CTL_LUN_ERROR;
2935 					snprintf(lun_req->error_str,
2936 					    sizeof(lun_req->error_str),
2937 					    "Cannot pack result nvlist.");
2938 					break;
2939 				}
2940 
2941 				if (packed_len > lun_req->result_len) {
2942 					lun_req->status = CTL_LUN_ERROR;
2943 					snprintf(lun_req->error_str,
2944 					    sizeof(lun_req->error_str),
2945 					    "Result nvlist too large.");
2946 					free(packed, M_NVLIST);
2947 					break;
2948 				}
2949 
2950 				if (copyout(packed, lun_req->result, packed_len)) {
2951 					lun_req->status = CTL_LUN_ERROR;
2952 					snprintf(lun_req->error_str,
2953 					    sizeof(lun_req->error_str),
2954 					    "Cannot copyout() the result.");
2955 					free(packed, M_NVLIST);
2956 					break;
2957 				}
2958 
2959 				lun_req->result_len = packed_len;
2960 				free(packed, M_NVLIST);
2961 			}
2962 
2963 			nvlist_destroy(lun_req->result_nvl);
2964 		}
2965 		break;
2966 	}
2967 	case CTL_LUN_LIST: {
2968 		struct sbuf *sb;
2969 		struct ctl_lun_list *list;
2970 		const char *name, *value;
2971 		void *cookie;
2972 		int type;
2973 
2974 		list = (struct ctl_lun_list *)addr;
2975 
2976 		/*
2977 		 * Allocate a fixed length sbuf here, based on the length
2978 		 * of the user's buffer.  We could allocate an auto-extending
2979 		 * buffer, and then tell the user how much larger our
2980 		 * amount of data is than his buffer, but that presents
2981 		 * some problems:
2982 		 *
2983 		 * 1.  The sbuf(9) routines use a blocking malloc, and so
2984 		 *     we can't hold a lock while calling them with an
2985 		 *     auto-extending buffer.
2986  		 *
2987 		 * 2.  There is not currently a LUN reference counting
2988 		 *     mechanism, outside of outstanding transactions on
2989 		 *     the LUN's OOA queue.  So a LUN could go away on us
2990 		 *     while we're getting the LUN number, backend-specific
2991 		 *     information, etc.  Thus, given the way things
2992 		 *     currently work, we need to hold the CTL lock while
2993 		 *     grabbing LUN information.
2994 		 *
2995 		 * So, from the user's standpoint, the best thing to do is
2996 		 * allocate what he thinks is a reasonable buffer length,
2997 		 * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
2998 		 * double the buffer length and try again.  (And repeat
2999 		 * that until he succeeds.)
3000 		 */
3001 		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3002 		if (sb == NULL) {
3003 			list->status = CTL_LUN_LIST_ERROR;
3004 			snprintf(list->error_str, sizeof(list->error_str),
3005 				 "Unable to allocate %d bytes for LUN list",
3006 				 list->alloc_len);
3007 			break;
3008 		}
3009 
3010 		sbuf_printf(sb, "<ctllunlist>\n");
3011 
3012 		mtx_lock(&softc->ctl_lock);
3013 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
3014 			mtx_lock(&lun->lun_lock);
3015 			retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3016 					     (uintmax_t)lun->lun);
3017 
3018 			/*
3019 			 * Bail out as soon as we see that we've overfilled
3020 			 * the buffer.
3021 			 */
3022 			if (retval != 0)
3023 				break;
3024 
3025 			retval = sbuf_printf(sb, "\t<backend_type>%s"
3026 					     "</backend_type>\n",
3027 					     (lun->backend == NULL) ?  "none" :
3028 					     lun->backend->name);
3029 
3030 			if (retval != 0)
3031 				break;
3032 
3033 			retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3034 					     lun->be_lun->lun_type);
3035 
3036 			if (retval != 0)
3037 				break;
3038 
3039 			if (lun->backend == NULL) {
3040 				retval = sbuf_printf(sb, "</lun>\n");
3041 				if (retval != 0)
3042 					break;
3043 				continue;
3044 			}
3045 
3046 			retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3047 					     (lun->be_lun->maxlba > 0) ?
3048 					     lun->be_lun->maxlba + 1 : 0);
3049 
3050 			if (retval != 0)
3051 				break;
3052 
3053 			retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3054 					     lun->be_lun->blocksize);
3055 
3056 			if (retval != 0)
3057 				break;
3058 
3059 			retval = sbuf_printf(sb, "\t<serial_number>");
3060 
3061 			if (retval != 0)
3062 				break;
3063 
3064 			retval = ctl_sbuf_printf_esc(sb,
3065 			    lun->be_lun->serial_num,
3066 			    sizeof(lun->be_lun->serial_num));
3067 
3068 			if (retval != 0)
3069 				break;
3070 
3071 			retval = sbuf_printf(sb, "</serial_number>\n");
3072 
3073 			if (retval != 0)
3074 				break;
3075 
3076 			retval = sbuf_printf(sb, "\t<device_id>");
3077 
3078 			if (retval != 0)
3079 				break;
3080 
3081 			retval = ctl_sbuf_printf_esc(sb,
3082 			    lun->be_lun->device_id,
3083 			    sizeof(lun->be_lun->device_id));
3084 
3085 			if (retval != 0)
3086 				break;
3087 
3088 			retval = sbuf_printf(sb, "</device_id>\n");
3089 
3090 			if (retval != 0)
3091 				break;
3092 
3093 			if (lun->backend->lun_info != NULL) {
3094 				retval = lun->backend->lun_info(lun->be_lun, sb);
3095 				if (retval != 0)
3096 					break;
3097 			}
3098 
3099 			cookie = NULL;
3100 			while ((name = nvlist_next(lun->be_lun->options, &type,
3101 			    &cookie)) != NULL) {
3102 				sbuf_printf(sb, "\t<%s>", name);
3103 
3104 				if (type == NV_TYPE_STRING) {
3105 					value = dnvlist_get_string(
3106 					    lun->be_lun->options, name, NULL);
3107 					if (value != NULL)
3108 						sbuf_printf(sb, "%s", value);
3109 				}
3110 
3111 				sbuf_printf(sb, "</%s>\n", name);
3112 			}
3113 
3114 			retval = sbuf_printf(sb, "</lun>\n");
3115 
3116 			if (retval != 0)
3117 				break;
3118 			mtx_unlock(&lun->lun_lock);
3119 		}
3120 		if (lun != NULL)
3121 			mtx_unlock(&lun->lun_lock);
3122 		mtx_unlock(&softc->ctl_lock);
3123 
3124 		if ((retval != 0)
3125 		 || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3126 			retval = 0;
3127 			sbuf_delete(sb);
3128 			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3129 			snprintf(list->error_str, sizeof(list->error_str),
3130 				 "Out of space, %d bytes is too small",
3131 				 list->alloc_len);
3132 			break;
3133 		}
3134 
3135 		sbuf_finish(sb);
3136 
3137 		retval = copyout(sbuf_data(sb), list->lun_xml,
3138 				 sbuf_len(sb) + 1);
3139 
3140 		list->fill_len = sbuf_len(sb) + 1;
3141 		list->status = CTL_LUN_LIST_OK;
3142 		sbuf_delete(sb);
3143 		break;
3144 	}
3145 	case CTL_ISCSI: {
3146 		struct ctl_iscsi *ci;
3147 		struct ctl_frontend *fe;
3148 
3149 		ci = (struct ctl_iscsi *)addr;
3150 
3151 		fe = ctl_frontend_find("iscsi");
3152 		if (fe == NULL) {
3153 			ci->status = CTL_ISCSI_ERROR;
3154 			snprintf(ci->error_str, sizeof(ci->error_str),
3155 			    "Frontend \"iscsi\" not found.");
3156 			break;
3157 		}
3158 
3159 		retval = fe->ioctl(dev, cmd, addr, flag, td);
3160 		break;
3161 	}
3162 	case CTL_PORT_REQ: {
3163 		struct ctl_req *req;
3164 		struct ctl_frontend *fe;
3165 		void *packed;
3166 		nvlist_t *tmp_args_nvl;
3167 		size_t packed_len;
3168 
3169 		req = (struct ctl_req *)addr;
3170 		tmp_args_nvl = req->args_nvl;
3171 
3172 		fe = ctl_frontend_find(req->driver);
3173 		if (fe == NULL) {
3174 			req->status = CTL_LUN_ERROR;
3175 			snprintf(req->error_str, sizeof(req->error_str),
3176 			    "Frontend \"%s\" not found.", req->driver);
3177 			break;
3178 		}
3179 
3180 		if (req->args != NULL) {
3181 			packed = malloc(req->args_len, M_CTL, M_WAITOK);
3182 			if (copyin(req->args, packed, req->args_len) != 0) {
3183 				free(packed, M_CTL);
3184 				req->status = CTL_LUN_ERROR;
3185 				snprintf(req->error_str, sizeof(req->error_str),
3186 				    "Cannot copyin args.");
3187 				break;
3188 			}
3189 			req->args_nvl = nvlist_unpack(packed,
3190 			    req->args_len, 0);
3191 			free(packed, M_CTL);
3192 
3193 			if (req->args_nvl == NULL) {
3194 				req->status = CTL_LUN_ERROR;
3195 				snprintf(req->error_str, sizeof(req->error_str),
3196 				    "Cannot unpack args nvlist.");
3197 				break;
3198 			}
3199 		} else
3200 			req->args_nvl = nvlist_create(0);
3201 
3202 		if (fe->ioctl)
3203 			retval = fe->ioctl(dev, cmd, addr, flag, td);
3204 		else
3205 			retval = ENODEV;
3206 
3207 		nvlist_destroy(req->args_nvl);
3208 		req->args_nvl = tmp_args_nvl;
3209 
3210 		if (req->result_nvl != NULL) {
3211 			if (req->result != NULL) {
3212 				packed = nvlist_pack(req->result_nvl,
3213 				    &packed_len);
3214 				if (packed == NULL) {
3215 					req->status = CTL_LUN_ERROR;
3216 					snprintf(req->error_str,
3217 					    sizeof(req->error_str),
3218 					    "Cannot pack result nvlist.");
3219 					break;
3220 				}
3221 
3222 				if (packed_len > req->result_len) {
3223 					req->status = CTL_LUN_ERROR;
3224 					snprintf(req->error_str,
3225 					    sizeof(req->error_str),
3226 					    "Result nvlist too large.");
3227 					free(packed, M_NVLIST);
3228 					break;
3229 				}
3230 
3231 				if (copyout(packed, req->result, packed_len)) {
3232 					req->status = CTL_LUN_ERROR;
3233 					snprintf(req->error_str,
3234 					    sizeof(req->error_str),
3235 					    "Cannot copyout() the result.");
3236 					free(packed, M_NVLIST);
3237 					break;
3238 				}
3239 
3240 				req->result_len = packed_len;
3241 				free(packed, M_NVLIST);
3242 			}
3243 
3244 			nvlist_destroy(req->result_nvl);
3245 		}
3246 		break;
3247 	}
3248 	case CTL_PORT_LIST: {
3249 		struct sbuf *sb;
3250 		struct ctl_port *port;
3251 		struct ctl_lun_list *list;
3252 		const char *name, *value;
3253 		void *cookie;
3254 		int j, type;
3255 		uint32_t plun;
3256 
3257 		list = (struct ctl_lun_list *)addr;
3258 
3259 		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3260 		if (sb == NULL) {
3261 			list->status = CTL_LUN_LIST_ERROR;
3262 			snprintf(list->error_str, sizeof(list->error_str),
3263 				 "Unable to allocate %d bytes for LUN list",
3264 				 list->alloc_len);
3265 			break;
3266 		}
3267 
3268 		sbuf_printf(sb, "<ctlportlist>\n");
3269 
3270 		mtx_lock(&softc->ctl_lock);
3271 		STAILQ_FOREACH(port, &softc->port_list, links) {
3272 			retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3273 					     (uintmax_t)port->targ_port);
3274 
3275 			/*
3276 			 * Bail out as soon as we see that we've overfilled
3277 			 * the buffer.
3278 			 */
3279 			if (retval != 0)
3280 				break;
3281 
3282 			retval = sbuf_printf(sb, "\t<frontend_type>%s"
3283 			    "</frontend_type>\n", port->frontend->name);
3284 			if (retval != 0)
3285 				break;
3286 
3287 			retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3288 					     port->port_type);
3289 			if (retval != 0)
3290 				break;
3291 
3292 			retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3293 			    (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3294 			if (retval != 0)
3295 				break;
3296 
3297 			retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3298 			    port->port_name);
3299 			if (retval != 0)
3300 				break;
3301 
3302 			retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3303 			    port->physical_port);
3304 			if (retval != 0)
3305 				break;
3306 
3307 			retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3308 			    port->virtual_port);
3309 			if (retval != 0)
3310 				break;
3311 
3312 			if (port->target_devid != NULL) {
3313 				sbuf_printf(sb, "\t<target>");
3314 				ctl_id_sbuf(port->target_devid, sb);
3315 				sbuf_printf(sb, "</target>\n");
3316 			}
3317 
3318 			if (port->port_devid != NULL) {
3319 				sbuf_printf(sb, "\t<port>");
3320 				ctl_id_sbuf(port->port_devid, sb);
3321 				sbuf_printf(sb, "</port>\n");
3322 			}
3323 
3324 			if (port->port_info != NULL) {
3325 				retval = port->port_info(port->onoff_arg, sb);
3326 				if (retval != 0)
3327 					break;
3328 			}
3329 
3330 			cookie = NULL;
3331 			while ((name = nvlist_next(port->options, &type,
3332 			    &cookie)) != NULL) {
3333 				sbuf_printf(sb, "\t<%s>", name);
3334 
3335 				if (type == NV_TYPE_STRING) {
3336 					value = dnvlist_get_string(port->options,
3337 					    name, NULL);
3338 					if (value != NULL)
3339 						sbuf_printf(sb, "%s", value);
3340 				}
3341 
3342 				sbuf_printf(sb, "</%s>\n", name);
3343 			}
3344 
3345 			if (port->lun_map != NULL) {
3346 				sbuf_printf(sb, "\t<lun_map>on</lun_map>\n");
3347 				for (j = 0; j < port->lun_map_size; j++) {
3348 					plun = ctl_lun_map_from_port(port, j);
3349 					if (plun == UINT32_MAX)
3350 						continue;
3351 					sbuf_printf(sb,
3352 					    "\t<lun id=\"%u\">%u</lun>\n",
3353 					    j, plun);
3354 				}
3355 			}
3356 
3357 			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3358 				if (port->wwpn_iid[j].in_use == 0 ||
3359 				    (port->wwpn_iid[j].wwpn == 0 &&
3360 				     port->wwpn_iid[j].name == NULL))
3361 					continue;
3362 
3363 				if (port->wwpn_iid[j].name != NULL)
3364 					retval = sbuf_printf(sb,
3365 					    "\t<initiator id=\"%u\">%s</initiator>\n",
3366 					    j, port->wwpn_iid[j].name);
3367 				else
3368 					retval = sbuf_printf(sb,
3369 					    "\t<initiator id=\"%u\">naa.%08jx</initiator>\n",
3370 					    j, port->wwpn_iid[j].wwpn);
3371 				if (retval != 0)
3372 					break;
3373 			}
3374 			if (retval != 0)
3375 				break;
3376 
3377 			retval = sbuf_printf(sb, "</targ_port>\n");
3378 			if (retval != 0)
3379 				break;
3380 		}
3381 		mtx_unlock(&softc->ctl_lock);
3382 
3383 		if ((retval != 0)
3384 		 || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3385 			retval = 0;
3386 			sbuf_delete(sb);
3387 			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3388 			snprintf(list->error_str, sizeof(list->error_str),
3389 				 "Out of space, %d bytes is too small",
3390 				 list->alloc_len);
3391 			break;
3392 		}
3393 
3394 		sbuf_finish(sb);
3395 
3396 		retval = copyout(sbuf_data(sb), list->lun_xml,
3397 				 sbuf_len(sb) + 1);
3398 
3399 		list->fill_len = sbuf_len(sb) + 1;
3400 		list->status = CTL_LUN_LIST_OK;
3401 		sbuf_delete(sb);
3402 		break;
3403 	}
3404 	case CTL_LUN_MAP: {
3405 		struct ctl_lun_map *lm  = (struct ctl_lun_map *)addr;
3406 		struct ctl_port *port;
3407 
3408 		mtx_lock(&softc->ctl_lock);
3409 		if (lm->port < softc->port_min ||
3410 		    lm->port >= softc->port_max ||
3411 		    (port = softc->ctl_ports[lm->port]) == NULL) {
3412 			mtx_unlock(&softc->ctl_lock);
3413 			return (ENXIO);
3414 		}
3415 		if (port->status & CTL_PORT_STATUS_ONLINE) {
3416 			STAILQ_FOREACH(lun, &softc->lun_list, links) {
3417 				if (ctl_lun_map_to_port(port, lun->lun) ==
3418 				    UINT32_MAX)
3419 					continue;
3420 				mtx_lock(&lun->lun_lock);
3421 				ctl_est_ua_port(lun, lm->port, -1,
3422 				    CTL_UA_LUN_CHANGE);
3423 				mtx_unlock(&lun->lun_lock);
3424 			}
3425 		}
3426 		mtx_unlock(&softc->ctl_lock); // XXX: port_enable sleeps
3427 		if (lm->plun != UINT32_MAX) {
3428 			if (lm->lun == UINT32_MAX)
3429 				retval = ctl_lun_map_unset(port, lm->plun);
3430 			else if (lm->lun < ctl_max_luns &&
3431 			    softc->ctl_luns[lm->lun] != NULL)
3432 				retval = ctl_lun_map_set(port, lm->plun, lm->lun);
3433 			else
3434 				return (ENXIO);
3435 		} else {
3436 			if (lm->lun == UINT32_MAX)
3437 				retval = ctl_lun_map_deinit(port);
3438 			else
3439 				retval = ctl_lun_map_init(port);
3440 		}
3441 		if (port->status & CTL_PORT_STATUS_ONLINE)
3442 			ctl_isc_announce_port(port);
3443 		break;
3444 	}
3445 	case CTL_GET_LUN_STATS: {
3446 		struct ctl_get_io_stats *stats = (struct ctl_get_io_stats *)addr;
3447 		int i;
3448 
3449 		/*
3450 		 * XXX KDM no locking here.  If the LUN list changes,
3451 		 * things can blow up.
3452 		 */
3453 		i = 0;
3454 		stats->status = CTL_SS_OK;
3455 		stats->fill_len = 0;
3456 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
3457 			if (lun->lun < stats->first_item)
3458 				continue;
3459 			if (stats->fill_len + sizeof(lun->stats) >
3460 			    stats->alloc_len) {
3461 				stats->status = CTL_SS_NEED_MORE_SPACE;
3462 				break;
3463 			}
3464 			retval = copyout(&lun->stats, &stats->stats[i++],
3465 					 sizeof(lun->stats));
3466 			if (retval != 0)
3467 				break;
3468 			stats->fill_len += sizeof(lun->stats);
3469 		}
3470 		stats->num_items = softc->num_luns;
3471 		stats->flags = CTL_STATS_FLAG_NONE;
3472 #ifdef CTL_TIME_IO
3473 		stats->flags |= CTL_STATS_FLAG_TIME_VALID;
3474 #endif
3475 		getnanouptime(&stats->timestamp);
3476 		break;
3477 	}
3478 	case CTL_GET_PORT_STATS: {
3479 		struct ctl_get_io_stats *stats = (struct ctl_get_io_stats *)addr;
3480 		int i;
3481 
3482 		/*
3483 		 * XXX KDM no locking here.  If the LUN list changes,
3484 		 * things can blow up.
3485 		 */
3486 		i = 0;
3487 		stats->status = CTL_SS_OK;
3488 		stats->fill_len = 0;
3489 		STAILQ_FOREACH(port, &softc->port_list, links) {
3490 			if (port->targ_port < stats->first_item)
3491 				continue;
3492 			if (stats->fill_len + sizeof(port->stats) >
3493 			    stats->alloc_len) {
3494 				stats->status = CTL_SS_NEED_MORE_SPACE;
3495 				break;
3496 			}
3497 			retval = copyout(&port->stats, &stats->stats[i++],
3498 					 sizeof(port->stats));
3499 			if (retval != 0)
3500 				break;
3501 			stats->fill_len += sizeof(port->stats);
3502 		}
3503 		stats->num_items = softc->num_ports;
3504 		stats->flags = CTL_STATS_FLAG_NONE;
3505 #ifdef CTL_TIME_IO
3506 		stats->flags |= CTL_STATS_FLAG_TIME_VALID;
3507 #endif
3508 		getnanouptime(&stats->timestamp);
3509 		break;
3510 	}
3511 	default: {
3512 		/* XXX KDM should we fix this? */
3513 #if 0
3514 		struct ctl_backend_driver *backend;
3515 		unsigned int type;
3516 		int found;
3517 
3518 		found = 0;
3519 
3520 		/*
3521 		 * We encode the backend type as the ioctl type for backend
3522 		 * ioctls.  So parse it out here, and then search for a
3523 		 * backend of this type.
3524 		 */
3525 		type = _IOC_TYPE(cmd);
3526 
3527 		STAILQ_FOREACH(backend, &softc->be_list, links) {
3528 			if (backend->type == type) {
3529 				found = 1;
3530 				break;
3531 			}
3532 		}
3533 		if (found == 0) {
3534 			printf("ctl: unknown ioctl command %#lx or backend "
3535 			       "%d\n", cmd, type);
3536 			retval = EINVAL;
3537 			break;
3538 		}
3539 		retval = backend->ioctl(dev, cmd, addr, flag, td);
3540 #endif
3541 		retval = ENOTTY;
3542 		break;
3543 	}
3544 	}
3545 	return (retval);
3546 }
3547 
3548 uint32_t
3549 ctl_get_initindex(struct ctl_nexus *nexus)
3550 {
3551 	return (nexus->initid + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3552 }
3553 
3554 int
3555 ctl_lun_map_init(struct ctl_port *port)
3556 {
3557 	struct ctl_softc *softc = port->ctl_softc;
3558 	struct ctl_lun *lun;
3559 	int size = ctl_lun_map_size;
3560 	uint32_t i;
3561 
3562 	if (port->lun_map == NULL || port->lun_map_size < size) {
3563 		port->lun_map_size = 0;
3564 		free(port->lun_map, M_CTL);
3565 		port->lun_map = malloc(size * sizeof(uint32_t),
3566 		    M_CTL, M_NOWAIT);
3567 	}
3568 	if (port->lun_map == NULL)
3569 		return (ENOMEM);
3570 	for (i = 0; i < size; i++)
3571 		port->lun_map[i] = UINT32_MAX;
3572 	port->lun_map_size = size;
3573 	if (port->status & CTL_PORT_STATUS_ONLINE) {
3574 		if (port->lun_disable != NULL) {
3575 			STAILQ_FOREACH(lun, &softc->lun_list, links)
3576 				port->lun_disable(port->targ_lun_arg, lun->lun);
3577 		}
3578 		ctl_isc_announce_port(port);
3579 	}
3580 	return (0);
3581 }
3582 
3583 int
3584 ctl_lun_map_deinit(struct ctl_port *port)
3585 {
3586 	struct ctl_softc *softc = port->ctl_softc;
3587 	struct ctl_lun *lun;
3588 
3589 	if (port->lun_map == NULL)
3590 		return (0);
3591 	port->lun_map_size = 0;
3592 	free(port->lun_map, M_CTL);
3593 	port->lun_map = NULL;
3594 	if (port->status & CTL_PORT_STATUS_ONLINE) {
3595 		if (port->lun_enable != NULL) {
3596 			STAILQ_FOREACH(lun, &softc->lun_list, links)
3597 				port->lun_enable(port->targ_lun_arg, lun->lun);
3598 		}
3599 		ctl_isc_announce_port(port);
3600 	}
3601 	return (0);
3602 }
3603 
3604 int
3605 ctl_lun_map_set(struct ctl_port *port, uint32_t plun, uint32_t glun)
3606 {
3607 	int status;
3608 	uint32_t old;
3609 
3610 	if (port->lun_map == NULL) {
3611 		status = ctl_lun_map_init(port);
3612 		if (status != 0)
3613 			return (status);
3614 	}
3615 	if (plun >= port->lun_map_size)
3616 		return (EINVAL);
3617 	old = port->lun_map[plun];
3618 	port->lun_map[plun] = glun;
3619 	if ((port->status & CTL_PORT_STATUS_ONLINE) && old == UINT32_MAX) {
3620 		if (port->lun_enable != NULL)
3621 			port->lun_enable(port->targ_lun_arg, plun);
3622 		ctl_isc_announce_port(port);
3623 	}
3624 	return (0);
3625 }
3626 
3627 int
3628 ctl_lun_map_unset(struct ctl_port *port, uint32_t plun)
3629 {
3630 	uint32_t old;
3631 
3632 	if (port->lun_map == NULL || plun >= port->lun_map_size)
3633 		return (0);
3634 	old = port->lun_map[plun];
3635 	port->lun_map[plun] = UINT32_MAX;
3636 	if ((port->status & CTL_PORT_STATUS_ONLINE) && old != UINT32_MAX) {
3637 		if (port->lun_disable != NULL)
3638 			port->lun_disable(port->targ_lun_arg, plun);
3639 		ctl_isc_announce_port(port);
3640 	}
3641 	return (0);
3642 }
3643 
3644 uint32_t
3645 ctl_lun_map_from_port(struct ctl_port *port, uint32_t lun_id)
3646 {
3647 
3648 	if (port == NULL)
3649 		return (UINT32_MAX);
3650 	if (port->lun_map == NULL)
3651 		return (lun_id);
3652 	if (lun_id > port->lun_map_size)
3653 		return (UINT32_MAX);
3654 	return (port->lun_map[lun_id]);
3655 }
3656 
3657 uint32_t
3658 ctl_lun_map_to_port(struct ctl_port *port, uint32_t lun_id)
3659 {
3660 	uint32_t i;
3661 
3662 	if (port == NULL)
3663 		return (UINT32_MAX);
3664 	if (port->lun_map == NULL)
3665 		return (lun_id);
3666 	for (i = 0; i < port->lun_map_size; i++) {
3667 		if (port->lun_map[i] == lun_id)
3668 			return (i);
3669 	}
3670 	return (UINT32_MAX);
3671 }
3672 
3673 uint32_t
3674 ctl_decode_lun(uint64_t encoded)
3675 {
3676 	uint8_t lun[8];
3677 	uint32_t result = 0xffffffff;
3678 
3679 	be64enc(lun, encoded);
3680 	switch (lun[0] & RPL_LUNDATA_ATYP_MASK) {
3681 	case RPL_LUNDATA_ATYP_PERIPH:
3682 		if ((lun[0] & 0x3f) == 0 && lun[2] == 0 && lun[3] == 0 &&
3683 		    lun[4] == 0 && lun[5] == 0 && lun[6] == 0 && lun[7] == 0)
3684 			result = lun[1];
3685 		break;
3686 	case RPL_LUNDATA_ATYP_FLAT:
3687 		if (lun[2] == 0 && lun[3] == 0 && lun[4] == 0 && lun[5] == 0 &&
3688 		    lun[6] == 0 && lun[7] == 0)
3689 			result = ((lun[0] & 0x3f) << 8) + lun[1];
3690 		break;
3691 	case RPL_LUNDATA_ATYP_EXTLUN:
3692 		switch (lun[0] & RPL_LUNDATA_EXT_EAM_MASK) {
3693 		case 0x02:
3694 			switch (lun[0] & RPL_LUNDATA_EXT_LEN_MASK) {
3695 			case 0x00:
3696 				result = lun[1];
3697 				break;
3698 			case 0x10:
3699 				result = (lun[1] << 16) + (lun[2] << 8) +
3700 				    lun[3];
3701 				break;
3702 			case 0x20:
3703 				if (lun[1] == 0 && lun[6] == 0 && lun[7] == 0)
3704 					result = (lun[2] << 24) +
3705 					    (lun[3] << 16) + (lun[4] << 8) +
3706 					    lun[5];
3707 				break;
3708 			}
3709 			break;
3710 		case RPL_LUNDATA_EXT_EAM_NOT_SPEC:
3711 			result = 0xffffffff;
3712 			break;
3713 		}
3714 		break;
3715 	}
3716 	return (result);
3717 }
3718 
3719 uint64_t
3720 ctl_encode_lun(uint32_t decoded)
3721 {
3722 	uint64_t l = decoded;
3723 
3724 	if (l <= 0xff)
3725 		return (((uint64_t)RPL_LUNDATA_ATYP_PERIPH << 56) | (l << 48));
3726 	if (l <= 0x3fff)
3727 		return (((uint64_t)RPL_LUNDATA_ATYP_FLAT << 56) | (l << 48));
3728 	if (l <= 0xffffff)
3729 		return (((uint64_t)(RPL_LUNDATA_ATYP_EXTLUN | 0x12) << 56) |
3730 		    (l << 32));
3731 	return ((((uint64_t)RPL_LUNDATA_ATYP_EXTLUN | 0x22) << 56) | (l << 16));
3732 }
3733 
3734 int
3735 ctl_ffz(uint32_t *mask, uint32_t first, uint32_t last)
3736 {
3737 	int i;
3738 
3739 	for (i = first; i < last; i++) {
3740 		if ((mask[i / 32] & (1 << (i % 32))) == 0)
3741 			return (i);
3742 	}
3743 	return (-1);
3744 }
3745 
3746 int
3747 ctl_set_mask(uint32_t *mask, uint32_t bit)
3748 {
3749 	uint32_t chunk, piece;
3750 
3751 	chunk = bit >> 5;
3752 	piece = bit % (sizeof(uint32_t) * 8);
3753 
3754 	if ((mask[chunk] & (1 << piece)) != 0)
3755 		return (-1);
3756 	else
3757 		mask[chunk] |= (1 << piece);
3758 
3759 	return (0);
3760 }
3761 
3762 int
3763 ctl_clear_mask(uint32_t *mask, uint32_t bit)
3764 {
3765 	uint32_t chunk, piece;
3766 
3767 	chunk = bit >> 5;
3768 	piece = bit % (sizeof(uint32_t) * 8);
3769 
3770 	if ((mask[chunk] & (1 << piece)) == 0)
3771 		return (-1);
3772 	else
3773 		mask[chunk] &= ~(1 << piece);
3774 
3775 	return (0);
3776 }
3777 
3778 int
3779 ctl_is_set(uint32_t *mask, uint32_t bit)
3780 {
3781 	uint32_t chunk, piece;
3782 
3783 	chunk = bit >> 5;
3784 	piece = bit % (sizeof(uint32_t) * 8);
3785 
3786 	if ((mask[chunk] & (1 << piece)) == 0)
3787 		return (0);
3788 	else
3789 		return (1);
3790 }
3791 
3792 static uint64_t
3793 ctl_get_prkey(struct ctl_lun *lun, uint32_t residx)
3794 {
3795 	uint64_t *t;
3796 
3797 	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3798 	if (t == NULL)
3799 		return (0);
3800 	return (t[residx % CTL_MAX_INIT_PER_PORT]);
3801 }
3802 
3803 static void
3804 ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx)
3805 {
3806 	uint64_t *t;
3807 
3808 	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3809 	if (t == NULL)
3810 		return;
3811 	t[residx % CTL_MAX_INIT_PER_PORT] = 0;
3812 }
3813 
3814 static void
3815 ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx)
3816 {
3817 	uint64_t *p;
3818 	u_int i;
3819 
3820 	i = residx/CTL_MAX_INIT_PER_PORT;
3821 	if (lun->pr_keys[i] != NULL)
3822 		return;
3823 	mtx_unlock(&lun->lun_lock);
3824 	p = malloc(sizeof(uint64_t) * CTL_MAX_INIT_PER_PORT, M_CTL,
3825 	    M_WAITOK | M_ZERO);
3826 	mtx_lock(&lun->lun_lock);
3827 	if (lun->pr_keys[i] == NULL)
3828 		lun->pr_keys[i] = p;
3829 	else
3830 		free(p, M_CTL);
3831 }
3832 
3833 static void
3834 ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key)
3835 {
3836 	uint64_t *t;
3837 
3838 	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3839 	KASSERT(t != NULL, ("prkey %d is not allocated", residx));
3840 	t[residx % CTL_MAX_INIT_PER_PORT] = key;
3841 }
3842 
3843 /*
3844  * ctl_softc, pool_name, total_ctl_io are passed in.
3845  * npool is passed out.
3846  */
3847 int
3848 ctl_pool_create(struct ctl_softc *ctl_softc, const char *pool_name,
3849 		uint32_t total_ctl_io, void **npool)
3850 {
3851 	struct ctl_io_pool *pool;
3852 
3853 	pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3854 					    M_NOWAIT | M_ZERO);
3855 	if (pool == NULL)
3856 		return (ENOMEM);
3857 
3858 	snprintf(pool->name, sizeof(pool->name), "CTL IO %s", pool_name);
3859 	pool->ctl_softc = ctl_softc;
3860 #ifdef IO_POOLS
3861 	pool->zone = uma_zsecond_create(pool->name, NULL,
3862 	    NULL, NULL, NULL, ctl_softc->io_zone);
3863 	/* uma_prealloc(pool->zone, total_ctl_io); */
3864 #else
3865 	pool->zone = ctl_softc->io_zone;
3866 #endif
3867 
3868 	*npool = pool;
3869 	return (0);
3870 }
3871 
3872 void
3873 ctl_pool_free(struct ctl_io_pool *pool)
3874 {
3875 
3876 	if (pool == NULL)
3877 		return;
3878 
3879 #ifdef IO_POOLS
3880 	uma_zdestroy(pool->zone);
3881 #endif
3882 	free(pool, M_CTL);
3883 }
3884 
3885 union ctl_io *
3886 ctl_alloc_io(void *pool_ref)
3887 {
3888 	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3889 	union ctl_io *io;
3890 
3891 	io = uma_zalloc(pool->zone, M_WAITOK);
3892 	if (io != NULL) {
3893 		io->io_hdr.pool = pool_ref;
3894 		CTL_SOFTC(io) = pool->ctl_softc;
3895 		TAILQ_INIT(&io->io_hdr.blocked_queue);
3896 	}
3897 	return (io);
3898 }
3899 
3900 union ctl_io *
3901 ctl_alloc_io_nowait(void *pool_ref)
3902 {
3903 	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3904 	union ctl_io *io;
3905 
3906 	io = uma_zalloc(pool->zone, M_NOWAIT);
3907 	if (io != NULL) {
3908 		io->io_hdr.pool = pool_ref;
3909 		CTL_SOFTC(io) = pool->ctl_softc;
3910 		TAILQ_INIT(&io->io_hdr.blocked_queue);
3911 	}
3912 	return (io);
3913 }
3914 
3915 void
3916 ctl_free_io(union ctl_io *io)
3917 {
3918 	struct ctl_io_pool *pool;
3919 
3920 	if (io == NULL)
3921 		return;
3922 
3923 	pool = (struct ctl_io_pool *)io->io_hdr.pool;
3924 	uma_zfree(pool->zone, io);
3925 }
3926 
3927 void
3928 ctl_zero_io(union ctl_io *io)
3929 {
3930 	struct ctl_io_pool *pool;
3931 
3932 	if (io == NULL)
3933 		return;
3934 
3935 	/*
3936 	 * May need to preserve linked list pointers at some point too.
3937 	 */
3938 	pool = io->io_hdr.pool;
3939 	memset(io, 0, sizeof(*io));
3940 	io->io_hdr.pool = pool;
3941 	CTL_SOFTC(io) = pool->ctl_softc;
3942 	TAILQ_INIT(&io->io_hdr.blocked_queue);
3943 }
3944 
3945 int
3946 ctl_expand_number(const char *buf, uint64_t *num)
3947 {
3948 	char *endptr;
3949 	uint64_t number;
3950 	unsigned shift;
3951 
3952 	number = strtoq(buf, &endptr, 0);
3953 
3954 	switch (tolower((unsigned char)*endptr)) {
3955 	case 'e':
3956 		shift = 60;
3957 		break;
3958 	case 'p':
3959 		shift = 50;
3960 		break;
3961 	case 't':
3962 		shift = 40;
3963 		break;
3964 	case 'g':
3965 		shift = 30;
3966 		break;
3967 	case 'm':
3968 		shift = 20;
3969 		break;
3970 	case 'k':
3971 		shift = 10;
3972 		break;
3973 	case 'b':
3974 	case '\0': /* No unit. */
3975 		*num = number;
3976 		return (0);
3977 	default:
3978 		/* Unrecognized unit. */
3979 		return (-1);
3980 	}
3981 
3982 	if ((number << shift) >> shift != number) {
3983 		/* Overflow */
3984 		return (-1);
3985 	}
3986 	*num = number << shift;
3987 	return (0);
3988 }
3989 
3990 /*
3991  * This routine could be used in the future to load default and/or saved
3992  * mode page parameters for a particuar lun.
3993  */
3994 static int
3995 ctl_init_page_index(struct ctl_lun *lun)
3996 {
3997 	int i, page_code;
3998 	struct ctl_page_index *page_index;
3999 	const char *value;
4000 	uint64_t ival;
4001 
4002 	memcpy(&lun->mode_pages.index, page_index_template,
4003 	       sizeof(page_index_template));
4004 
4005 	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
4006 		page_index = &lun->mode_pages.index[i];
4007 		if (lun->be_lun->lun_type == T_DIRECT &&
4008 		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
4009 			continue;
4010 		if (lun->be_lun->lun_type == T_PROCESSOR &&
4011 		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
4012 			continue;
4013 		if (lun->be_lun->lun_type == T_CDROM &&
4014 		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
4015 			continue;
4016 
4017 		page_code = page_index->page_code & SMPH_PC_MASK;
4018 		switch (page_code) {
4019 		case SMS_RW_ERROR_RECOVERY_PAGE: {
4020 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4021 			    ("subpage %#x for page %#x is incorrect!",
4022 			    page_index->subpage, page_code));
4023 			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT],
4024 			       &rw_er_page_default,
4025 			       sizeof(rw_er_page_default));
4026 			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CHANGEABLE],
4027 			       &rw_er_page_changeable,
4028 			       sizeof(rw_er_page_changeable));
4029 			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_DEFAULT],
4030 			       &rw_er_page_default,
4031 			       sizeof(rw_er_page_default));
4032 			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_SAVED],
4033 			       &rw_er_page_default,
4034 			       sizeof(rw_er_page_default));
4035 			page_index->page_data =
4036 				(uint8_t *)lun->mode_pages.rw_er_page;
4037 			break;
4038 		}
4039 		case SMS_FORMAT_DEVICE_PAGE: {
4040 			struct scsi_format_page *format_page;
4041 
4042 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4043 			    ("subpage %#x for page %#x is incorrect!",
4044 			    page_index->subpage, page_code));
4045 
4046 			/*
4047 			 * Sectors per track are set above.  Bytes per
4048 			 * sector need to be set here on a per-LUN basis.
4049 			 */
4050 			memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
4051 			       &format_page_default,
4052 			       sizeof(format_page_default));
4053 			memcpy(&lun->mode_pages.format_page[
4054 			       CTL_PAGE_CHANGEABLE], &format_page_changeable,
4055 			       sizeof(format_page_changeable));
4056 			memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
4057 			       &format_page_default,
4058 			       sizeof(format_page_default));
4059 			memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
4060 			       &format_page_default,
4061 			       sizeof(format_page_default));
4062 
4063 			format_page = &lun->mode_pages.format_page[
4064 				CTL_PAGE_CURRENT];
4065 			scsi_ulto2b(lun->be_lun->blocksize,
4066 				    format_page->bytes_per_sector);
4067 
4068 			format_page = &lun->mode_pages.format_page[
4069 				CTL_PAGE_DEFAULT];
4070 			scsi_ulto2b(lun->be_lun->blocksize,
4071 				    format_page->bytes_per_sector);
4072 
4073 			format_page = &lun->mode_pages.format_page[
4074 				CTL_PAGE_SAVED];
4075 			scsi_ulto2b(lun->be_lun->blocksize,
4076 				    format_page->bytes_per_sector);
4077 
4078 			page_index->page_data =
4079 				(uint8_t *)lun->mode_pages.format_page;
4080 			break;
4081 		}
4082 		case SMS_RIGID_DISK_PAGE: {
4083 			struct scsi_rigid_disk_page *rigid_disk_page;
4084 			uint32_t sectors_per_cylinder;
4085 			uint64_t cylinders;
4086 #ifndef	__XSCALE__
4087 			int shift;
4088 #endif /* !__XSCALE__ */
4089 
4090 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4091 			    ("subpage %#x for page %#x is incorrect!",
4092 			    page_index->subpage, page_code));
4093 
4094 			/*
4095 			 * Rotation rate and sectors per track are set
4096 			 * above.  We calculate the cylinders here based on
4097 			 * capacity.  Due to the number of heads and
4098 			 * sectors per track we're using, smaller arrays
4099 			 * may turn out to have 0 cylinders.  Linux and
4100 			 * FreeBSD don't pay attention to these mode pages
4101 			 * to figure out capacity, but Solaris does.  It
4102 			 * seems to deal with 0 cylinders just fine, and
4103 			 * works out a fake geometry based on the capacity.
4104 			 */
4105 			memcpy(&lun->mode_pages.rigid_disk_page[
4106 			       CTL_PAGE_DEFAULT], &rigid_disk_page_default,
4107 			       sizeof(rigid_disk_page_default));
4108 			memcpy(&lun->mode_pages.rigid_disk_page[
4109 			       CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
4110 			       sizeof(rigid_disk_page_changeable));
4111 
4112 			sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
4113 				CTL_DEFAULT_HEADS;
4114 
4115 			/*
4116 			 * The divide method here will be more accurate,
4117 			 * probably, but results in floating point being
4118 			 * used in the kernel on i386 (__udivdi3()).  On the
4119 			 * XScale, though, __udivdi3() is implemented in
4120 			 * software.
4121 			 *
4122 			 * The shift method for cylinder calculation is
4123 			 * accurate if sectors_per_cylinder is a power of
4124 			 * 2.  Otherwise it might be slightly off -- you
4125 			 * might have a bit of a truncation problem.
4126 			 */
4127 #ifdef	__XSCALE__
4128 			cylinders = (lun->be_lun->maxlba + 1) /
4129 				sectors_per_cylinder;
4130 #else
4131 			for (shift = 31; shift > 0; shift--) {
4132 				if (sectors_per_cylinder & (1 << shift))
4133 					break;
4134 			}
4135 			cylinders = (lun->be_lun->maxlba + 1) >> shift;
4136 #endif
4137 
4138 			/*
4139 			 * We've basically got 3 bytes, or 24 bits for the
4140 			 * cylinder size in the mode page.  If we're over,
4141 			 * just round down to 2^24.
4142 			 */
4143 			if (cylinders > 0xffffff)
4144 				cylinders = 0xffffff;
4145 
4146 			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4147 				CTL_PAGE_DEFAULT];
4148 			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4149 
4150 			if ((value = dnvlist_get_string(lun->be_lun->options,
4151 			    "rpm", NULL)) != NULL) {
4152 				scsi_ulto2b(strtol(value, NULL, 0),
4153 				     rigid_disk_page->rotation_rate);
4154 			}
4155 
4156 			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_CURRENT],
4157 			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4158 			       sizeof(rigid_disk_page_default));
4159 			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_SAVED],
4160 			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4161 			       sizeof(rigid_disk_page_default));
4162 
4163 			page_index->page_data =
4164 				(uint8_t *)lun->mode_pages.rigid_disk_page;
4165 			break;
4166 		}
4167 		case SMS_VERIFY_ERROR_RECOVERY_PAGE: {
4168 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4169 			    ("subpage %#x for page %#x is incorrect!",
4170 			    page_index->subpage, page_code));
4171 			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_CURRENT],
4172 			       &verify_er_page_default,
4173 			       sizeof(verify_er_page_default));
4174 			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_CHANGEABLE],
4175 			       &verify_er_page_changeable,
4176 			       sizeof(verify_er_page_changeable));
4177 			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_DEFAULT],
4178 			       &verify_er_page_default,
4179 			       sizeof(verify_er_page_default));
4180 			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_SAVED],
4181 			       &verify_er_page_default,
4182 			       sizeof(verify_er_page_default));
4183 			page_index->page_data =
4184 				(uint8_t *)lun->mode_pages.verify_er_page;
4185 			break;
4186 		}
4187 		case SMS_CACHING_PAGE: {
4188 			struct scsi_caching_page *caching_page;
4189 
4190 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4191 			    ("subpage %#x for page %#x is incorrect!",
4192 			    page_index->subpage, page_code));
4193 			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4194 			       &caching_page_default,
4195 			       sizeof(caching_page_default));
4196 			memcpy(&lun->mode_pages.caching_page[
4197 			       CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4198 			       sizeof(caching_page_changeable));
4199 			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4200 			       &caching_page_default,
4201 			       sizeof(caching_page_default));
4202 			caching_page = &lun->mode_pages.caching_page[
4203 			    CTL_PAGE_SAVED];
4204 			value = dnvlist_get_string(lun->be_lun->options,
4205 			    "writecache", NULL);
4206 			if (value != NULL && strcmp(value, "off") == 0)
4207 				caching_page->flags1 &= ~SCP_WCE;
4208 			value = dnvlist_get_string(lun->be_lun->options,
4209 			    "readcache", NULL);
4210 			if (value != NULL && strcmp(value, "off") == 0)
4211 				caching_page->flags1 |= SCP_RCD;
4212 			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4213 			       &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4214 			       sizeof(caching_page_default));
4215 			page_index->page_data =
4216 				(uint8_t *)lun->mode_pages.caching_page;
4217 			break;
4218 		}
4219 		case SMS_CONTROL_MODE_PAGE: {
4220 			switch (page_index->subpage) {
4221 			case SMS_SUBPAGE_PAGE_0: {
4222 				struct scsi_control_page *control_page;
4223 
4224 				memcpy(&lun->mode_pages.control_page[
4225 				    CTL_PAGE_DEFAULT],
4226 				       &control_page_default,
4227 				       sizeof(control_page_default));
4228 				memcpy(&lun->mode_pages.control_page[
4229 				    CTL_PAGE_CHANGEABLE],
4230 				       &control_page_changeable,
4231 				       sizeof(control_page_changeable));
4232 				memcpy(&lun->mode_pages.control_page[
4233 				    CTL_PAGE_SAVED],
4234 				       &control_page_default,
4235 				       sizeof(control_page_default));
4236 				control_page = &lun->mode_pages.control_page[
4237 				    CTL_PAGE_SAVED];
4238 				value = dnvlist_get_string(lun->be_lun->options,
4239 				    "reordering", NULL);
4240 				if (value != NULL &&
4241 				    strcmp(value, "unrestricted") == 0) {
4242 					control_page->queue_flags &=
4243 					    ~SCP_QUEUE_ALG_MASK;
4244 					control_page->queue_flags |=
4245 					    SCP_QUEUE_ALG_UNRESTRICTED;
4246 				}
4247 				memcpy(&lun->mode_pages.control_page[
4248 				    CTL_PAGE_CURRENT],
4249 				       &lun->mode_pages.control_page[
4250 				    CTL_PAGE_SAVED],
4251 				       sizeof(control_page_default));
4252 				page_index->page_data =
4253 				    (uint8_t *)lun->mode_pages.control_page;
4254 				break;
4255 			}
4256 			case 0x01:
4257 				memcpy(&lun->mode_pages.control_ext_page[
4258 				    CTL_PAGE_DEFAULT],
4259 				       &control_ext_page_default,
4260 				       sizeof(control_ext_page_default));
4261 				memcpy(&lun->mode_pages.control_ext_page[
4262 				    CTL_PAGE_CHANGEABLE],
4263 				       &control_ext_page_changeable,
4264 				       sizeof(control_ext_page_changeable));
4265 				memcpy(&lun->mode_pages.control_ext_page[
4266 				    CTL_PAGE_SAVED],
4267 				       &control_ext_page_default,
4268 				       sizeof(control_ext_page_default));
4269 				memcpy(&lun->mode_pages.control_ext_page[
4270 				    CTL_PAGE_CURRENT],
4271 				       &lun->mode_pages.control_ext_page[
4272 				    CTL_PAGE_SAVED],
4273 				       sizeof(control_ext_page_default));
4274 				page_index->page_data =
4275 				    (uint8_t *)lun->mode_pages.control_ext_page;
4276 				break;
4277 			default:
4278 				panic("subpage %#x for page %#x is incorrect!",
4279 				      page_index->subpage, page_code);
4280 			}
4281 			break;
4282 		}
4283 		case SMS_INFO_EXCEPTIONS_PAGE: {
4284 			switch (page_index->subpage) {
4285 			case SMS_SUBPAGE_PAGE_0:
4286 				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_CURRENT],
4287 				       &ie_page_default,
4288 				       sizeof(ie_page_default));
4289 				memcpy(&lun->mode_pages.ie_page[
4290 				       CTL_PAGE_CHANGEABLE], &ie_page_changeable,
4291 				       sizeof(ie_page_changeable));
4292 				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_DEFAULT],
4293 				       &ie_page_default,
4294 				       sizeof(ie_page_default));
4295 				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_SAVED],
4296 				       &ie_page_default,
4297 				       sizeof(ie_page_default));
4298 				page_index->page_data =
4299 					(uint8_t *)lun->mode_pages.ie_page;
4300 				break;
4301 			case 0x02: {
4302 				struct ctl_logical_block_provisioning_page *page;
4303 
4304 				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_DEFAULT],
4305 				       &lbp_page_default,
4306 				       sizeof(lbp_page_default));
4307 				memcpy(&lun->mode_pages.lbp_page[
4308 				       CTL_PAGE_CHANGEABLE], &lbp_page_changeable,
4309 				       sizeof(lbp_page_changeable));
4310 				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4311 				       &lbp_page_default,
4312 				       sizeof(lbp_page_default));
4313 				page = &lun->mode_pages.lbp_page[CTL_PAGE_SAVED];
4314 				value = dnvlist_get_string(lun->be_lun->options,
4315 				    "avail-threshold", NULL);
4316 				if (value != NULL &&
4317 				    ctl_expand_number(value, &ival) == 0) {
4318 					page->descr[0].flags |= SLBPPD_ENABLED |
4319 					    SLBPPD_ARMING_DEC;
4320 					if (lun->be_lun->blocksize)
4321 						ival /= lun->be_lun->blocksize;
4322 					else
4323 						ival /= 512;
4324 					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4325 					    page->descr[0].count);
4326 				}
4327 				value = dnvlist_get_string(lun->be_lun->options,
4328 				    "used-threshold", NULL);
4329 				if (value != NULL &&
4330 				    ctl_expand_number(value, &ival) == 0) {
4331 					page->descr[1].flags |= SLBPPD_ENABLED |
4332 					    SLBPPD_ARMING_INC;
4333 					if (lun->be_lun->blocksize)
4334 						ival /= lun->be_lun->blocksize;
4335 					else
4336 						ival /= 512;
4337 					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4338 					    page->descr[1].count);
4339 				}
4340 				value = dnvlist_get_string(lun->be_lun->options,
4341 				    "pool-avail-threshold", NULL);
4342 				if (value != NULL &&
4343 				    ctl_expand_number(value, &ival) == 0) {
4344 					page->descr[2].flags |= SLBPPD_ENABLED |
4345 					    SLBPPD_ARMING_DEC;
4346 					if (lun->be_lun->blocksize)
4347 						ival /= lun->be_lun->blocksize;
4348 					else
4349 						ival /= 512;
4350 					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4351 					    page->descr[2].count);
4352 				}
4353 				value = dnvlist_get_string(lun->be_lun->options,
4354 				    "pool-used-threshold", NULL);
4355 				if (value != NULL &&
4356 				    ctl_expand_number(value, &ival) == 0) {
4357 					page->descr[3].flags |= SLBPPD_ENABLED |
4358 					    SLBPPD_ARMING_INC;
4359 					if (lun->be_lun->blocksize)
4360 						ival /= lun->be_lun->blocksize;
4361 					else
4362 						ival /= 512;
4363 					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4364 					    page->descr[3].count);
4365 				}
4366 				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_CURRENT],
4367 				       &lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4368 				       sizeof(lbp_page_default));
4369 				page_index->page_data =
4370 					(uint8_t *)lun->mode_pages.lbp_page;
4371 				break;
4372 			}
4373 			default:
4374 				panic("subpage %#x for page %#x is incorrect!",
4375 				      page_index->subpage, page_code);
4376 			}
4377 			break;
4378 		}
4379 		case SMS_CDDVD_CAPS_PAGE:{
4380 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4381 			    ("subpage %#x for page %#x is incorrect!",
4382 			    page_index->subpage, page_code));
4383 			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_DEFAULT],
4384 			       &cddvd_page_default,
4385 			       sizeof(cddvd_page_default));
4386 			memcpy(&lun->mode_pages.cddvd_page[
4387 			       CTL_PAGE_CHANGEABLE], &cddvd_page_changeable,
4388 			       sizeof(cddvd_page_changeable));
4389 			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_SAVED],
4390 			       &cddvd_page_default,
4391 			       sizeof(cddvd_page_default));
4392 			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_CURRENT],
4393 			       &lun->mode_pages.cddvd_page[CTL_PAGE_SAVED],
4394 			       sizeof(cddvd_page_default));
4395 			page_index->page_data =
4396 				(uint8_t *)lun->mode_pages.cddvd_page;
4397 			break;
4398 		}
4399 		default:
4400 			panic("invalid page code value %#x", page_code);
4401 		}
4402 	}
4403 
4404 	return (CTL_RETVAL_COMPLETE);
4405 }
4406 
4407 static int
4408 ctl_init_log_page_index(struct ctl_lun *lun)
4409 {
4410 	struct ctl_page_index *page_index;
4411 	int i, j, k, prev;
4412 
4413 	memcpy(&lun->log_pages.index, log_page_index_template,
4414 	       sizeof(log_page_index_template));
4415 
4416 	prev = -1;
4417 	for (i = 0, j = 0, k = 0; i < CTL_NUM_LOG_PAGES; i++) {
4418 		page_index = &lun->log_pages.index[i];
4419 		if (lun->be_lun->lun_type == T_DIRECT &&
4420 		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
4421 			continue;
4422 		if (lun->be_lun->lun_type == T_PROCESSOR &&
4423 		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
4424 			continue;
4425 		if (lun->be_lun->lun_type == T_CDROM &&
4426 		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
4427 			continue;
4428 
4429 		if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING &&
4430 		    lun->backend->lun_attr == NULL)
4431 			continue;
4432 
4433 		if (page_index->page_code != prev) {
4434 			lun->log_pages.pages_page[j] = page_index->page_code;
4435 			prev = page_index->page_code;
4436 			j++;
4437 		}
4438 		lun->log_pages.subpages_page[k*2] = page_index->page_code;
4439 		lun->log_pages.subpages_page[k*2+1] = page_index->subpage;
4440 		k++;
4441 	}
4442 	lun->log_pages.index[0].page_data = &lun->log_pages.pages_page[0];
4443 	lun->log_pages.index[0].page_len = j;
4444 	lun->log_pages.index[1].page_data = &lun->log_pages.subpages_page[0];
4445 	lun->log_pages.index[1].page_len = k * 2;
4446 	lun->log_pages.index[2].page_data = (uint8_t *)&lun->log_pages.temp_page;
4447 	lun->log_pages.index[2].page_len = sizeof(lun->log_pages.temp_page);
4448 	lun->log_pages.index[3].page_data = &lun->log_pages.lbp_page[0];
4449 	lun->log_pages.index[3].page_len = 12*CTL_NUM_LBP_PARAMS;
4450 	lun->log_pages.index[4].page_data = (uint8_t *)&lun->log_pages.stat_page;
4451 	lun->log_pages.index[4].page_len = sizeof(lun->log_pages.stat_page);
4452 	lun->log_pages.index[5].page_data = (uint8_t *)&lun->log_pages.ie_page;
4453 	lun->log_pages.index[5].page_len = sizeof(lun->log_pages.ie_page);
4454 
4455 	return (CTL_RETVAL_COMPLETE);
4456 }
4457 
4458 static int
4459 hex2bin(const char *str, uint8_t *buf, int buf_size)
4460 {
4461 	int i;
4462 	u_char c;
4463 
4464 	memset(buf, 0, buf_size);
4465 	while (isspace(str[0]))
4466 		str++;
4467 	if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
4468 		str += 2;
4469 	buf_size *= 2;
4470 	for (i = 0; str[i] != 0 && i < buf_size; i++) {
4471 		while (str[i] == '-')	/* Skip dashes in UUIDs. */
4472 			str++;
4473 		c = str[i];
4474 		if (isdigit(c))
4475 			c -= '0';
4476 		else if (isalpha(c))
4477 			c -= isupper(c) ? 'A' - 10 : 'a' - 10;
4478 		else
4479 			break;
4480 		if (c >= 16)
4481 			break;
4482 		if ((i & 1) == 0)
4483 			buf[i / 2] |= (c << 4);
4484 		else
4485 			buf[i / 2] |= c;
4486 	}
4487 	return ((i + 1) / 2);
4488 }
4489 
4490 /*
4491  * Add LUN.
4492  *
4493  * Returns 0 for success, non-zero (errno) for failure.
4494  */
4495 int
4496 ctl_add_lun(struct ctl_be_lun *be_lun)
4497 {
4498 	struct ctl_softc *ctl_softc = control_softc;
4499 	struct ctl_lun *nlun, *lun;
4500 	struct scsi_vpd_id_descriptor *desc;
4501 	struct scsi_vpd_id_t10 *t10id;
4502 	const char *eui, *naa, *scsiname, *uuid, *vendor, *value;
4503 	int lun_number;
4504 	int devidlen, idlen1, idlen2 = 0, len;
4505 
4506 	/*
4507 	 * We support only Direct Access, CD-ROM or Processor LUN types.
4508 	 */
4509 	switch (be_lun->lun_type) {
4510 	case T_DIRECT:
4511 	case T_PROCESSOR:
4512 	case T_CDROM:
4513 		break;
4514 	case T_SEQUENTIAL:
4515 	case T_CHANGER:
4516 	default:
4517 		return (EINVAL);
4518 	}
4519 	lun = malloc(sizeof(*lun), M_CTL, M_WAITOK | M_ZERO);
4520 
4521 	lun->pending_sense = malloc(sizeof(struct scsi_sense_data *) *
4522 	    ctl_max_ports, M_DEVBUF, M_WAITOK | M_ZERO);
4523 	lun->pending_ua = malloc(sizeof(ctl_ua_type *) * ctl_max_ports,
4524 	    M_DEVBUF, M_WAITOK | M_ZERO);
4525 	lun->pr_keys = malloc(sizeof(uint64_t *) * ctl_max_ports,
4526 	    M_DEVBUF, M_WAITOK | M_ZERO);
4527 
4528 	/* Generate LUN ID. */
4529 	devidlen = max(CTL_DEVID_MIN_LEN,
4530 	    strnlen(be_lun->device_id, CTL_DEVID_LEN));
4531 	idlen1 = sizeof(*t10id) + devidlen;
4532 	len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4533 	scsiname = dnvlist_get_string(be_lun->options, "scsiname", NULL);
4534 	if (scsiname != NULL) {
4535 		idlen2 = roundup2(strlen(scsiname) + 1, 4);
4536 		len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4537 	}
4538 	eui = dnvlist_get_string(be_lun->options, "eui", NULL);
4539 	if (eui != NULL) {
4540 		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4541 	}
4542 	naa = dnvlist_get_string(be_lun->options, "naa", NULL);
4543 	if (naa != NULL) {
4544 		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4545 	}
4546 	uuid = dnvlist_get_string(be_lun->options, "uuid", NULL);
4547 	if (uuid != NULL) {
4548 		len += sizeof(struct scsi_vpd_id_descriptor) + 18;
4549 	}
4550 	lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4551 	    M_CTL, M_WAITOK | M_ZERO);
4552 	desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4553 	desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4554 	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4555 	desc->length = idlen1;
4556 	t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4557 	memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4558 	if ((vendor = dnvlist_get_string(be_lun->options, "vendor", NULL)) == NULL) {
4559 		strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4560 	} else {
4561 		strncpy(t10id->vendor, vendor,
4562 		    min(sizeof(t10id->vendor), strlen(vendor)));
4563 	}
4564 	strncpy((char *)t10id->vendor_spec_id,
4565 	    (char *)be_lun->device_id, devidlen);
4566 	if (scsiname != NULL) {
4567 		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4568 		    desc->length);
4569 		desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4570 		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4571 		    SVPD_ID_TYPE_SCSI_NAME;
4572 		desc->length = idlen2;
4573 		strlcpy(desc->identifier, scsiname, idlen2);
4574 	}
4575 	if (eui != NULL) {
4576 		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4577 		    desc->length);
4578 		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4579 		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4580 		    SVPD_ID_TYPE_EUI64;
4581 		desc->length = hex2bin(eui, desc->identifier, 16);
4582 		desc->length = desc->length > 12 ? 16 :
4583 		    (desc->length > 8 ? 12 : 8);
4584 		len -= 16 - desc->length;
4585 	}
4586 	if (naa != NULL) {
4587 		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4588 		    desc->length);
4589 		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4590 		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4591 		    SVPD_ID_TYPE_NAA;
4592 		desc->length = hex2bin(naa, desc->identifier, 16);
4593 		desc->length = desc->length > 8 ? 16 : 8;
4594 		len -= 16 - desc->length;
4595 	}
4596 	if (uuid != NULL) {
4597 		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4598 		    desc->length);
4599 		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4600 		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4601 		    SVPD_ID_TYPE_UUID;
4602 		desc->identifier[0] = 0x10;
4603 		hex2bin(uuid, &desc->identifier[2], 16);
4604 		desc->length = 18;
4605 	}
4606 	lun->lun_devid->len = len;
4607 
4608 	mtx_lock(&ctl_softc->ctl_lock);
4609 	/*
4610 	 * See if the caller requested a particular LUN number.  If so, see
4611 	 * if it is available.  Otherwise, allocate the first available LUN.
4612 	 */
4613 	if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4614 		if ((be_lun->req_lun_id > (ctl_max_luns - 1))
4615 		 || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4616 			mtx_unlock(&ctl_softc->ctl_lock);
4617 			if (be_lun->req_lun_id > (ctl_max_luns - 1)) {
4618 				printf("ctl: requested LUN ID %d is higher "
4619 				       "than ctl_max_luns - 1 (%d)\n",
4620 				       be_lun->req_lun_id, ctl_max_luns - 1);
4621 			} else {
4622 				/*
4623 				 * XXX KDM return an error, or just assign
4624 				 * another LUN ID in this case??
4625 				 */
4626 				printf("ctl: requested LUN ID %d is already "
4627 				       "in use\n", be_lun->req_lun_id);
4628 			}
4629 fail:
4630 			free(lun->lun_devid, M_CTL);
4631 			free(lun, M_CTL);
4632 			return (ENOSPC);
4633 		}
4634 		lun_number = be_lun->req_lun_id;
4635 	} else {
4636 		lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, 0, ctl_max_luns);
4637 		if (lun_number == -1) {
4638 			mtx_unlock(&ctl_softc->ctl_lock);
4639 			printf("ctl: can't allocate LUN, out of LUNs\n");
4640 			goto fail;
4641 		}
4642 	}
4643 	ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4644 	mtx_unlock(&ctl_softc->ctl_lock);
4645 
4646 	mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4647 	lun->lun = lun_number;
4648 	lun->be_lun = be_lun;
4649 	/*
4650 	 * The processor LUN is always enabled.  Disk LUNs come on line
4651 	 * disabled, and must be enabled by the backend.
4652 	 */
4653 	lun->flags |= CTL_LUN_DISABLED;
4654 	lun->backend = be_lun->be;
4655 	be_lun->ctl_lun = lun;
4656 	be_lun->lun_id = lun_number;
4657 	if (be_lun->flags & CTL_LUN_FLAG_EJECTED)
4658 		lun->flags |= CTL_LUN_EJECTED;
4659 	if (be_lun->flags & CTL_LUN_FLAG_NO_MEDIA)
4660 		lun->flags |= CTL_LUN_NO_MEDIA;
4661 	if (be_lun->flags & CTL_LUN_FLAG_STOPPED)
4662 		lun->flags |= CTL_LUN_STOPPED;
4663 
4664 	if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4665 		lun->flags |= CTL_LUN_PRIMARY_SC;
4666 
4667 	value = dnvlist_get_string(be_lun->options, "removable", NULL);
4668 	if (value != NULL) {
4669 		if (strcmp(value, "on") == 0)
4670 			lun->flags |= CTL_LUN_REMOVABLE;
4671 	} else if (be_lun->lun_type == T_CDROM)
4672 		lun->flags |= CTL_LUN_REMOVABLE;
4673 
4674 	lun->ctl_softc = ctl_softc;
4675 #ifdef CTL_TIME_IO
4676 	lun->last_busy = getsbinuptime();
4677 #endif
4678 	LIST_INIT(&lun->ooa_queue);
4679 	STAILQ_INIT(&lun->error_list);
4680 	lun->ie_reported = 1;
4681 	callout_init_mtx(&lun->ie_callout, &lun->lun_lock, 0);
4682 	ctl_tpc_lun_init(lun);
4683 	if (lun->flags & CTL_LUN_REMOVABLE) {
4684 		lun->prevent = malloc((CTL_MAX_INITIATORS + 31) / 32 * 4,
4685 		    M_CTL, M_WAITOK);
4686 	}
4687 
4688 	/*
4689 	 * Initialize the mode and log page index.
4690 	 */
4691 	ctl_init_page_index(lun);
4692 	ctl_init_log_page_index(lun);
4693 
4694 	/* Setup statistics gathering */
4695 	lun->stats.item = lun_number;
4696 
4697 	/*
4698 	 * Now, before we insert this lun on the lun list, set the lun
4699 	 * inventory changed UA for all other luns.
4700 	 */
4701 	mtx_lock(&ctl_softc->ctl_lock);
4702 	STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4703 		mtx_lock(&nlun->lun_lock);
4704 		ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4705 		mtx_unlock(&nlun->lun_lock);
4706 	}
4707 	STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4708 	ctl_softc->ctl_luns[lun_number] = lun;
4709 	ctl_softc->num_luns++;
4710 	mtx_unlock(&ctl_softc->ctl_lock);
4711 
4712 	/*
4713 	 * We successfully added the LUN, attempt to enable it.
4714 	 */
4715 	if (ctl_enable_lun(lun) != 0) {
4716 		printf("%s: ctl_enable_lun() failed!\n", __func__);
4717 		mtx_lock(&ctl_softc->ctl_lock);
4718 		STAILQ_REMOVE(&ctl_softc->lun_list, lun, ctl_lun, links);
4719 		ctl_clear_mask(ctl_softc->ctl_lun_mask, lun_number);
4720 		ctl_softc->ctl_luns[lun_number] = NULL;
4721 		ctl_softc->num_luns--;
4722 		mtx_unlock(&ctl_softc->ctl_lock);
4723 		free(lun->lun_devid, M_CTL);
4724 		free(lun, M_CTL);
4725 		return (EIO);
4726 	}
4727 
4728 	return (0);
4729 }
4730 
4731 /*
4732  * Free LUN that has no active requests.
4733  */
4734 static int
4735 ctl_free_lun(struct ctl_lun *lun)
4736 {
4737 	struct ctl_softc *softc = lun->ctl_softc;
4738 	struct ctl_lun *nlun;
4739 	int i;
4740 
4741 	KASSERT(LIST_EMPTY(&lun->ooa_queue),
4742 	    ("Freeing a LUN %p with outstanding I/O!\n", lun));
4743 
4744 	mtx_lock(&softc->ctl_lock);
4745 	STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4746 	ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4747 	softc->ctl_luns[lun->lun] = NULL;
4748 	softc->num_luns--;
4749 	STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4750 		mtx_lock(&nlun->lun_lock);
4751 		ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4752 		mtx_unlock(&nlun->lun_lock);
4753 	}
4754 	mtx_unlock(&softc->ctl_lock);
4755 
4756 	/*
4757 	 * Tell the backend to free resources, if this LUN has a backend.
4758 	 */
4759 	lun->be_lun->lun_shutdown(lun->be_lun);
4760 
4761 	lun->ie_reportcnt = UINT32_MAX;
4762 	callout_drain(&lun->ie_callout);
4763 	ctl_tpc_lun_shutdown(lun);
4764 	mtx_destroy(&lun->lun_lock);
4765 	free(lun->lun_devid, M_CTL);
4766 	for (i = 0; i < ctl_max_ports; i++)
4767 		free(lun->pending_ua[i], M_CTL);
4768 	free(lun->pending_ua, M_DEVBUF);
4769 	for (i = 0; i < ctl_max_ports; i++)
4770 		free(lun->pr_keys[i], M_CTL);
4771 	free(lun->pr_keys, M_DEVBUF);
4772 	free(lun->write_buffer, M_CTL);
4773 	free(lun->prevent, M_CTL);
4774 	free(lun, M_CTL);
4775 
4776 	return (0);
4777 }
4778 
4779 static int
4780 ctl_enable_lun(struct ctl_lun *lun)
4781 {
4782 	struct ctl_softc *softc;
4783 	struct ctl_port *port, *nport;
4784 	int retval;
4785 
4786 	softc = lun->ctl_softc;
4787 
4788 	mtx_lock(&softc->ctl_lock);
4789 	mtx_lock(&lun->lun_lock);
4790 	KASSERT((lun->flags & CTL_LUN_DISABLED) != 0,
4791 	    ("%s: LUN not disabled", __func__));
4792 	lun->flags &= ~CTL_LUN_DISABLED;
4793 	mtx_unlock(&lun->lun_lock);
4794 
4795 	STAILQ_FOREACH_SAFE(port, &softc->port_list, links, nport) {
4796 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4797 		    port->lun_map != NULL || port->lun_enable == NULL)
4798 			continue;
4799 
4800 		/*
4801 		 * Drop the lock while we call the FETD's enable routine.
4802 		 * This can lead to a callback into CTL (at least in the
4803 		 * case of the internal initiator frontend.
4804 		 */
4805 		mtx_unlock(&softc->ctl_lock);
4806 		retval = port->lun_enable(port->targ_lun_arg, lun->lun);
4807 		mtx_lock(&softc->ctl_lock);
4808 		if (retval != 0) {
4809 			printf("%s: FETD %s port %d returned error "
4810 			       "%d for lun_enable on lun %jd\n",
4811 			       __func__, port->port_name, port->targ_port,
4812 			       retval, (intmax_t)lun->lun);
4813 		}
4814 	}
4815 
4816 	mtx_unlock(&softc->ctl_lock);
4817 	ctl_isc_announce_lun(lun);
4818 
4819 	return (0);
4820 }
4821 
4822 static int
4823 ctl_disable_lun(struct ctl_lun *lun)
4824 {
4825 	struct ctl_softc *softc;
4826 	struct ctl_port *port;
4827 	int retval;
4828 
4829 	softc = lun->ctl_softc;
4830 
4831 	mtx_lock(&softc->ctl_lock);
4832 	mtx_lock(&lun->lun_lock);
4833 	KASSERT((lun->flags & CTL_LUN_DISABLED) == 0,
4834 	    ("%s: LUN not enabled", __func__));
4835 	lun->flags |= CTL_LUN_DISABLED;
4836 	mtx_unlock(&lun->lun_lock);
4837 
4838 	STAILQ_FOREACH(port, &softc->port_list, links) {
4839 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4840 		    port->lun_map != NULL || port->lun_disable == NULL)
4841 			continue;
4842 
4843 		/*
4844 		 * Drop the lock before we call the frontend's disable
4845 		 * routine, to avoid lock order reversals.
4846 		 *
4847 		 * XXX KDM what happens if the frontend list changes while
4848 		 * we're traversing it?  It's unlikely, but should be handled.
4849 		 */
4850 		mtx_unlock(&softc->ctl_lock);
4851 		retval = port->lun_disable(port->targ_lun_arg, lun->lun);
4852 		mtx_lock(&softc->ctl_lock);
4853 		if (retval != 0) {
4854 			printf("%s: FETD %s port %d returned error "
4855 			       "%d for lun_disable on lun %jd\n",
4856 			       __func__, port->port_name, port->targ_port,
4857 			       retval, (intmax_t)lun->lun);
4858 		}
4859 	}
4860 
4861 	mtx_unlock(&softc->ctl_lock);
4862 	ctl_isc_announce_lun(lun);
4863 
4864 	return (0);
4865 }
4866 
4867 int
4868 ctl_start_lun(struct ctl_be_lun *be_lun)
4869 {
4870 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4871 
4872 	mtx_lock(&lun->lun_lock);
4873 	lun->flags &= ~CTL_LUN_STOPPED;
4874 	mtx_unlock(&lun->lun_lock);
4875 	return (0);
4876 }
4877 
4878 int
4879 ctl_stop_lun(struct ctl_be_lun *be_lun)
4880 {
4881 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4882 
4883 	mtx_lock(&lun->lun_lock);
4884 	lun->flags |= CTL_LUN_STOPPED;
4885 	mtx_unlock(&lun->lun_lock);
4886 	return (0);
4887 }
4888 
4889 int
4890 ctl_lun_no_media(struct ctl_be_lun *be_lun)
4891 {
4892 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4893 
4894 	mtx_lock(&lun->lun_lock);
4895 	lun->flags |= CTL_LUN_NO_MEDIA;
4896 	mtx_unlock(&lun->lun_lock);
4897 	return (0);
4898 }
4899 
4900 int
4901 ctl_lun_has_media(struct ctl_be_lun *be_lun)
4902 {
4903 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4904 	union ctl_ha_msg msg;
4905 
4906 	mtx_lock(&lun->lun_lock);
4907 	lun->flags &= ~(CTL_LUN_NO_MEDIA | CTL_LUN_EJECTED);
4908 	if (lun->flags & CTL_LUN_REMOVABLE)
4909 		ctl_est_ua_all(lun, -1, CTL_UA_MEDIUM_CHANGE);
4910 	mtx_unlock(&lun->lun_lock);
4911 	if ((lun->flags & CTL_LUN_REMOVABLE) &&
4912 	    lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
4913 		bzero(&msg.ua, sizeof(msg.ua));
4914 		msg.hdr.msg_type = CTL_MSG_UA;
4915 		msg.hdr.nexus.initid = -1;
4916 		msg.hdr.nexus.targ_port = -1;
4917 		msg.hdr.nexus.targ_lun = lun->lun;
4918 		msg.hdr.nexus.targ_mapped_lun = lun->lun;
4919 		msg.ua.ua_all = 1;
4920 		msg.ua.ua_set = 1;
4921 		msg.ua.ua_type = CTL_UA_MEDIUM_CHANGE;
4922 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
4923 		    M_WAITOK);
4924 	}
4925 	return (0);
4926 }
4927 
4928 int
4929 ctl_lun_ejected(struct ctl_be_lun *be_lun)
4930 {
4931 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4932 
4933 	mtx_lock(&lun->lun_lock);
4934 	lun->flags |= CTL_LUN_EJECTED;
4935 	mtx_unlock(&lun->lun_lock);
4936 	return (0);
4937 }
4938 
4939 int
4940 ctl_lun_primary(struct ctl_be_lun *be_lun)
4941 {
4942 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4943 
4944 	mtx_lock(&lun->lun_lock);
4945 	lun->flags |= CTL_LUN_PRIMARY_SC;
4946 	ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
4947 	mtx_unlock(&lun->lun_lock);
4948 	ctl_isc_announce_lun(lun);
4949 	return (0);
4950 }
4951 
4952 int
4953 ctl_lun_secondary(struct ctl_be_lun *be_lun)
4954 {
4955 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4956 
4957 	mtx_lock(&lun->lun_lock);
4958 	lun->flags &= ~CTL_LUN_PRIMARY_SC;
4959 	ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
4960 	mtx_unlock(&lun->lun_lock);
4961 	ctl_isc_announce_lun(lun);
4962 	return (0);
4963 }
4964 
4965 /*
4966  * Remove LUN.  If there are active requests, wait for completion.
4967  *
4968  * Returns 0 for success, non-zero (errno) for failure.
4969  * Completion is reported to backed via the lun_shutdown() method.
4970  */
4971 int
4972 ctl_remove_lun(struct ctl_be_lun *be_lun)
4973 {
4974 	struct ctl_lun *lun;
4975 
4976 	lun = (struct ctl_lun *)be_lun->ctl_lun;
4977 
4978 	ctl_disable_lun(lun);
4979 
4980 	mtx_lock(&lun->lun_lock);
4981 	lun->flags |= CTL_LUN_INVALID;
4982 
4983 	/*
4984 	 * If there is nothing in the OOA queue, go ahead and free the LUN.
4985 	 * If we have something in the OOA queue, we'll free it when the
4986 	 * last I/O completes.
4987 	 */
4988 	if (LIST_EMPTY(&lun->ooa_queue)) {
4989 		mtx_unlock(&lun->lun_lock);
4990 		ctl_free_lun(lun);
4991 	} else
4992 		mtx_unlock(&lun->lun_lock);
4993 
4994 	return (0);
4995 }
4996 
4997 void
4998 ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
4999 {
5000 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5001 	union ctl_ha_msg msg;
5002 
5003 	mtx_lock(&lun->lun_lock);
5004 	ctl_est_ua_all(lun, -1, CTL_UA_CAPACITY_CHANGE);
5005 	mtx_unlock(&lun->lun_lock);
5006 	if (lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
5007 		/* Send msg to other side. */
5008 		bzero(&msg.ua, sizeof(msg.ua));
5009 		msg.hdr.msg_type = CTL_MSG_UA;
5010 		msg.hdr.nexus.initid = -1;
5011 		msg.hdr.nexus.targ_port = -1;
5012 		msg.hdr.nexus.targ_lun = lun->lun;
5013 		msg.hdr.nexus.targ_mapped_lun = lun->lun;
5014 		msg.ua.ua_all = 1;
5015 		msg.ua.ua_set = 1;
5016 		msg.ua.ua_type = CTL_UA_CAPACITY_CHANGE;
5017 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
5018 		    M_WAITOK);
5019 	}
5020 }
5021 
5022 /*
5023  * Backend "memory move is complete" callback for requests that never
5024  * make it down to say RAIDCore's configuration code.
5025  */
5026 int
5027 ctl_config_move_done(union ctl_io *io, bool samethr)
5028 {
5029 	int retval;
5030 
5031 	CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
5032 	KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
5033 	    ("%s: unexpected I/O type %x", __func__, io->io_hdr.io_type));
5034 
5035 	if (ctl_debug & CTL_DEBUG_CDB_DATA)
5036 		ctl_data_print(io);
5037 	if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN) ||
5038 	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5039 	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) ||
5040 	    ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
5041 		/*
5042 		 * XXX KDM just assuming a single pointer here, and not a
5043 		 * S/G list.  If we start using S/G lists for config data,
5044 		 * we'll need to know how to clean them up here as well.
5045 		 */
5046 		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5047 			free(io->scsiio.kern_data_ptr, M_CTL);
5048 		ctl_done(io);
5049 		retval = CTL_RETVAL_COMPLETE;
5050 	} else {
5051 		/*
5052 		 * XXX KDM now we need to continue data movement.  Some
5053 		 * options:
5054 		 * - call ctl_scsiio() again?  We don't do this for data
5055 		 *   writes, because for those at least we know ahead of
5056 		 *   time where the write will go and how long it is.  For
5057 		 *   config writes, though, that information is largely
5058 		 *   contained within the write itself, thus we need to
5059 		 *   parse out the data again.
5060 		 *
5061 		 * - Call some other function once the data is in?
5062 		 */
5063 
5064 		/*
5065 		 * XXX KDM call ctl_scsiio() again for now, and check flag
5066 		 * bits to see whether we're allocated or not.
5067 		 */
5068 		retval = ctl_scsiio(&io->scsiio);
5069 	}
5070 	return (retval);
5071 }
5072 
5073 /*
5074  * This gets called by a backend driver when it is done with a
5075  * data_submit method.
5076  */
5077 void
5078 ctl_data_submit_done(union ctl_io *io)
5079 {
5080 	/*
5081 	 * If the IO_CONT flag is set, we need to call the supplied
5082 	 * function to continue processing the I/O, instead of completing
5083 	 * the I/O just yet.
5084 	 *
5085 	 * If there is an error, though, we don't want to keep processing.
5086 	 * Instead, just send status back to the initiator.
5087 	 */
5088 	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5089 	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5090 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5091 	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5092 		io->scsiio.io_cont(io);
5093 		return;
5094 	}
5095 	ctl_done(io);
5096 }
5097 
5098 /*
5099  * This gets called by a backend driver when it is done with a
5100  * configuration write.
5101  */
5102 void
5103 ctl_config_write_done(union ctl_io *io)
5104 {
5105 	uint8_t *buf;
5106 
5107 	/*
5108 	 * If the IO_CONT flag is set, we need to call the supplied
5109 	 * function to continue processing the I/O, instead of completing
5110 	 * the I/O just yet.
5111 	 *
5112 	 * If there is an error, though, we don't want to keep processing.
5113 	 * Instead, just send status back to the initiator.
5114 	 */
5115 	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5116 	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5117 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5118 	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5119 		io->scsiio.io_cont(io);
5120 		return;
5121 	}
5122 	/*
5123 	 * Since a configuration write can be done for commands that actually
5124 	 * have data allocated, like write buffer, and commands that have
5125 	 * no data, like start/stop unit, we need to check here.
5126 	 */
5127 	if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5128 		buf = io->scsiio.kern_data_ptr;
5129 	else
5130 		buf = NULL;
5131 	ctl_done(io);
5132 	if (buf)
5133 		free(buf, M_CTL);
5134 }
5135 
5136 void
5137 ctl_config_read_done(union ctl_io *io)
5138 {
5139 	uint8_t *buf;
5140 
5141 	/*
5142 	 * If there is some error -- we are done, skip data transfer.
5143 	 */
5144 	if ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0 ||
5145 	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5146 	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)) {
5147 		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5148 			buf = io->scsiio.kern_data_ptr;
5149 		else
5150 			buf = NULL;
5151 		ctl_done(io);
5152 		if (buf)
5153 			free(buf, M_CTL);
5154 		return;
5155 	}
5156 
5157 	/*
5158 	 * If the IO_CONT flag is set, we need to call the supplied
5159 	 * function to continue processing the I/O, instead of completing
5160 	 * the I/O just yet.
5161 	 */
5162 	if (io->io_hdr.flags & CTL_FLAG_IO_CONT) {
5163 		io->scsiio.io_cont(io);
5164 		return;
5165 	}
5166 
5167 	ctl_datamove(io);
5168 }
5169 
5170 /*
5171  * SCSI release command.
5172  */
5173 int
5174 ctl_scsi_release(struct ctl_scsiio *ctsio)
5175 {
5176 	struct ctl_lun *lun = CTL_LUN(ctsio);
5177 	uint32_t residx;
5178 
5179 	CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5180 
5181 	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5182 
5183 	/*
5184 	 * XXX KDM right now, we only support LUN reservation.  We don't
5185 	 * support 3rd party reservations, or extent reservations, which
5186 	 * might actually need the parameter list.  If we've gotten this
5187 	 * far, we've got a LUN reservation.  Anything else got kicked out
5188 	 * above.  So, according to SPC, ignore the length.
5189 	 */
5190 
5191 	mtx_lock(&lun->lun_lock);
5192 
5193 	/*
5194 	 * According to SPC, it is not an error for an intiator to attempt
5195 	 * to release a reservation on a LUN that isn't reserved, or that
5196 	 * is reserved by another initiator.  The reservation can only be
5197 	 * released, though, by the initiator who made it or by one of
5198 	 * several reset type events.
5199 	 */
5200 	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
5201 			lun->flags &= ~CTL_LUN_RESERVED;
5202 
5203 	mtx_unlock(&lun->lun_lock);
5204 
5205 	ctl_set_success(ctsio);
5206 	ctl_done((union ctl_io *)ctsio);
5207 	return (CTL_RETVAL_COMPLETE);
5208 }
5209 
5210 int
5211 ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5212 {
5213 	struct ctl_lun *lun = CTL_LUN(ctsio);
5214 	uint32_t residx;
5215 
5216 	CTL_DEBUG_PRINT(("ctl_reserve\n"));
5217 
5218 	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5219 
5220 	/*
5221 	 * XXX KDM right now, we only support LUN reservation.  We don't
5222 	 * support 3rd party reservations, or extent reservations, which
5223 	 * might actually need the parameter list.  If we've gotten this
5224 	 * far, we've got a LUN reservation.  Anything else got kicked out
5225 	 * above.  So, according to SPC, ignore the length.
5226 	 */
5227 
5228 	mtx_lock(&lun->lun_lock);
5229 	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
5230 		ctl_set_reservation_conflict(ctsio);
5231 		goto bailout;
5232 	}
5233 
5234 	/* SPC-3 exceptions to SPC-2 RESERVE and RELEASE behavior. */
5235 	if (lun->flags & CTL_LUN_PR_RESERVED) {
5236 		ctl_set_success(ctsio);
5237 		goto bailout;
5238 	}
5239 
5240 	lun->flags |= CTL_LUN_RESERVED;
5241 	lun->res_idx = residx;
5242 	ctl_set_success(ctsio);
5243 
5244 bailout:
5245 	mtx_unlock(&lun->lun_lock);
5246 	ctl_done((union ctl_io *)ctsio);
5247 	return (CTL_RETVAL_COMPLETE);
5248 }
5249 
5250 int
5251 ctl_start_stop(struct ctl_scsiio *ctsio)
5252 {
5253 	struct ctl_lun *lun = CTL_LUN(ctsio);
5254 	struct scsi_start_stop_unit *cdb;
5255 	int retval;
5256 
5257 	CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5258 
5259 	cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5260 
5261 	if ((cdb->how & SSS_PC_MASK) == 0) {
5262 		if ((lun->flags & CTL_LUN_PR_RESERVED) &&
5263 		    (cdb->how & SSS_START) == 0) {
5264 			uint32_t residx;
5265 
5266 			residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5267 			if (ctl_get_prkey(lun, residx) == 0 ||
5268 			    (lun->pr_res_idx != residx && lun->pr_res_type < 4)) {
5269 				ctl_set_reservation_conflict(ctsio);
5270 				ctl_done((union ctl_io *)ctsio);
5271 				return (CTL_RETVAL_COMPLETE);
5272 			}
5273 		}
5274 
5275 		if ((cdb->how & SSS_LOEJ) &&
5276 		    (lun->flags & CTL_LUN_REMOVABLE) == 0) {
5277 			ctl_set_invalid_field(ctsio,
5278 					      /*sks_valid*/ 1,
5279 					      /*command*/ 1,
5280 					      /*field*/ 4,
5281 					      /*bit_valid*/ 1,
5282 					      /*bit*/ 1);
5283 			ctl_done((union ctl_io *)ctsio);
5284 			return (CTL_RETVAL_COMPLETE);
5285 		}
5286 
5287 		if ((cdb->how & SSS_START) == 0 && (cdb->how & SSS_LOEJ) &&
5288 		    lun->prevent_count > 0) {
5289 			/* "Medium removal prevented" */
5290 			ctl_set_sense(ctsio, /*current_error*/ 1,
5291 			    /*sense_key*/(lun->flags & CTL_LUN_NO_MEDIA) ?
5292 			     SSD_KEY_NOT_READY : SSD_KEY_ILLEGAL_REQUEST,
5293 			    /*asc*/ 0x53, /*ascq*/ 0x02, SSD_ELEM_NONE);
5294 			ctl_done((union ctl_io *)ctsio);
5295 			return (CTL_RETVAL_COMPLETE);
5296 		}
5297 	}
5298 
5299 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5300 	return (retval);
5301 }
5302 
5303 int
5304 ctl_prevent_allow(struct ctl_scsiio *ctsio)
5305 {
5306 	struct ctl_lun *lun = CTL_LUN(ctsio);
5307 	struct scsi_prevent *cdb;
5308 	int retval;
5309 	uint32_t initidx;
5310 
5311 	CTL_DEBUG_PRINT(("ctl_prevent_allow\n"));
5312 
5313 	cdb = (struct scsi_prevent *)ctsio->cdb;
5314 
5315 	if ((lun->flags & CTL_LUN_REMOVABLE) == 0 || lun->prevent == NULL) {
5316 		ctl_set_invalid_opcode(ctsio);
5317 		ctl_done((union ctl_io *)ctsio);
5318 		return (CTL_RETVAL_COMPLETE);
5319 	}
5320 
5321 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5322 	mtx_lock(&lun->lun_lock);
5323 	if ((cdb->how & PR_PREVENT) &&
5324 	    ctl_is_set(lun->prevent, initidx) == 0) {
5325 		ctl_set_mask(lun->prevent, initidx);
5326 		lun->prevent_count++;
5327 	} else if ((cdb->how & PR_PREVENT) == 0 &&
5328 	    ctl_is_set(lun->prevent, initidx)) {
5329 		ctl_clear_mask(lun->prevent, initidx);
5330 		lun->prevent_count--;
5331 	}
5332 	mtx_unlock(&lun->lun_lock);
5333 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5334 	return (retval);
5335 }
5336 
5337 /*
5338  * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5339  * we don't really do anything with the LBA and length fields if the user
5340  * passes them in.  Instead we'll just flush out the cache for the entire
5341  * LUN.
5342  */
5343 int
5344 ctl_sync_cache(struct ctl_scsiio *ctsio)
5345 {
5346 	struct ctl_lun *lun = CTL_LUN(ctsio);
5347 	struct ctl_lba_len_flags *lbalen;
5348 	uint64_t starting_lba;
5349 	uint32_t block_count;
5350 	int retval;
5351 	uint8_t byte2;
5352 
5353 	CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5354 
5355 	retval = 0;
5356 
5357 	switch (ctsio->cdb[0]) {
5358 	case SYNCHRONIZE_CACHE: {
5359 		struct scsi_sync_cache *cdb;
5360 		cdb = (struct scsi_sync_cache *)ctsio->cdb;
5361 
5362 		starting_lba = scsi_4btoul(cdb->begin_lba);
5363 		block_count = scsi_2btoul(cdb->lb_count);
5364 		byte2 = cdb->byte2;
5365 		break;
5366 	}
5367 	case SYNCHRONIZE_CACHE_16: {
5368 		struct scsi_sync_cache_16 *cdb;
5369 		cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5370 
5371 		starting_lba = scsi_8btou64(cdb->begin_lba);
5372 		block_count = scsi_4btoul(cdb->lb_count);
5373 		byte2 = cdb->byte2;
5374 		break;
5375 	}
5376 	default:
5377 		ctl_set_invalid_opcode(ctsio);
5378 		ctl_done((union ctl_io *)ctsio);
5379 		goto bailout;
5380 		break; /* NOTREACHED */
5381 	}
5382 
5383 	/*
5384 	 * We check the LBA and length, but don't do anything with them.
5385 	 * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5386 	 * get flushed.  This check will just help satisfy anyone who wants
5387 	 * to see an error for an out of range LBA.
5388 	 */
5389 	if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5390 		ctl_set_lba_out_of_range(ctsio,
5391 		    MAX(starting_lba, lun->be_lun->maxlba + 1));
5392 		ctl_done((union ctl_io *)ctsio);
5393 		goto bailout;
5394 	}
5395 
5396 	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5397 	lbalen->lba = starting_lba;
5398 	lbalen->len = block_count;
5399 	lbalen->flags = byte2;
5400 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5401 
5402 bailout:
5403 	return (retval);
5404 }
5405 
5406 int
5407 ctl_format(struct ctl_scsiio *ctsio)
5408 {
5409 	struct scsi_format *cdb;
5410 	int length, defect_list_len;
5411 
5412 	CTL_DEBUG_PRINT(("ctl_format\n"));
5413 
5414 	cdb = (struct scsi_format *)ctsio->cdb;
5415 
5416 	length = 0;
5417 	if (cdb->byte2 & SF_FMTDATA) {
5418 		if (cdb->byte2 & SF_LONGLIST)
5419 			length = sizeof(struct scsi_format_header_long);
5420 		else
5421 			length = sizeof(struct scsi_format_header_short);
5422 	}
5423 
5424 	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5425 	 && (length > 0)) {
5426 		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5427 		ctsio->kern_data_len = length;
5428 		ctsio->kern_total_len = length;
5429 		ctsio->kern_rel_offset = 0;
5430 		ctsio->kern_sg_entries = 0;
5431 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5432 		ctsio->be_move_done = ctl_config_move_done;
5433 		ctl_datamove((union ctl_io *)ctsio);
5434 
5435 		return (CTL_RETVAL_COMPLETE);
5436 	}
5437 
5438 	defect_list_len = 0;
5439 
5440 	if (cdb->byte2 & SF_FMTDATA) {
5441 		if (cdb->byte2 & SF_LONGLIST) {
5442 			struct scsi_format_header_long *header;
5443 
5444 			header = (struct scsi_format_header_long *)
5445 				ctsio->kern_data_ptr;
5446 
5447 			defect_list_len = scsi_4btoul(header->defect_list_len);
5448 			if (defect_list_len != 0) {
5449 				ctl_set_invalid_field(ctsio,
5450 						      /*sks_valid*/ 1,
5451 						      /*command*/ 0,
5452 						      /*field*/ 2,
5453 						      /*bit_valid*/ 0,
5454 						      /*bit*/ 0);
5455 				goto bailout;
5456 			}
5457 		} else {
5458 			struct scsi_format_header_short *header;
5459 
5460 			header = (struct scsi_format_header_short *)
5461 				ctsio->kern_data_ptr;
5462 
5463 			defect_list_len = scsi_2btoul(header->defect_list_len);
5464 			if (defect_list_len != 0) {
5465 				ctl_set_invalid_field(ctsio,
5466 						      /*sks_valid*/ 1,
5467 						      /*command*/ 0,
5468 						      /*field*/ 2,
5469 						      /*bit_valid*/ 0,
5470 						      /*bit*/ 0);
5471 				goto bailout;
5472 			}
5473 		}
5474 	}
5475 
5476 	ctl_set_success(ctsio);
5477 bailout:
5478 
5479 	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5480 		free(ctsio->kern_data_ptr, M_CTL);
5481 		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5482 	}
5483 
5484 	ctl_done((union ctl_io *)ctsio);
5485 	return (CTL_RETVAL_COMPLETE);
5486 }
5487 
5488 int
5489 ctl_read_buffer(struct ctl_scsiio *ctsio)
5490 {
5491 	struct ctl_lun *lun = CTL_LUN(ctsio);
5492 	uint64_t buffer_offset;
5493 	uint32_t len;
5494 	uint8_t byte2;
5495 	static uint8_t descr[4];
5496 	static uint8_t echo_descr[4] = { 0 };
5497 
5498 	CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5499 
5500 	switch (ctsio->cdb[0]) {
5501 	case READ_BUFFER: {
5502 		struct scsi_read_buffer *cdb;
5503 
5504 		cdb = (struct scsi_read_buffer *)ctsio->cdb;
5505 		buffer_offset = scsi_3btoul(cdb->offset);
5506 		len = scsi_3btoul(cdb->length);
5507 		byte2 = cdb->byte2;
5508 		break;
5509 	}
5510 	case READ_BUFFER_16: {
5511 		struct scsi_read_buffer_16 *cdb;
5512 
5513 		cdb = (struct scsi_read_buffer_16 *)ctsio->cdb;
5514 		buffer_offset = scsi_8btou64(cdb->offset);
5515 		len = scsi_4btoul(cdb->length);
5516 		byte2 = cdb->byte2;
5517 		break;
5518 	}
5519 	default: /* This shouldn't happen. */
5520 		ctl_set_invalid_opcode(ctsio);
5521 		ctl_done((union ctl_io *)ctsio);
5522 		return (CTL_RETVAL_COMPLETE);
5523 	}
5524 
5525 	if (buffer_offset > CTL_WRITE_BUFFER_SIZE ||
5526 	    buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5527 		ctl_set_invalid_field(ctsio,
5528 				      /*sks_valid*/ 1,
5529 				      /*command*/ 1,
5530 				      /*field*/ 6,
5531 				      /*bit_valid*/ 0,
5532 				      /*bit*/ 0);
5533 		ctl_done((union ctl_io *)ctsio);
5534 		return (CTL_RETVAL_COMPLETE);
5535 	}
5536 
5537 	if ((byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5538 		descr[0] = 0;
5539 		scsi_ulto3b(CTL_WRITE_BUFFER_SIZE, &descr[1]);
5540 		ctsio->kern_data_ptr = descr;
5541 		len = min(len, sizeof(descr));
5542 	} else if ((byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5543 		ctsio->kern_data_ptr = echo_descr;
5544 		len = min(len, sizeof(echo_descr));
5545 	} else {
5546 		if (lun->write_buffer == NULL) {
5547 			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5548 			    M_CTL, M_WAITOK);
5549 		}
5550 		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5551 	}
5552 	ctsio->kern_data_len = len;
5553 	ctsio->kern_total_len = len;
5554 	ctsio->kern_rel_offset = 0;
5555 	ctsio->kern_sg_entries = 0;
5556 	ctl_set_success(ctsio);
5557 	ctsio->be_move_done = ctl_config_move_done;
5558 	ctl_datamove((union ctl_io *)ctsio);
5559 	return (CTL_RETVAL_COMPLETE);
5560 }
5561 
5562 int
5563 ctl_write_buffer(struct ctl_scsiio *ctsio)
5564 {
5565 	struct ctl_lun *lun = CTL_LUN(ctsio);
5566 	struct scsi_write_buffer *cdb;
5567 	int buffer_offset, len;
5568 
5569 	CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5570 
5571 	cdb = (struct scsi_write_buffer *)ctsio->cdb;
5572 
5573 	len = scsi_3btoul(cdb->length);
5574 	buffer_offset = scsi_3btoul(cdb->offset);
5575 
5576 	if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5577 		ctl_set_invalid_field(ctsio,
5578 				      /*sks_valid*/ 1,
5579 				      /*command*/ 1,
5580 				      /*field*/ 6,
5581 				      /*bit_valid*/ 0,
5582 				      /*bit*/ 0);
5583 		ctl_done((union ctl_io *)ctsio);
5584 		return (CTL_RETVAL_COMPLETE);
5585 	}
5586 
5587 	/*
5588 	 * If we've got a kernel request that hasn't been malloced yet,
5589 	 * malloc it and tell the caller the data buffer is here.
5590 	 */
5591 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5592 		if (lun->write_buffer == NULL) {
5593 			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5594 			    M_CTL, M_WAITOK);
5595 		}
5596 		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5597 		ctsio->kern_data_len = len;
5598 		ctsio->kern_total_len = len;
5599 		ctsio->kern_rel_offset = 0;
5600 		ctsio->kern_sg_entries = 0;
5601 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5602 		ctsio->be_move_done = ctl_config_move_done;
5603 		ctl_datamove((union ctl_io *)ctsio);
5604 
5605 		return (CTL_RETVAL_COMPLETE);
5606 	}
5607 
5608 	ctl_set_success(ctsio);
5609 	ctl_done((union ctl_io *)ctsio);
5610 	return (CTL_RETVAL_COMPLETE);
5611 }
5612 
5613 static int
5614 ctl_write_same_cont(union ctl_io *io)
5615 {
5616 	struct ctl_lun *lun = CTL_LUN(io);
5617 	struct ctl_scsiio *ctsio;
5618 	struct ctl_lba_len_flags *lbalen;
5619 	int retval;
5620 
5621 	ctsio = &io->scsiio;
5622 	ctsio->io_hdr.status = CTL_STATUS_NONE;
5623 	lbalen = (struct ctl_lba_len_flags *)
5624 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5625 	lbalen->lba += lbalen->len;
5626 	if ((lun->be_lun->maxlba + 1) - lbalen->lba <= UINT32_MAX) {
5627 		ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
5628 		lbalen->len = (lun->be_lun->maxlba + 1) - lbalen->lba;
5629 	}
5630 
5631 	CTL_DEBUG_PRINT(("ctl_write_same_cont: calling config_write()\n"));
5632 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5633 	return (retval);
5634 }
5635 
5636 int
5637 ctl_write_same(struct ctl_scsiio *ctsio)
5638 {
5639 	struct ctl_lun *lun = CTL_LUN(ctsio);
5640 	struct ctl_lba_len_flags *lbalen;
5641 	const char *val;
5642 	uint64_t lba, ival;
5643 	uint32_t num_blocks;
5644 	int len, retval;
5645 	uint8_t byte2;
5646 
5647 	CTL_DEBUG_PRINT(("ctl_write_same\n"));
5648 
5649 	switch (ctsio->cdb[0]) {
5650 	case WRITE_SAME_10: {
5651 		struct scsi_write_same_10 *cdb;
5652 
5653 		cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5654 
5655 		lba = scsi_4btoul(cdb->addr);
5656 		num_blocks = scsi_2btoul(cdb->length);
5657 		byte2 = cdb->byte2;
5658 		break;
5659 	}
5660 	case WRITE_SAME_16: {
5661 		struct scsi_write_same_16 *cdb;
5662 
5663 		cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5664 
5665 		lba = scsi_8btou64(cdb->addr);
5666 		num_blocks = scsi_4btoul(cdb->length);
5667 		byte2 = cdb->byte2;
5668 		break;
5669 	}
5670 	default:
5671 		/*
5672 		 * We got a command we don't support.  This shouldn't
5673 		 * happen, commands should be filtered out above us.
5674 		 */
5675 		ctl_set_invalid_opcode(ctsio);
5676 		ctl_done((union ctl_io *)ctsio);
5677 
5678 		return (CTL_RETVAL_COMPLETE);
5679 		break; /* NOTREACHED */
5680 	}
5681 
5682 	/* ANCHOR flag can be used only together with UNMAP */
5683 	if ((byte2 & SWS_UNMAP) == 0 && (byte2 & SWS_ANCHOR) != 0) {
5684 		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
5685 		    /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
5686 		ctl_done((union ctl_io *)ctsio);
5687 		return (CTL_RETVAL_COMPLETE);
5688 	}
5689 
5690 	/*
5691 	 * The first check is to make sure we're in bounds, the second
5692 	 * check is to catch wrap-around problems.  If the lba + num blocks
5693 	 * is less than the lba, then we've wrapped around and the block
5694 	 * range is invalid anyway.
5695 	 */
5696 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5697 	 || ((lba + num_blocks) < lba)) {
5698 		ctl_set_lba_out_of_range(ctsio,
5699 		    MAX(lba, lun->be_lun->maxlba + 1));
5700 		ctl_done((union ctl_io *)ctsio);
5701 		return (CTL_RETVAL_COMPLETE);
5702 	}
5703 
5704 	/* Zero number of blocks means "to the last logical block" */
5705 	if (num_blocks == 0) {
5706 		ival = UINT64_MAX;
5707 		val = dnvlist_get_string(lun->be_lun->options,
5708 		    "write_same_max_lba", NULL);
5709 		if (val != NULL)
5710 			ctl_expand_number(val, &ival);
5711 		if ((lun->be_lun->maxlba + 1) - lba > ival) {
5712 			ctl_set_invalid_field(ctsio,
5713 			    /*sks_valid*/ 1, /*command*/ 1,
5714 			    /*field*/ ctsio->cdb[0] == WRITE_SAME_10 ? 7 : 10,
5715 			    /*bit_valid*/ 0, /*bit*/ 0);
5716 			ctl_done((union ctl_io *)ctsio);
5717 			return (CTL_RETVAL_COMPLETE);
5718 		}
5719 		if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5720 			ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
5721 			ctsio->io_cont = ctl_write_same_cont;
5722 			num_blocks = 1 << 31;
5723 		} else
5724 			num_blocks = (lun->be_lun->maxlba + 1) - lba;
5725 	}
5726 
5727 	len = lun->be_lun->blocksize;
5728 
5729 	/*
5730 	 * If we've got a kernel request that hasn't been malloced yet,
5731 	 * malloc it and tell the caller the data buffer is here.
5732 	 */
5733 	if ((byte2 & SWS_NDOB) == 0 &&
5734 	    (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5735 		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);
5736 		ctsio->kern_data_len = len;
5737 		ctsio->kern_total_len = len;
5738 		ctsio->kern_rel_offset = 0;
5739 		ctsio->kern_sg_entries = 0;
5740 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5741 		ctsio->be_move_done = ctl_config_move_done;
5742 		ctl_datamove((union ctl_io *)ctsio);
5743 
5744 		return (CTL_RETVAL_COMPLETE);
5745 	}
5746 
5747 	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5748 	lbalen->lba = lba;
5749 	lbalen->len = num_blocks;
5750 	lbalen->flags = byte2;
5751 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5752 
5753 	return (retval);
5754 }
5755 
5756 int
5757 ctl_unmap(struct ctl_scsiio *ctsio)
5758 {
5759 	struct ctl_lun *lun = CTL_LUN(ctsio);
5760 	struct scsi_unmap *cdb;
5761 	struct ctl_ptr_len_flags *ptrlen;
5762 	struct scsi_unmap_header *hdr;
5763 	struct scsi_unmap_desc *buf, *end, *endnz, *range;
5764 	uint64_t lba;
5765 	uint32_t num_blocks;
5766 	int len, retval;
5767 	uint8_t byte2;
5768 
5769 	CTL_DEBUG_PRINT(("ctl_unmap\n"));
5770 
5771 	cdb = (struct scsi_unmap *)ctsio->cdb;
5772 	len = scsi_2btoul(cdb->length);
5773 	byte2 = cdb->byte2;
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 ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5780 		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);
5781 		ctsio->kern_data_len = len;
5782 		ctsio->kern_total_len = len;
5783 		ctsio->kern_rel_offset = 0;
5784 		ctsio->kern_sg_entries = 0;
5785 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5786 		ctsio->be_move_done = ctl_config_move_done;
5787 		ctl_datamove((union ctl_io *)ctsio);
5788 
5789 		return (CTL_RETVAL_COMPLETE);
5790 	}
5791 
5792 	len = ctsio->kern_total_len - ctsio->kern_data_resid;
5793 	hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
5794 	if (len < sizeof (*hdr) ||
5795 	    len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
5796 	    len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
5797 	    scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
5798 		ctl_set_invalid_field(ctsio,
5799 				      /*sks_valid*/ 0,
5800 				      /*command*/ 0,
5801 				      /*field*/ 0,
5802 				      /*bit_valid*/ 0,
5803 				      /*bit*/ 0);
5804 		goto done;
5805 	}
5806 	len = scsi_2btoul(hdr->desc_length);
5807 	buf = (struct scsi_unmap_desc *)(hdr + 1);
5808 	end = buf + len / sizeof(*buf);
5809 
5810 	endnz = buf;
5811 	for (range = buf; range < end; range++) {
5812 		lba = scsi_8btou64(range->lba);
5813 		num_blocks = scsi_4btoul(range->length);
5814 		if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5815 		 || ((lba + num_blocks) < lba)) {
5816 			ctl_set_lba_out_of_range(ctsio,
5817 			    MAX(lba, lun->be_lun->maxlba + 1));
5818 			ctl_done((union ctl_io *)ctsio);
5819 			return (CTL_RETVAL_COMPLETE);
5820 		}
5821 		if (num_blocks != 0)
5822 			endnz = range + 1;
5823 	}
5824 
5825 	/*
5826 	 * Block backend can not handle zero last range.
5827 	 * Filter it out and return if there is nothing left.
5828 	 */
5829 	len = (uint8_t *)endnz - (uint8_t *)buf;
5830 	if (len == 0) {
5831 		ctl_set_success(ctsio);
5832 		goto done;
5833 	}
5834 
5835 	mtx_lock(&lun->lun_lock);
5836 	ptrlen = (struct ctl_ptr_len_flags *)
5837 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5838 	ptrlen->ptr = (void *)buf;
5839 	ptrlen->len = len;
5840 	ptrlen->flags = byte2;
5841 	ctl_try_unblock_others(lun, (union ctl_io *)ctsio, FALSE);
5842 	mtx_unlock(&lun->lun_lock);
5843 
5844 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5845 	return (retval);
5846 
5847 done:
5848 	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5849 		free(ctsio->kern_data_ptr, M_CTL);
5850 		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5851 	}
5852 	ctl_done((union ctl_io *)ctsio);
5853 	return (CTL_RETVAL_COMPLETE);
5854 }
5855 
5856 int
5857 ctl_default_page_handler(struct ctl_scsiio *ctsio,
5858 			 struct ctl_page_index *page_index, uint8_t *page_ptr)
5859 {
5860 	struct ctl_lun *lun = CTL_LUN(ctsio);
5861 	uint8_t *current_cp;
5862 	int set_ua;
5863 	uint32_t initidx;
5864 
5865 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5866 	set_ua = 0;
5867 
5868 	current_cp = (page_index->page_data + (page_index->page_len *
5869 	    CTL_PAGE_CURRENT));
5870 
5871 	mtx_lock(&lun->lun_lock);
5872 	if (memcmp(current_cp, page_ptr, page_index->page_len)) {
5873 		memcpy(current_cp, page_ptr, page_index->page_len);
5874 		set_ua = 1;
5875 	}
5876 	if (set_ua != 0)
5877 		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
5878 	mtx_unlock(&lun->lun_lock);
5879 	if (set_ua) {
5880 		ctl_isc_announce_mode(lun,
5881 		    ctl_get_initindex(&ctsio->io_hdr.nexus),
5882 		    page_index->page_code, page_index->subpage);
5883 	}
5884 	return (CTL_RETVAL_COMPLETE);
5885 }
5886 
5887 static void
5888 ctl_ie_timer(void *arg)
5889 {
5890 	struct ctl_lun *lun = arg;
5891 	uint64_t t;
5892 
5893 	if (lun->ie_asc == 0)
5894 		return;
5895 
5896 	if (lun->MODE_IE.mrie == SIEP_MRIE_UA)
5897 		ctl_est_ua_all(lun, -1, CTL_UA_IE);
5898 	else
5899 		lun->ie_reported = 0;
5900 
5901 	if (lun->ie_reportcnt < scsi_4btoul(lun->MODE_IE.report_count)) {
5902 		lun->ie_reportcnt++;
5903 		t = scsi_4btoul(lun->MODE_IE.interval_timer);
5904 		if (t == 0 || t == UINT32_MAX)
5905 			t = 3000;  /* 5 min */
5906 		callout_schedule(&lun->ie_callout, t * hz / 10);
5907 	}
5908 }
5909 
5910 int
5911 ctl_ie_page_handler(struct ctl_scsiio *ctsio,
5912 			 struct ctl_page_index *page_index, uint8_t *page_ptr)
5913 {
5914 	struct ctl_lun *lun = CTL_LUN(ctsio);
5915 	struct scsi_info_exceptions_page *pg;
5916 	uint64_t t;
5917 
5918 	(void)ctl_default_page_handler(ctsio, page_index, page_ptr);
5919 
5920 	pg = (struct scsi_info_exceptions_page *)page_ptr;
5921 	mtx_lock(&lun->lun_lock);
5922 	if (pg->info_flags & SIEP_FLAGS_TEST) {
5923 		lun->ie_asc = 0x5d;
5924 		lun->ie_ascq = 0xff;
5925 		if (pg->mrie == SIEP_MRIE_UA) {
5926 			ctl_est_ua_all(lun, -1, CTL_UA_IE);
5927 			lun->ie_reported = 1;
5928 		} else {
5929 			ctl_clr_ua_all(lun, -1, CTL_UA_IE);
5930 			lun->ie_reported = -1;
5931 		}
5932 		lun->ie_reportcnt = 1;
5933 		if (lun->ie_reportcnt < scsi_4btoul(pg->report_count)) {
5934 			lun->ie_reportcnt++;
5935 			t = scsi_4btoul(pg->interval_timer);
5936 			if (t == 0 || t == UINT32_MAX)
5937 				t = 3000;  /* 5 min */
5938 			callout_reset(&lun->ie_callout, t * hz / 10,
5939 			    ctl_ie_timer, lun);
5940 		}
5941 	} else {
5942 		lun->ie_asc = 0;
5943 		lun->ie_ascq = 0;
5944 		lun->ie_reported = 1;
5945 		ctl_clr_ua_all(lun, -1, CTL_UA_IE);
5946 		lun->ie_reportcnt = UINT32_MAX;
5947 		callout_stop(&lun->ie_callout);
5948 	}
5949 	mtx_unlock(&lun->lun_lock);
5950 	return (CTL_RETVAL_COMPLETE);
5951 }
5952 
5953 static int
5954 ctl_do_mode_select(union ctl_io *io)
5955 {
5956 	struct ctl_lun *lun = CTL_LUN(io);
5957 	struct scsi_mode_page_header *page_header;
5958 	struct ctl_page_index *page_index;
5959 	struct ctl_scsiio *ctsio;
5960 	int page_len, page_len_offset, page_len_size;
5961 	union ctl_modepage_info *modepage_info;
5962 	uint16_t *len_left, *len_used;
5963 	int retval, i;
5964 
5965 	ctsio = &io->scsiio;
5966 	page_index = NULL;
5967 	page_len = 0;
5968 
5969 	modepage_info = (union ctl_modepage_info *)
5970 		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
5971 	len_left = &modepage_info->header.len_left;
5972 	len_used = &modepage_info->header.len_used;
5973 
5974 do_next_page:
5975 
5976 	page_header = (struct scsi_mode_page_header *)
5977 		(ctsio->kern_data_ptr + *len_used);
5978 
5979 	if (*len_left == 0) {
5980 		free(ctsio->kern_data_ptr, M_CTL);
5981 		ctl_set_success(ctsio);
5982 		ctl_done((union ctl_io *)ctsio);
5983 		return (CTL_RETVAL_COMPLETE);
5984 	} else if (*len_left < sizeof(struct scsi_mode_page_header)) {
5985 		free(ctsio->kern_data_ptr, M_CTL);
5986 		ctl_set_param_len_error(ctsio);
5987 		ctl_done((union ctl_io *)ctsio);
5988 		return (CTL_RETVAL_COMPLETE);
5989 
5990 	} else if ((page_header->page_code & SMPH_SPF)
5991 		&& (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
5992 		free(ctsio->kern_data_ptr, M_CTL);
5993 		ctl_set_param_len_error(ctsio);
5994 		ctl_done((union ctl_io *)ctsio);
5995 		return (CTL_RETVAL_COMPLETE);
5996 	}
5997 
5998 	/*
5999 	 * XXX KDM should we do something with the block descriptor?
6000 	 */
6001 	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6002 		page_index = &lun->mode_pages.index[i];
6003 		if (lun->be_lun->lun_type == T_DIRECT &&
6004 		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6005 			continue;
6006 		if (lun->be_lun->lun_type == T_PROCESSOR &&
6007 		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6008 			continue;
6009 		if (lun->be_lun->lun_type == T_CDROM &&
6010 		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6011 			continue;
6012 
6013 		if ((page_index->page_code & SMPH_PC_MASK) !=
6014 		    (page_header->page_code & SMPH_PC_MASK))
6015 			continue;
6016 
6017 		/*
6018 		 * If neither page has a subpage code, then we've got a
6019 		 * match.
6020 		 */
6021 		if (((page_index->page_code & SMPH_SPF) == 0)
6022 		 && ((page_header->page_code & SMPH_SPF) == 0)) {
6023 			page_len = page_header->page_length;
6024 			break;
6025 		}
6026 
6027 		/*
6028 		 * If both pages have subpages, then the subpage numbers
6029 		 * have to match.
6030 		 */
6031 		if ((page_index->page_code & SMPH_SPF)
6032 		  && (page_header->page_code & SMPH_SPF)) {
6033 			struct scsi_mode_page_header_sp *sph;
6034 
6035 			sph = (struct scsi_mode_page_header_sp *)page_header;
6036 			if (page_index->subpage == sph->subpage) {
6037 				page_len = scsi_2btoul(sph->page_length);
6038 				break;
6039 			}
6040 		}
6041 	}
6042 
6043 	/*
6044 	 * If we couldn't find the page, or if we don't have a mode select
6045 	 * handler for it, send back an error to the user.
6046 	 */
6047 	if ((i >= CTL_NUM_MODE_PAGES)
6048 	 || (page_index->select_handler == NULL)) {
6049 		ctl_set_invalid_field(ctsio,
6050 				      /*sks_valid*/ 1,
6051 				      /*command*/ 0,
6052 				      /*field*/ *len_used,
6053 				      /*bit_valid*/ 0,
6054 				      /*bit*/ 0);
6055 		free(ctsio->kern_data_ptr, M_CTL);
6056 		ctl_done((union ctl_io *)ctsio);
6057 		return (CTL_RETVAL_COMPLETE);
6058 	}
6059 
6060 	if (page_index->page_code & SMPH_SPF) {
6061 		page_len_offset = 2;
6062 		page_len_size = 2;
6063 	} else {
6064 		page_len_size = 1;
6065 		page_len_offset = 1;
6066 	}
6067 
6068 	/*
6069 	 * If the length the initiator gives us isn't the one we specify in
6070 	 * the mode page header, or if they didn't specify enough data in
6071 	 * the CDB to avoid truncating this page, kick out the request.
6072 	 */
6073 	if (page_len != page_index->page_len - page_len_offset - page_len_size) {
6074 		ctl_set_invalid_field(ctsio,
6075 				      /*sks_valid*/ 1,
6076 				      /*command*/ 0,
6077 				      /*field*/ *len_used + page_len_offset,
6078 				      /*bit_valid*/ 0,
6079 				      /*bit*/ 0);
6080 		free(ctsio->kern_data_ptr, M_CTL);
6081 		ctl_done((union ctl_io *)ctsio);
6082 		return (CTL_RETVAL_COMPLETE);
6083 	}
6084 	if (*len_left < page_index->page_len) {
6085 		free(ctsio->kern_data_ptr, M_CTL);
6086 		ctl_set_param_len_error(ctsio);
6087 		ctl_done((union ctl_io *)ctsio);
6088 		return (CTL_RETVAL_COMPLETE);
6089 	}
6090 
6091 	/*
6092 	 * Run through the mode page, checking to make sure that the bits
6093 	 * the user changed are actually legal for him to change.
6094 	 */
6095 	for (i = 0; i < page_index->page_len; i++) {
6096 		uint8_t *user_byte, *change_mask, *current_byte;
6097 		int bad_bit;
6098 		int j;
6099 
6100 		user_byte = (uint8_t *)page_header + i;
6101 		change_mask = page_index->page_data +
6102 			      (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6103 		current_byte = page_index->page_data +
6104 			       (page_index->page_len * CTL_PAGE_CURRENT) + i;
6105 
6106 		/*
6107 		 * Check to see whether the user set any bits in this byte
6108 		 * that he is not allowed to set.
6109 		 */
6110 		if ((*user_byte & ~(*change_mask)) ==
6111 		    (*current_byte & ~(*change_mask)))
6112 			continue;
6113 
6114 		/*
6115 		 * Go through bit by bit to determine which one is illegal.
6116 		 */
6117 		bad_bit = 0;
6118 		for (j = 7; j >= 0; j--) {
6119 			if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6120 			    (((1 << i) & ~(*change_mask)) & *current_byte)) {
6121 				bad_bit = i;
6122 				break;
6123 			}
6124 		}
6125 		ctl_set_invalid_field(ctsio,
6126 				      /*sks_valid*/ 1,
6127 				      /*command*/ 0,
6128 				      /*field*/ *len_used + i,
6129 				      /*bit_valid*/ 1,
6130 				      /*bit*/ bad_bit);
6131 		free(ctsio->kern_data_ptr, M_CTL);
6132 		ctl_done((union ctl_io *)ctsio);
6133 		return (CTL_RETVAL_COMPLETE);
6134 	}
6135 
6136 	/*
6137 	 * Decrement these before we call the page handler, since we may
6138 	 * end up getting called back one way or another before the handler
6139 	 * returns to this context.
6140 	 */
6141 	*len_left -= page_index->page_len;
6142 	*len_used += page_index->page_len;
6143 
6144 	retval = page_index->select_handler(ctsio, page_index,
6145 					    (uint8_t *)page_header);
6146 
6147 	/*
6148 	 * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6149 	 * wait until this queued command completes to finish processing
6150 	 * the mode page.  If it returns anything other than
6151 	 * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6152 	 * already set the sense information, freed the data pointer, and
6153 	 * completed the io for us.
6154 	 */
6155 	if (retval != CTL_RETVAL_COMPLETE)
6156 		goto bailout_no_done;
6157 
6158 	/*
6159 	 * If the initiator sent us more than one page, parse the next one.
6160 	 */
6161 	if (*len_left > 0)
6162 		goto do_next_page;
6163 
6164 	ctl_set_success(ctsio);
6165 	free(ctsio->kern_data_ptr, M_CTL);
6166 	ctl_done((union ctl_io *)ctsio);
6167 
6168 bailout_no_done:
6169 
6170 	return (CTL_RETVAL_COMPLETE);
6171 
6172 }
6173 
6174 int
6175 ctl_mode_select(struct ctl_scsiio *ctsio)
6176 {
6177 	struct ctl_lun *lun = CTL_LUN(ctsio);
6178 	union ctl_modepage_info *modepage_info;
6179 	int bd_len, i, header_size, param_len, rtd;
6180 	uint32_t initidx;
6181 
6182 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6183 	switch (ctsio->cdb[0]) {
6184 	case MODE_SELECT_6: {
6185 		struct scsi_mode_select_6 *cdb;
6186 
6187 		cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6188 
6189 		rtd = (cdb->byte2 & SMS_RTD) ? 1 : 0;
6190 		param_len = cdb->length;
6191 		header_size = sizeof(struct scsi_mode_header_6);
6192 		break;
6193 	}
6194 	case MODE_SELECT_10: {
6195 		struct scsi_mode_select_10 *cdb;
6196 
6197 		cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6198 
6199 		rtd = (cdb->byte2 & SMS_RTD) ? 1 : 0;
6200 		param_len = scsi_2btoul(cdb->length);
6201 		header_size = sizeof(struct scsi_mode_header_10);
6202 		break;
6203 	}
6204 	default:
6205 		ctl_set_invalid_opcode(ctsio);
6206 		ctl_done((union ctl_io *)ctsio);
6207 		return (CTL_RETVAL_COMPLETE);
6208 	}
6209 
6210 	if (rtd) {
6211 		if (param_len != 0) {
6212 			ctl_set_invalid_field(ctsio, /*sks_valid*/ 0,
6213 			    /*command*/ 1, /*field*/ 0,
6214 			    /*bit_valid*/ 0, /*bit*/ 0);
6215 			ctl_done((union ctl_io *)ctsio);
6216 			return (CTL_RETVAL_COMPLETE);
6217 		}
6218 
6219 		/* Revert to defaults. */
6220 		ctl_init_page_index(lun);
6221 		mtx_lock(&lun->lun_lock);
6222 		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
6223 		mtx_unlock(&lun->lun_lock);
6224 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6225 			ctl_isc_announce_mode(lun, -1,
6226 			    lun->mode_pages.index[i].page_code & SMPH_PC_MASK,
6227 			    lun->mode_pages.index[i].subpage);
6228 		}
6229 		ctl_set_success(ctsio);
6230 		ctl_done((union ctl_io *)ctsio);
6231 		return (CTL_RETVAL_COMPLETE);
6232 	}
6233 
6234 	/*
6235 	 * From SPC-3:
6236 	 * "A parameter list length of zero indicates that the Data-Out Buffer
6237 	 * shall be empty. This condition shall not be considered as an error."
6238 	 */
6239 	if (param_len == 0) {
6240 		ctl_set_success(ctsio);
6241 		ctl_done((union ctl_io *)ctsio);
6242 		return (CTL_RETVAL_COMPLETE);
6243 	}
6244 
6245 	/*
6246 	 * Since we'll hit this the first time through, prior to
6247 	 * allocation, we don't need to free a data buffer here.
6248 	 */
6249 	if (param_len < header_size) {
6250 		ctl_set_param_len_error(ctsio);
6251 		ctl_done((union ctl_io *)ctsio);
6252 		return (CTL_RETVAL_COMPLETE);
6253 	}
6254 
6255 	/*
6256 	 * Allocate the data buffer and grab the user's data.  In theory,
6257 	 * we shouldn't have to sanity check the parameter list length here
6258 	 * because the maximum size is 64K.  We should be able to malloc
6259 	 * that much without too many problems.
6260 	 */
6261 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6262 		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6263 		ctsio->kern_data_len = param_len;
6264 		ctsio->kern_total_len = param_len;
6265 		ctsio->kern_rel_offset = 0;
6266 		ctsio->kern_sg_entries = 0;
6267 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6268 		ctsio->be_move_done = ctl_config_move_done;
6269 		ctl_datamove((union ctl_io *)ctsio);
6270 
6271 		return (CTL_RETVAL_COMPLETE);
6272 	}
6273 
6274 	switch (ctsio->cdb[0]) {
6275 	case MODE_SELECT_6: {
6276 		struct scsi_mode_header_6 *mh6;
6277 
6278 		mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6279 		bd_len = mh6->blk_desc_len;
6280 		break;
6281 	}
6282 	case MODE_SELECT_10: {
6283 		struct scsi_mode_header_10 *mh10;
6284 
6285 		mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6286 		bd_len = scsi_2btoul(mh10->blk_desc_len);
6287 		break;
6288 	}
6289 	default:
6290 		panic("%s: Invalid CDB type %#x", __func__, ctsio->cdb[0]);
6291 	}
6292 
6293 	if (param_len < (header_size + bd_len)) {
6294 		free(ctsio->kern_data_ptr, M_CTL);
6295 		ctl_set_param_len_error(ctsio);
6296 		ctl_done((union ctl_io *)ctsio);
6297 		return (CTL_RETVAL_COMPLETE);
6298 	}
6299 
6300 	/*
6301 	 * Set the IO_CONT flag, so that if this I/O gets passed to
6302 	 * ctl_config_write_done(), it'll get passed back to
6303 	 * ctl_do_mode_select() for further processing, or completion if
6304 	 * we're all done.
6305 	 */
6306 	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6307 	ctsio->io_cont = ctl_do_mode_select;
6308 
6309 	modepage_info = (union ctl_modepage_info *)
6310 		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6311 	memset(modepage_info, 0, sizeof(*modepage_info));
6312 	modepage_info->header.len_left = param_len - header_size - bd_len;
6313 	modepage_info->header.len_used = header_size + bd_len;
6314 
6315 	return (ctl_do_mode_select((union ctl_io *)ctsio));
6316 }
6317 
6318 int
6319 ctl_mode_sense(struct ctl_scsiio *ctsio)
6320 {
6321 	struct ctl_lun *lun = CTL_LUN(ctsio);
6322 	int pc, page_code, llba, subpage;
6323 	int alloc_len, page_len, header_len, bd_len, total_len;
6324 	void *block_desc;
6325 	struct ctl_page_index *page_index;
6326 
6327 	llba = 0;
6328 
6329 	CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6330 
6331 	switch (ctsio->cdb[0]) {
6332 	case MODE_SENSE_6: {
6333 		struct scsi_mode_sense_6 *cdb;
6334 
6335 		cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6336 
6337 		header_len = sizeof(struct scsi_mode_hdr_6);
6338 		if (cdb->byte2 & SMS_DBD)
6339 			bd_len = 0;
6340 		else
6341 			bd_len = sizeof(struct scsi_mode_block_descr);
6342 		header_len += bd_len;
6343 
6344 		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6345 		page_code = cdb->page & SMS_PAGE_CODE;
6346 		subpage = cdb->subpage;
6347 		alloc_len = cdb->length;
6348 		break;
6349 	}
6350 	case MODE_SENSE_10: {
6351 		struct scsi_mode_sense_10 *cdb;
6352 
6353 		cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6354 
6355 		header_len = sizeof(struct scsi_mode_hdr_10);
6356 		if (cdb->byte2 & SMS_DBD) {
6357 			bd_len = 0;
6358 		} else if (lun->be_lun->lun_type == T_DIRECT) {
6359 			if (cdb->byte2 & SMS10_LLBAA) {
6360 				llba = 1;
6361 				bd_len = sizeof(struct scsi_mode_block_descr_dlong);
6362 			} else
6363 				bd_len = sizeof(struct scsi_mode_block_descr_dshort);
6364 		} else
6365 			bd_len = sizeof(struct scsi_mode_block_descr);
6366 		header_len += bd_len;
6367 
6368 		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6369 		page_code = cdb->page & SMS_PAGE_CODE;
6370 		subpage = cdb->subpage;
6371 		alloc_len = scsi_2btoul(cdb->length);
6372 		break;
6373 	}
6374 	default:
6375 		ctl_set_invalid_opcode(ctsio);
6376 		ctl_done((union ctl_io *)ctsio);
6377 		return (CTL_RETVAL_COMPLETE);
6378 		break; /* NOTREACHED */
6379 	}
6380 
6381 	/*
6382 	 * We have to make a first pass through to calculate the size of
6383 	 * the pages that match the user's query.  Then we allocate enough
6384 	 * memory to hold it, and actually copy the data into the buffer.
6385 	 */
6386 	switch (page_code) {
6387 	case SMS_ALL_PAGES_PAGE: {
6388 		u_int i;
6389 
6390 		page_len = 0;
6391 
6392 		/*
6393 		 * At the moment, values other than 0 and 0xff here are
6394 		 * reserved according to SPC-3.
6395 		 */
6396 		if ((subpage != SMS_SUBPAGE_PAGE_0)
6397 		 && (subpage != SMS_SUBPAGE_ALL)) {
6398 			ctl_set_invalid_field(ctsio,
6399 					      /*sks_valid*/ 1,
6400 					      /*command*/ 1,
6401 					      /*field*/ 3,
6402 					      /*bit_valid*/ 0,
6403 					      /*bit*/ 0);
6404 			ctl_done((union ctl_io *)ctsio);
6405 			return (CTL_RETVAL_COMPLETE);
6406 		}
6407 
6408 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6409 			page_index = &lun->mode_pages.index[i];
6410 
6411 			/* Make sure the page is supported for this dev type */
6412 			if (lun->be_lun->lun_type == T_DIRECT &&
6413 			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6414 				continue;
6415 			if (lun->be_lun->lun_type == T_PROCESSOR &&
6416 			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6417 				continue;
6418 			if (lun->be_lun->lun_type == T_CDROM &&
6419 			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6420 				continue;
6421 
6422 			/*
6423 			 * We don't use this subpage if the user didn't
6424 			 * request all subpages.
6425 			 */
6426 			if ((page_index->subpage != 0)
6427 			 && (subpage == SMS_SUBPAGE_PAGE_0))
6428 				continue;
6429 
6430 			page_len += page_index->page_len;
6431 		}
6432 		break;
6433 	}
6434 	default: {
6435 		u_int i;
6436 
6437 		page_len = 0;
6438 
6439 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6440 			page_index = &lun->mode_pages.index[i];
6441 
6442 			/* Make sure the page is supported for this dev type */
6443 			if (lun->be_lun->lun_type == T_DIRECT &&
6444 			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6445 				continue;
6446 			if (lun->be_lun->lun_type == T_PROCESSOR &&
6447 			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6448 				continue;
6449 			if (lun->be_lun->lun_type == T_CDROM &&
6450 			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6451 				continue;
6452 
6453 			/* Look for the right page code */
6454 			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6455 				continue;
6456 
6457 			/* Look for the right subpage or the subpage wildcard*/
6458 			if ((page_index->subpage != subpage)
6459 			 && (subpage != SMS_SUBPAGE_ALL))
6460 				continue;
6461 
6462 			page_len += page_index->page_len;
6463 		}
6464 
6465 		if (page_len == 0) {
6466 			ctl_set_invalid_field(ctsio,
6467 					      /*sks_valid*/ 1,
6468 					      /*command*/ 1,
6469 					      /*field*/ 2,
6470 					      /*bit_valid*/ 1,
6471 					      /*bit*/ 5);
6472 			ctl_done((union ctl_io *)ctsio);
6473 			return (CTL_RETVAL_COMPLETE);
6474 		}
6475 		break;
6476 	}
6477 	}
6478 
6479 	total_len = header_len + page_len;
6480 
6481 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6482 	ctsio->kern_sg_entries = 0;
6483 	ctsio->kern_rel_offset = 0;
6484 	ctsio->kern_data_len = min(total_len, alloc_len);
6485 	ctsio->kern_total_len = ctsio->kern_data_len;
6486 
6487 	switch (ctsio->cdb[0]) {
6488 	case MODE_SENSE_6: {
6489 		struct scsi_mode_hdr_6 *header;
6490 
6491 		header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6492 
6493 		header->datalen = MIN(total_len - 1, 254);
6494 		if (lun->be_lun->lun_type == T_DIRECT) {
6495 			header->dev_specific = 0x10; /* DPOFUA */
6496 			if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6497 			    (lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0)
6498 				header->dev_specific |= 0x80; /* WP */
6499 		}
6500 		header->block_descr_len = bd_len;
6501 		block_desc = &header[1];
6502 		break;
6503 	}
6504 	case MODE_SENSE_10: {
6505 		struct scsi_mode_hdr_10 *header;
6506 		int datalen;
6507 
6508 		header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6509 
6510 		datalen = MIN(total_len - 2, 65533);
6511 		scsi_ulto2b(datalen, header->datalen);
6512 		if (lun->be_lun->lun_type == T_DIRECT) {
6513 			header->dev_specific = 0x10; /* DPOFUA */
6514 			if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6515 			    (lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0)
6516 				header->dev_specific |= 0x80; /* WP */
6517 		}
6518 		if (llba)
6519 			header->flags |= SMH_LONGLBA;
6520 		scsi_ulto2b(bd_len, header->block_descr_len);
6521 		block_desc = &header[1];
6522 		break;
6523 	}
6524 	default:
6525 		panic("%s: Invalid CDB type %#x", __func__, ctsio->cdb[0]);
6526 	}
6527 
6528 	/*
6529 	 * If we've got a disk, use its blocksize in the block
6530 	 * descriptor.  Otherwise, just set it to 0.
6531 	 */
6532 	if (bd_len > 0) {
6533 		if (lun->be_lun->lun_type == T_DIRECT) {
6534 			if (llba) {
6535 				struct scsi_mode_block_descr_dlong *bd = block_desc;
6536 				if (lun->be_lun->maxlba != 0)
6537 					scsi_u64to8b(lun->be_lun->maxlba + 1,
6538 					    bd->num_blocks);
6539 				scsi_ulto4b(lun->be_lun->blocksize,
6540 				    bd->block_len);
6541 			} else {
6542 				struct scsi_mode_block_descr_dshort *bd = block_desc;
6543 				if (lun->be_lun->maxlba != 0)
6544 					scsi_ulto4b(MIN(lun->be_lun->maxlba+1,
6545 					    UINT32_MAX), bd->num_blocks);
6546 				scsi_ulto3b(lun->be_lun->blocksize,
6547 				    bd->block_len);
6548 			}
6549 		} else {
6550 			struct scsi_mode_block_descr *bd = block_desc;
6551 			scsi_ulto3b(0, bd->block_len);
6552 		}
6553 	}
6554 
6555 	switch (page_code) {
6556 	case SMS_ALL_PAGES_PAGE: {
6557 		int i, data_used;
6558 
6559 		data_used = header_len;
6560 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6561 			struct ctl_page_index *page_index;
6562 
6563 			page_index = &lun->mode_pages.index[i];
6564 			if (lun->be_lun->lun_type == T_DIRECT &&
6565 			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6566 				continue;
6567 			if (lun->be_lun->lun_type == T_PROCESSOR &&
6568 			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6569 				continue;
6570 			if (lun->be_lun->lun_type == T_CDROM &&
6571 			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6572 				continue;
6573 
6574 			/*
6575 			 * We don't use this subpage if the user didn't
6576 			 * request all subpages.  We already checked (above)
6577 			 * to make sure the user only specified a subpage
6578 			 * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
6579 			 */
6580 			if ((page_index->subpage != 0)
6581 			 && (subpage == SMS_SUBPAGE_PAGE_0))
6582 				continue;
6583 
6584 			/*
6585 			 * Call the handler, if it exists, to update the
6586 			 * page to the latest values.
6587 			 */
6588 			if (page_index->sense_handler != NULL)
6589 				page_index->sense_handler(ctsio, page_index,pc);
6590 
6591 			memcpy(ctsio->kern_data_ptr + data_used,
6592 			       page_index->page_data +
6593 			       (page_index->page_len * pc),
6594 			       page_index->page_len);
6595 			data_used += page_index->page_len;
6596 		}
6597 		break;
6598 	}
6599 	default: {
6600 		int i, data_used;
6601 
6602 		data_used = header_len;
6603 
6604 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6605 			struct ctl_page_index *page_index;
6606 
6607 			page_index = &lun->mode_pages.index[i];
6608 
6609 			/* Look for the right page code */
6610 			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6611 				continue;
6612 
6613 			/* Look for the right subpage or the subpage wildcard*/
6614 			if ((page_index->subpage != subpage)
6615 			 && (subpage != SMS_SUBPAGE_ALL))
6616 				continue;
6617 
6618 			/* Make sure the page is supported for this dev type */
6619 			if (lun->be_lun->lun_type == T_DIRECT &&
6620 			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6621 				continue;
6622 			if (lun->be_lun->lun_type == T_PROCESSOR &&
6623 			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6624 				continue;
6625 			if (lun->be_lun->lun_type == T_CDROM &&
6626 			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6627 				continue;
6628 
6629 			/*
6630 			 * Call the handler, if it exists, to update the
6631 			 * page to the latest values.
6632 			 */
6633 			if (page_index->sense_handler != NULL)
6634 				page_index->sense_handler(ctsio, page_index,pc);
6635 
6636 			memcpy(ctsio->kern_data_ptr + data_used,
6637 			       page_index->page_data +
6638 			       (page_index->page_len * pc),
6639 			       page_index->page_len);
6640 			data_used += page_index->page_len;
6641 		}
6642 		break;
6643 	}
6644 	}
6645 
6646 	ctl_set_success(ctsio);
6647 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6648 	ctsio->be_move_done = ctl_config_move_done;
6649 	ctl_datamove((union ctl_io *)ctsio);
6650 	return (CTL_RETVAL_COMPLETE);
6651 }
6652 
6653 int
6654 ctl_temp_log_sense_handler(struct ctl_scsiio *ctsio,
6655 			       struct ctl_page_index *page_index,
6656 			       int pc)
6657 {
6658 	struct ctl_lun *lun = CTL_LUN(ctsio);
6659 	struct scsi_log_temperature *data;
6660 	const char *value;
6661 
6662 	data = (struct scsi_log_temperature *)page_index->page_data;
6663 
6664 	scsi_ulto2b(SLP_TEMPERATURE, data->hdr.param_code);
6665 	data->hdr.param_control = SLP_LBIN;
6666 	data->hdr.param_len = sizeof(struct scsi_log_temperature) -
6667 	    sizeof(struct scsi_log_param_header);
6668 	if ((value = dnvlist_get_string(lun->be_lun->options, "temperature",
6669 	    NULL)) != NULL)
6670 		data->temperature = strtol(value, NULL, 0);
6671 	else
6672 		data->temperature = 0xff;
6673 	data++;
6674 
6675 	scsi_ulto2b(SLP_REFTEMPERATURE, data->hdr.param_code);
6676 	data->hdr.param_control = SLP_LBIN;
6677 	data->hdr.param_len = sizeof(struct scsi_log_temperature) -
6678 	    sizeof(struct scsi_log_param_header);
6679 	if ((value = dnvlist_get_string(lun->be_lun->options, "reftemperature",
6680 	    NULL)) != NULL)
6681 		data->temperature = strtol(value, NULL, 0);
6682 	else
6683 		data->temperature = 0xff;
6684 	return (0);
6685 }
6686 
6687 int
6688 ctl_lbp_log_sense_handler(struct ctl_scsiio *ctsio,
6689 			       struct ctl_page_index *page_index,
6690 			       int pc)
6691 {
6692 	struct ctl_lun *lun = CTL_LUN(ctsio);
6693 	struct scsi_log_param_header *phdr;
6694 	uint8_t *data;
6695 	uint64_t val;
6696 
6697 	data = page_index->page_data;
6698 
6699 	if (lun->backend->lun_attr != NULL &&
6700 	    (val = lun->backend->lun_attr(lun->be_lun, "blocksavail"))
6701 	     != UINT64_MAX) {
6702 		phdr = (struct scsi_log_param_header *)data;
6703 		scsi_ulto2b(0x0001, phdr->param_code);
6704 		phdr->param_control = SLP_LBIN | SLP_LP;
6705 		phdr->param_len = 8;
6706 		data = (uint8_t *)(phdr + 1);
6707 		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6708 		data[4] = 0x02; /* per-pool */
6709 		data += phdr->param_len;
6710 	}
6711 
6712 	if (lun->backend->lun_attr != NULL &&
6713 	    (val = lun->backend->lun_attr(lun->be_lun, "blocksused"))
6714 	     != UINT64_MAX) {
6715 		phdr = (struct scsi_log_param_header *)data;
6716 		scsi_ulto2b(0x0002, phdr->param_code);
6717 		phdr->param_control = SLP_LBIN | SLP_LP;
6718 		phdr->param_len = 8;
6719 		data = (uint8_t *)(phdr + 1);
6720 		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6721 		data[4] = 0x01; /* per-LUN */
6722 		data += phdr->param_len;
6723 	}
6724 
6725 	if (lun->backend->lun_attr != NULL &&
6726 	    (val = lun->backend->lun_attr(lun->be_lun, "poolblocksavail"))
6727 	     != UINT64_MAX) {
6728 		phdr = (struct scsi_log_param_header *)data;
6729 		scsi_ulto2b(0x00f1, phdr->param_code);
6730 		phdr->param_control = SLP_LBIN | SLP_LP;
6731 		phdr->param_len = 8;
6732 		data = (uint8_t *)(phdr + 1);
6733 		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6734 		data[4] = 0x02; /* per-pool */
6735 		data += phdr->param_len;
6736 	}
6737 
6738 	if (lun->backend->lun_attr != NULL &&
6739 	    (val = lun->backend->lun_attr(lun->be_lun, "poolblocksused"))
6740 	     != UINT64_MAX) {
6741 		phdr = (struct scsi_log_param_header *)data;
6742 		scsi_ulto2b(0x00f2, phdr->param_code);
6743 		phdr->param_control = SLP_LBIN | SLP_LP;
6744 		phdr->param_len = 8;
6745 		data = (uint8_t *)(phdr + 1);
6746 		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6747 		data[4] = 0x02; /* per-pool */
6748 		data += phdr->param_len;
6749 	}
6750 
6751 	page_index->page_len = data - page_index->page_data;
6752 	return (0);
6753 }
6754 
6755 int
6756 ctl_sap_log_sense_handler(struct ctl_scsiio *ctsio,
6757 			       struct ctl_page_index *page_index,
6758 			       int pc)
6759 {
6760 	struct ctl_lun *lun = CTL_LUN(ctsio);
6761 	struct stat_page *data;
6762 	struct bintime *t;
6763 
6764 	data = (struct stat_page *)page_index->page_data;
6765 
6766 	scsi_ulto2b(SLP_SAP, data->sap.hdr.param_code);
6767 	data->sap.hdr.param_control = SLP_LBIN;
6768 	data->sap.hdr.param_len = sizeof(struct scsi_log_stat_and_perf) -
6769 	    sizeof(struct scsi_log_param_header);
6770 	scsi_u64to8b(lun->stats.operations[CTL_STATS_READ],
6771 	    data->sap.read_num);
6772 	scsi_u64to8b(lun->stats.operations[CTL_STATS_WRITE],
6773 	    data->sap.write_num);
6774 	if (lun->be_lun->blocksize > 0) {
6775 		scsi_u64to8b(lun->stats.bytes[CTL_STATS_WRITE] /
6776 		    lun->be_lun->blocksize, data->sap.recvieved_lba);
6777 		scsi_u64to8b(lun->stats.bytes[CTL_STATS_READ] /
6778 		    lun->be_lun->blocksize, data->sap.transmitted_lba);
6779 	}
6780 	t = &lun->stats.time[CTL_STATS_READ];
6781 	scsi_u64to8b((uint64_t)t->sec * 1000 + t->frac / (UINT64_MAX / 1000),
6782 	    data->sap.read_int);
6783 	t = &lun->stats.time[CTL_STATS_WRITE];
6784 	scsi_u64to8b((uint64_t)t->sec * 1000 + t->frac / (UINT64_MAX / 1000),
6785 	    data->sap.write_int);
6786 	scsi_u64to8b(0, data->sap.weighted_num);
6787 	scsi_u64to8b(0, data->sap.weighted_int);
6788 	scsi_ulto2b(SLP_IT, data->it.hdr.param_code);
6789 	data->it.hdr.param_control = SLP_LBIN;
6790 	data->it.hdr.param_len = sizeof(struct scsi_log_idle_time) -
6791 	    sizeof(struct scsi_log_param_header);
6792 #ifdef CTL_TIME_IO
6793 	scsi_u64to8b(lun->idle_time / SBT_1MS, data->it.idle_int);
6794 #endif
6795 	scsi_ulto2b(SLP_TI, data->ti.hdr.param_code);
6796 	data->it.hdr.param_control = SLP_LBIN;
6797 	data->ti.hdr.param_len = sizeof(struct scsi_log_time_interval) -
6798 	    sizeof(struct scsi_log_param_header);
6799 	scsi_ulto4b(3, data->ti.exponent);
6800 	scsi_ulto4b(1, data->ti.integer);
6801 	return (0);
6802 }
6803 
6804 int
6805 ctl_ie_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 scsi_log_informational_exceptions *data;
6811 	const char *value;
6812 
6813 	data = (struct scsi_log_informational_exceptions *)page_index->page_data;
6814 
6815 	scsi_ulto2b(SLP_IE_GEN, data->hdr.param_code);
6816 	data->hdr.param_control = SLP_LBIN;
6817 	data->hdr.param_len = sizeof(struct scsi_log_informational_exceptions) -
6818 	    sizeof(struct scsi_log_param_header);
6819 	data->ie_asc = lun->ie_asc;
6820 	data->ie_ascq = lun->ie_ascq;
6821 	if ((value = dnvlist_get_string(lun->be_lun->options, "temperature",
6822 	    NULL)) != NULL)
6823 		data->temperature = strtol(value, NULL, 0);
6824 	else
6825 		data->temperature = 0xff;
6826 	return (0);
6827 }
6828 
6829 int
6830 ctl_log_sense(struct ctl_scsiio *ctsio)
6831 {
6832 	struct ctl_lun *lun = CTL_LUN(ctsio);
6833 	int i, pc, page_code, subpage;
6834 	int alloc_len, total_len;
6835 	struct ctl_page_index *page_index;
6836 	struct scsi_log_sense *cdb;
6837 	struct scsi_log_header *header;
6838 
6839 	CTL_DEBUG_PRINT(("ctl_log_sense\n"));
6840 
6841 	cdb = (struct scsi_log_sense *)ctsio->cdb;
6842 	pc = (cdb->page & SLS_PAGE_CTRL_MASK) >> 6;
6843 	page_code = cdb->page & SLS_PAGE_CODE;
6844 	subpage = cdb->subpage;
6845 	alloc_len = scsi_2btoul(cdb->length);
6846 
6847 	page_index = NULL;
6848 	for (i = 0; i < CTL_NUM_LOG_PAGES; i++) {
6849 		page_index = &lun->log_pages.index[i];
6850 
6851 		/* Look for the right page code */
6852 		if ((page_index->page_code & SL_PAGE_CODE) != page_code)
6853 			continue;
6854 
6855 		/* Look for the right subpage or the subpage wildcard*/
6856 		if (page_index->subpage != subpage)
6857 			continue;
6858 
6859 		break;
6860 	}
6861 	if (i >= CTL_NUM_LOG_PAGES) {
6862 		ctl_set_invalid_field(ctsio,
6863 				      /*sks_valid*/ 1,
6864 				      /*command*/ 1,
6865 				      /*field*/ 2,
6866 				      /*bit_valid*/ 0,
6867 				      /*bit*/ 0);
6868 		ctl_done((union ctl_io *)ctsio);
6869 		return (CTL_RETVAL_COMPLETE);
6870 	}
6871 
6872 	total_len = sizeof(struct scsi_log_header) + page_index->page_len;
6873 
6874 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6875 	ctsio->kern_sg_entries = 0;
6876 	ctsio->kern_rel_offset = 0;
6877 	ctsio->kern_data_len = min(total_len, alloc_len);
6878 	ctsio->kern_total_len = ctsio->kern_data_len;
6879 
6880 	header = (struct scsi_log_header *)ctsio->kern_data_ptr;
6881 	header->page = page_index->page_code;
6882 	if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING)
6883 		header->page |= SL_DS;
6884 	if (page_index->subpage) {
6885 		header->page |= SL_SPF;
6886 		header->subpage = page_index->subpage;
6887 	}
6888 	scsi_ulto2b(page_index->page_len, header->datalen);
6889 
6890 	/*
6891 	 * Call the handler, if it exists, to update the
6892 	 * page to the latest values.
6893 	 */
6894 	if (page_index->sense_handler != NULL)
6895 		page_index->sense_handler(ctsio, page_index, pc);
6896 
6897 	memcpy(header + 1, page_index->page_data, page_index->page_len);
6898 
6899 	ctl_set_success(ctsio);
6900 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6901 	ctsio->be_move_done = ctl_config_move_done;
6902 	ctl_datamove((union ctl_io *)ctsio);
6903 	return (CTL_RETVAL_COMPLETE);
6904 }
6905 
6906 int
6907 ctl_read_capacity(struct ctl_scsiio *ctsio)
6908 {
6909 	struct ctl_lun *lun = CTL_LUN(ctsio);
6910 	struct scsi_read_capacity *cdb;
6911 	struct scsi_read_capacity_data *data;
6912 	uint32_t lba;
6913 
6914 	CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
6915 
6916 	cdb = (struct scsi_read_capacity *)ctsio->cdb;
6917 
6918 	lba = scsi_4btoul(cdb->addr);
6919 	if (((cdb->pmi & SRC_PMI) == 0)
6920 	 && (lba != 0)) {
6921 		ctl_set_invalid_field(/*ctsio*/ ctsio,
6922 				      /*sks_valid*/ 1,
6923 				      /*command*/ 1,
6924 				      /*field*/ 2,
6925 				      /*bit_valid*/ 0,
6926 				      /*bit*/ 0);
6927 		ctl_done((union ctl_io *)ctsio);
6928 		return (CTL_RETVAL_COMPLETE);
6929 	}
6930 
6931 	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
6932 	data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
6933 	ctsio->kern_data_len = sizeof(*data);
6934 	ctsio->kern_total_len = sizeof(*data);
6935 	ctsio->kern_rel_offset = 0;
6936 	ctsio->kern_sg_entries = 0;
6937 
6938 	/*
6939 	 * If the maximum LBA is greater than 0xfffffffe, the user must
6940 	 * issue a SERVICE ACTION IN (16) command, with the read capacity
6941 	 * serivce action set.
6942 	 */
6943 	if (lun->be_lun->maxlba > 0xfffffffe)
6944 		scsi_ulto4b(0xffffffff, data->addr);
6945 	else
6946 		scsi_ulto4b(lun->be_lun->maxlba, data->addr);
6947 
6948 	/*
6949 	 * XXX KDM this may not be 512 bytes...
6950 	 */
6951 	scsi_ulto4b(lun->be_lun->blocksize, data->length);
6952 
6953 	ctl_set_success(ctsio);
6954 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6955 	ctsio->be_move_done = ctl_config_move_done;
6956 	ctl_datamove((union ctl_io *)ctsio);
6957 	return (CTL_RETVAL_COMPLETE);
6958 }
6959 
6960 int
6961 ctl_read_capacity_16(struct ctl_scsiio *ctsio)
6962 {
6963 	struct ctl_lun *lun = CTL_LUN(ctsio);
6964 	struct scsi_read_capacity_16 *cdb;
6965 	struct scsi_read_capacity_data_long *data;
6966 	uint64_t lba;
6967 	uint32_t alloc_len;
6968 
6969 	CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
6970 
6971 	cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
6972 
6973 	alloc_len = scsi_4btoul(cdb->alloc_len);
6974 	lba = scsi_8btou64(cdb->addr);
6975 
6976 	if ((cdb->reladr & SRC16_PMI)
6977 	 && (lba != 0)) {
6978 		ctl_set_invalid_field(/*ctsio*/ ctsio,
6979 				      /*sks_valid*/ 1,
6980 				      /*command*/ 1,
6981 				      /*field*/ 2,
6982 				      /*bit_valid*/ 0,
6983 				      /*bit*/ 0);
6984 		ctl_done((union ctl_io *)ctsio);
6985 		return (CTL_RETVAL_COMPLETE);
6986 	}
6987 
6988 	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
6989 	data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
6990 	ctsio->kern_rel_offset = 0;
6991 	ctsio->kern_sg_entries = 0;
6992 	ctsio->kern_data_len = min(sizeof(*data), alloc_len);
6993 	ctsio->kern_total_len = ctsio->kern_data_len;
6994 
6995 	scsi_u64to8b(lun->be_lun->maxlba, data->addr);
6996 	/* XXX KDM this may not be 512 bytes... */
6997 	scsi_ulto4b(lun->be_lun->blocksize, data->length);
6998 	data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
6999 	scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
7000 	if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
7001 		data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
7002 
7003 	ctl_set_success(ctsio);
7004 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7005 	ctsio->be_move_done = ctl_config_move_done;
7006 	ctl_datamove((union ctl_io *)ctsio);
7007 	return (CTL_RETVAL_COMPLETE);
7008 }
7009 
7010 int
7011 ctl_get_lba_status(struct ctl_scsiio *ctsio)
7012 {
7013 	struct ctl_lun *lun = CTL_LUN(ctsio);
7014 	struct scsi_get_lba_status *cdb;
7015 	struct scsi_get_lba_status_data *data;
7016 	struct ctl_lba_len_flags *lbalen;
7017 	uint64_t lba;
7018 	uint32_t alloc_len, total_len;
7019 	int retval;
7020 
7021 	CTL_DEBUG_PRINT(("ctl_get_lba_status\n"));
7022 
7023 	cdb = (struct scsi_get_lba_status *)ctsio->cdb;
7024 	lba = scsi_8btou64(cdb->addr);
7025 	alloc_len = scsi_4btoul(cdb->alloc_len);
7026 
7027 	if (lba > lun->be_lun->maxlba) {
7028 		ctl_set_lba_out_of_range(ctsio, lba);
7029 		ctl_done((union ctl_io *)ctsio);
7030 		return (CTL_RETVAL_COMPLETE);
7031 	}
7032 
7033 	total_len = sizeof(*data) + sizeof(data->descr[0]);
7034 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7035 	data = (struct scsi_get_lba_status_data *)ctsio->kern_data_ptr;
7036 	ctsio->kern_rel_offset = 0;
7037 	ctsio->kern_sg_entries = 0;
7038 	ctsio->kern_data_len = min(total_len, alloc_len);
7039 	ctsio->kern_total_len = ctsio->kern_data_len;
7040 
7041 	/* Fill dummy data in case backend can't tell anything. */
7042 	scsi_ulto4b(4 + sizeof(data->descr[0]), data->length);
7043 	scsi_u64to8b(lba, data->descr[0].addr);
7044 	scsi_ulto4b(MIN(UINT32_MAX, lun->be_lun->maxlba + 1 - lba),
7045 	    data->descr[0].length);
7046 	data->descr[0].status = 0; /* Mapped or unknown. */
7047 
7048 	ctl_set_success(ctsio);
7049 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7050 	ctsio->be_move_done = ctl_config_move_done;
7051 
7052 	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
7053 	lbalen->lba = lba;
7054 	lbalen->len = total_len;
7055 	lbalen->flags = 0;
7056 	retval = lun->backend->config_read((union ctl_io *)ctsio);
7057 	return (retval);
7058 }
7059 
7060 int
7061 ctl_read_defect(struct ctl_scsiio *ctsio)
7062 {
7063 	struct scsi_read_defect_data_10 *ccb10;
7064 	struct scsi_read_defect_data_12 *ccb12;
7065 	struct scsi_read_defect_data_hdr_10 *data10;
7066 	struct scsi_read_defect_data_hdr_12 *data12;
7067 	uint32_t alloc_len, data_len;
7068 	uint8_t format;
7069 
7070 	CTL_DEBUG_PRINT(("ctl_read_defect\n"));
7071 
7072 	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7073 		ccb10 = (struct scsi_read_defect_data_10 *)&ctsio->cdb;
7074 		format = ccb10->format;
7075 		alloc_len = scsi_2btoul(ccb10->alloc_length);
7076 		data_len = sizeof(*data10);
7077 	} else {
7078 		ccb12 = (struct scsi_read_defect_data_12 *)&ctsio->cdb;
7079 		format = ccb12->format;
7080 		alloc_len = scsi_4btoul(ccb12->alloc_length);
7081 		data_len = sizeof(*data12);
7082 	}
7083 	if (alloc_len == 0) {
7084 		ctl_set_success(ctsio);
7085 		ctl_done((union ctl_io *)ctsio);
7086 		return (CTL_RETVAL_COMPLETE);
7087 	}
7088 
7089 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
7090 	ctsio->kern_rel_offset = 0;
7091 	ctsio->kern_sg_entries = 0;
7092 	ctsio->kern_data_len = min(data_len, alloc_len);
7093 	ctsio->kern_total_len = ctsio->kern_data_len;
7094 
7095 	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7096 		data10 = (struct scsi_read_defect_data_hdr_10 *)
7097 		    ctsio->kern_data_ptr;
7098 		data10->format = format;
7099 		scsi_ulto2b(0, data10->length);
7100 	} else {
7101 		data12 = (struct scsi_read_defect_data_hdr_12 *)
7102 		    ctsio->kern_data_ptr;
7103 		data12->format = format;
7104 		scsi_ulto2b(0, data12->generation);
7105 		scsi_ulto4b(0, data12->length);
7106 	}
7107 
7108 	ctl_set_success(ctsio);
7109 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7110 	ctsio->be_move_done = ctl_config_move_done;
7111 	ctl_datamove((union ctl_io *)ctsio);
7112 	return (CTL_RETVAL_COMPLETE);
7113 }
7114 
7115 int
7116 ctl_report_ident_info(struct ctl_scsiio *ctsio)
7117 {
7118 	struct ctl_lun *lun = CTL_LUN(ctsio);
7119 	struct scsi_report_ident_info *cdb;
7120 	struct scsi_report_ident_info_data *rii_ptr;
7121 	struct scsi_report_ident_info_descr *riid_ptr;
7122 	const char *oii, *otii;
7123 	int retval, alloc_len, total_len = 0, len = 0;
7124 
7125 	CTL_DEBUG_PRINT(("ctl_report_ident_info\n"));
7126 
7127 	cdb = (struct scsi_report_ident_info *)ctsio->cdb;
7128 	retval = CTL_RETVAL_COMPLETE;
7129 
7130 	total_len = sizeof(struct scsi_report_ident_info_data);
7131 	switch (cdb->type) {
7132 	case RII_LUII:
7133 		oii = dnvlist_get_string(lun->be_lun->options,
7134 		    "ident_info", NULL);
7135 		if (oii)
7136 			len = strlen(oii);	/* Approximately */
7137 		break;
7138 	case RII_LUTII:
7139 		otii = dnvlist_get_string(lun->be_lun->options,
7140 		    "text_ident_info", NULL);
7141 		if (otii)
7142 			len = strlen(otii) + 1;	/* NULL-terminated */
7143 		break;
7144 	case RII_IIS:
7145 		len = 2 * sizeof(struct scsi_report_ident_info_descr);
7146 		break;
7147 	default:
7148 		ctl_set_invalid_field(/*ctsio*/ ctsio,
7149 				      /*sks_valid*/ 1,
7150 				      /*command*/ 1,
7151 				      /*field*/ 11,
7152 				      /*bit_valid*/ 1,
7153 				      /*bit*/ 2);
7154 		ctl_done((union ctl_io *)ctsio);
7155 		return(retval);
7156 	}
7157 	total_len += len;
7158 	alloc_len = scsi_4btoul(cdb->length);
7159 
7160 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7161 	ctsio->kern_sg_entries = 0;
7162 	ctsio->kern_rel_offset = 0;
7163 	ctsio->kern_data_len = min(total_len, alloc_len);
7164 	ctsio->kern_total_len = ctsio->kern_data_len;
7165 
7166 	rii_ptr = (struct scsi_report_ident_info_data *)ctsio->kern_data_ptr;
7167 	switch (cdb->type) {
7168 	case RII_LUII:
7169 		if (oii) {
7170 			if (oii[0] == '0' && oii[1] == 'x')
7171 				len = hex2bin(oii, (uint8_t *)(rii_ptr + 1), len);
7172 			else
7173 				strncpy((uint8_t *)(rii_ptr + 1), oii, len);
7174 		}
7175 		break;
7176 	case RII_LUTII:
7177 		if (otii)
7178 			strlcpy((uint8_t *)(rii_ptr + 1), otii, len);
7179 		break;
7180 	case RII_IIS:
7181 		riid_ptr = (struct scsi_report_ident_info_descr *)(rii_ptr + 1);
7182 		riid_ptr->type = RII_LUII;
7183 		scsi_ulto2b(0xffff, riid_ptr->length);
7184 		riid_ptr++;
7185 		riid_ptr->type = RII_LUTII;
7186 		scsi_ulto2b(0xffff, riid_ptr->length);
7187 	}
7188 	scsi_ulto2b(len, rii_ptr->length);
7189 
7190 	ctl_set_success(ctsio);
7191 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7192 	ctsio->be_move_done = ctl_config_move_done;
7193 	ctl_datamove((union ctl_io *)ctsio);
7194 	return(retval);
7195 }
7196 
7197 int
7198 ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7199 {
7200 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
7201 	struct ctl_lun *lun = CTL_LUN(ctsio);
7202 	struct scsi_maintenance_in *cdb;
7203 	int retval;
7204 	int alloc_len, ext, total_len = 0, g, pc, pg, ts, os;
7205 	int num_ha_groups, num_target_ports, shared_group;
7206 	struct ctl_port *port;
7207 	struct scsi_target_group_data *rtg_ptr;
7208 	struct scsi_target_group_data_extended *rtg_ext_ptr;
7209 	struct scsi_target_port_group_descriptor *tpg_desc;
7210 
7211 	CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7212 
7213 	cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7214 	retval = CTL_RETVAL_COMPLETE;
7215 
7216 	switch (cdb->byte2 & STG_PDF_MASK) {
7217 	case STG_PDF_LENGTH:
7218 		ext = 0;
7219 		break;
7220 	case STG_PDF_EXTENDED:
7221 		ext = 1;
7222 		break;
7223 	default:
7224 		ctl_set_invalid_field(/*ctsio*/ ctsio,
7225 				      /*sks_valid*/ 1,
7226 				      /*command*/ 1,
7227 				      /*field*/ 2,
7228 				      /*bit_valid*/ 1,
7229 				      /*bit*/ 5);
7230 		ctl_done((union ctl_io *)ctsio);
7231 		return(retval);
7232 	}
7233 
7234 	num_target_ports = 0;
7235 	shared_group = (softc->is_single != 0);
7236 	mtx_lock(&softc->ctl_lock);
7237 	STAILQ_FOREACH(port, &softc->port_list, links) {
7238 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7239 			continue;
7240 		if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7241 			continue;
7242 		num_target_ports++;
7243 		if (port->status & CTL_PORT_STATUS_HA_SHARED)
7244 			shared_group = 1;
7245 	}
7246 	mtx_unlock(&softc->ctl_lock);
7247 	num_ha_groups = (softc->is_single) ? 0 : NUM_HA_SHELVES;
7248 
7249 	if (ext)
7250 		total_len = sizeof(struct scsi_target_group_data_extended);
7251 	else
7252 		total_len = sizeof(struct scsi_target_group_data);
7253 	total_len += sizeof(struct scsi_target_port_group_descriptor) *
7254 		(shared_group + num_ha_groups) +
7255 	    sizeof(struct scsi_target_port_descriptor) * num_target_ports;
7256 
7257 	alloc_len = scsi_4btoul(cdb->length);
7258 
7259 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7260 	ctsio->kern_sg_entries = 0;
7261 	ctsio->kern_rel_offset = 0;
7262 	ctsio->kern_data_len = min(total_len, alloc_len);
7263 	ctsio->kern_total_len = ctsio->kern_data_len;
7264 
7265 	if (ext) {
7266 		rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7267 		    ctsio->kern_data_ptr;
7268 		scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7269 		rtg_ext_ptr->format_type = 0x10;
7270 		rtg_ext_ptr->implicit_transition_time = 0;
7271 		tpg_desc = &rtg_ext_ptr->groups[0];
7272 	} else {
7273 		rtg_ptr = (struct scsi_target_group_data *)
7274 		    ctsio->kern_data_ptr;
7275 		scsi_ulto4b(total_len - 4, rtg_ptr->length);
7276 		tpg_desc = &rtg_ptr->groups[0];
7277 	}
7278 
7279 	mtx_lock(&softc->ctl_lock);
7280 	pg = softc->port_min / softc->port_cnt;
7281 	if (lun->flags & (CTL_LUN_PRIMARY_SC | CTL_LUN_PEER_SC_PRIMARY)) {
7282 		/* Some shelf is known to be primary. */
7283 		if (softc->ha_link == CTL_HA_LINK_OFFLINE)
7284 			os = TPG_ASYMMETRIC_ACCESS_UNAVAILABLE;
7285 		else if (softc->ha_link == CTL_HA_LINK_UNKNOWN)
7286 			os = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7287 		else if (softc->ha_mode == CTL_HA_MODE_ACT_STBY)
7288 			os = TPG_ASYMMETRIC_ACCESS_STANDBY;
7289 		else
7290 			os = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7291 		if (lun->flags & CTL_LUN_PRIMARY_SC) {
7292 			ts = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7293 		} else {
7294 			ts = os;
7295 			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7296 		}
7297 	} else {
7298 		/* No known primary shelf. */
7299 		if (softc->ha_link == CTL_HA_LINK_OFFLINE) {
7300 			ts = TPG_ASYMMETRIC_ACCESS_UNAVAILABLE;
7301 			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7302 		} else if (softc->ha_link == CTL_HA_LINK_UNKNOWN) {
7303 			ts = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7304 			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7305 		} else {
7306 			ts = os = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7307 		}
7308 	}
7309 	if (shared_group) {
7310 		tpg_desc->pref_state = ts;
7311 		tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP |
7312 		    TPG_U_SUP | TPG_T_SUP;
7313 		scsi_ulto2b(1, tpg_desc->target_port_group);
7314 		tpg_desc->status = TPG_IMPLICIT;
7315 		pc = 0;
7316 		STAILQ_FOREACH(port, &softc->port_list, links) {
7317 			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7318 				continue;
7319 			if (!softc->is_single &&
7320 			    (port->status & CTL_PORT_STATUS_HA_SHARED) == 0)
7321 				continue;
7322 			if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7323 				continue;
7324 			scsi_ulto2b(port->targ_port, tpg_desc->descriptors[pc].
7325 			    relative_target_port_identifier);
7326 			pc++;
7327 		}
7328 		tpg_desc->target_port_count = pc;
7329 		tpg_desc = (struct scsi_target_port_group_descriptor *)
7330 		    &tpg_desc->descriptors[pc];
7331 	}
7332 	for (g = 0; g < num_ha_groups; g++) {
7333 		tpg_desc->pref_state = (g == pg) ? ts : os;
7334 		tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP |
7335 		    TPG_U_SUP | TPG_T_SUP;
7336 		scsi_ulto2b(2 + g, tpg_desc->target_port_group);
7337 		tpg_desc->status = TPG_IMPLICIT;
7338 		pc = 0;
7339 		STAILQ_FOREACH(port, &softc->port_list, links) {
7340 			if (port->targ_port < g * softc->port_cnt ||
7341 			    port->targ_port >= (g + 1) * softc->port_cnt)
7342 				continue;
7343 			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7344 				continue;
7345 			if (port->status & CTL_PORT_STATUS_HA_SHARED)
7346 				continue;
7347 			if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7348 				continue;
7349 			scsi_ulto2b(port->targ_port, tpg_desc->descriptors[pc].
7350 			    relative_target_port_identifier);
7351 			pc++;
7352 		}
7353 		tpg_desc->target_port_count = pc;
7354 		tpg_desc = (struct scsi_target_port_group_descriptor *)
7355 		    &tpg_desc->descriptors[pc];
7356 	}
7357 	mtx_unlock(&softc->ctl_lock);
7358 
7359 	ctl_set_success(ctsio);
7360 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7361 	ctsio->be_move_done = ctl_config_move_done;
7362 	ctl_datamove((union ctl_io *)ctsio);
7363 	return(retval);
7364 }
7365 
7366 int
7367 ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7368 {
7369 	struct ctl_lun *lun = CTL_LUN(ctsio);
7370 	struct scsi_report_supported_opcodes *cdb;
7371 	const struct ctl_cmd_entry *entry, *sentry;
7372 	struct scsi_report_supported_opcodes_all *all;
7373 	struct scsi_report_supported_opcodes_descr *descr;
7374 	struct scsi_report_supported_opcodes_one *one;
7375 	int retval;
7376 	int alloc_len, total_len;
7377 	int opcode, service_action, i, j, num;
7378 
7379 	CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7380 
7381 	cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7382 	retval = CTL_RETVAL_COMPLETE;
7383 
7384 	opcode = cdb->requested_opcode;
7385 	service_action = scsi_2btoul(cdb->requested_service_action);
7386 	switch (cdb->options & RSO_OPTIONS_MASK) {
7387 	case RSO_OPTIONS_ALL:
7388 		num = 0;
7389 		for (i = 0; i < 256; i++) {
7390 			entry = &ctl_cmd_table[i];
7391 			if (entry->flags & CTL_CMD_FLAG_SA5) {
7392 				for (j = 0; j < 32; j++) {
7393 					sentry = &((const struct ctl_cmd_entry *)
7394 					    entry->execute)[j];
7395 					if (ctl_cmd_applicable(
7396 					    lun->be_lun->lun_type, sentry))
7397 						num++;
7398 				}
7399 			} else {
7400 				if (ctl_cmd_applicable(lun->be_lun->lun_type,
7401 				    entry))
7402 					num++;
7403 			}
7404 		}
7405 		total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7406 		    num * sizeof(struct scsi_report_supported_opcodes_descr);
7407 		break;
7408 	case RSO_OPTIONS_OC:
7409 		if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7410 			ctl_set_invalid_field(/*ctsio*/ ctsio,
7411 					      /*sks_valid*/ 1,
7412 					      /*command*/ 1,
7413 					      /*field*/ 2,
7414 					      /*bit_valid*/ 1,
7415 					      /*bit*/ 2);
7416 			ctl_done((union ctl_io *)ctsio);
7417 			return (CTL_RETVAL_COMPLETE);
7418 		}
7419 		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7420 		break;
7421 	case RSO_OPTIONS_OC_SA:
7422 		if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7423 		    service_action >= 32) {
7424 			ctl_set_invalid_field(/*ctsio*/ ctsio,
7425 					      /*sks_valid*/ 1,
7426 					      /*command*/ 1,
7427 					      /*field*/ 2,
7428 					      /*bit_valid*/ 1,
7429 					      /*bit*/ 2);
7430 			ctl_done((union ctl_io *)ctsio);
7431 			return (CTL_RETVAL_COMPLETE);
7432 		}
7433 		/* FALLTHROUGH */
7434 	case RSO_OPTIONS_OC_ASA:
7435 		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7436 		break;
7437 	default:
7438 		ctl_set_invalid_field(/*ctsio*/ ctsio,
7439 				      /*sks_valid*/ 1,
7440 				      /*command*/ 1,
7441 				      /*field*/ 2,
7442 				      /*bit_valid*/ 1,
7443 				      /*bit*/ 2);
7444 		ctl_done((union ctl_io *)ctsio);
7445 		return (CTL_RETVAL_COMPLETE);
7446 	}
7447 
7448 	alloc_len = scsi_4btoul(cdb->length);
7449 
7450 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7451 	ctsio->kern_sg_entries = 0;
7452 	ctsio->kern_rel_offset = 0;
7453 	ctsio->kern_data_len = min(total_len, alloc_len);
7454 	ctsio->kern_total_len = ctsio->kern_data_len;
7455 
7456 	switch (cdb->options & RSO_OPTIONS_MASK) {
7457 	case RSO_OPTIONS_ALL:
7458 		all = (struct scsi_report_supported_opcodes_all *)
7459 		    ctsio->kern_data_ptr;
7460 		num = 0;
7461 		for (i = 0; i < 256; i++) {
7462 			entry = &ctl_cmd_table[i];
7463 			if (entry->flags & CTL_CMD_FLAG_SA5) {
7464 				for (j = 0; j < 32; j++) {
7465 					sentry = &((const struct ctl_cmd_entry *)
7466 					    entry->execute)[j];
7467 					if (!ctl_cmd_applicable(
7468 					    lun->be_lun->lun_type, sentry))
7469 						continue;
7470 					descr = &all->descr[num++];
7471 					descr->opcode = i;
7472 					scsi_ulto2b(j, descr->service_action);
7473 					descr->flags = RSO_SERVACTV;
7474 					scsi_ulto2b(sentry->length,
7475 					    descr->cdb_length);
7476 				}
7477 			} else {
7478 				if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7479 				    entry))
7480 					continue;
7481 				descr = &all->descr[num++];
7482 				descr->opcode = i;
7483 				scsi_ulto2b(0, descr->service_action);
7484 				descr->flags = 0;
7485 				scsi_ulto2b(entry->length, descr->cdb_length);
7486 			}
7487 		}
7488 		scsi_ulto4b(
7489 		    num * sizeof(struct scsi_report_supported_opcodes_descr),
7490 		    all->length);
7491 		break;
7492 	case RSO_OPTIONS_OC:
7493 		one = (struct scsi_report_supported_opcodes_one *)
7494 		    ctsio->kern_data_ptr;
7495 		entry = &ctl_cmd_table[opcode];
7496 		goto fill_one;
7497 	case RSO_OPTIONS_OC_SA:
7498 		one = (struct scsi_report_supported_opcodes_one *)
7499 		    ctsio->kern_data_ptr;
7500 		entry = &ctl_cmd_table[opcode];
7501 		entry = &((const struct ctl_cmd_entry *)
7502 		    entry->execute)[service_action];
7503 fill_one:
7504 		if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7505 			one->support = 3;
7506 			scsi_ulto2b(entry->length, one->cdb_length);
7507 			one->cdb_usage[0] = opcode;
7508 			memcpy(&one->cdb_usage[1], entry->usage,
7509 			    entry->length - 1);
7510 		} else
7511 			one->support = 1;
7512 		break;
7513 	case RSO_OPTIONS_OC_ASA:
7514 		one = (struct scsi_report_supported_opcodes_one *)
7515 		    ctsio->kern_data_ptr;
7516 		entry = &ctl_cmd_table[opcode];
7517 		if (entry->flags & CTL_CMD_FLAG_SA5) {
7518 			entry = &((const struct ctl_cmd_entry *)
7519 			    entry->execute)[service_action];
7520 		} else if (service_action != 0) {
7521 			one->support = 1;
7522 			break;
7523 		}
7524 		goto fill_one;
7525 	}
7526 
7527 	ctl_set_success(ctsio);
7528 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7529 	ctsio->be_move_done = ctl_config_move_done;
7530 	ctl_datamove((union ctl_io *)ctsio);
7531 	return(retval);
7532 }
7533 
7534 int
7535 ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7536 {
7537 	struct scsi_report_supported_tmf *cdb;
7538 	struct scsi_report_supported_tmf_ext_data *data;
7539 	int retval;
7540 	int alloc_len, total_len;
7541 
7542 	CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7543 
7544 	cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7545 
7546 	retval = CTL_RETVAL_COMPLETE;
7547 
7548 	if (cdb->options & RST_REPD)
7549 		total_len = sizeof(struct scsi_report_supported_tmf_ext_data);
7550 	else
7551 		total_len = sizeof(struct scsi_report_supported_tmf_data);
7552 	alloc_len = scsi_4btoul(cdb->length);
7553 
7554 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7555 	ctsio->kern_sg_entries = 0;
7556 	ctsio->kern_rel_offset = 0;
7557 	ctsio->kern_data_len = min(total_len, alloc_len);
7558 	ctsio->kern_total_len = ctsio->kern_data_len;
7559 
7560 	data = (struct scsi_report_supported_tmf_ext_data *)ctsio->kern_data_ptr;
7561 	data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_QTS |
7562 	    RST_TRS;
7563 	data->byte2 |= RST_QAES | RST_QTSS | RST_ITNRS;
7564 	data->length = total_len - 4;
7565 
7566 	ctl_set_success(ctsio);
7567 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7568 	ctsio->be_move_done = ctl_config_move_done;
7569 	ctl_datamove((union ctl_io *)ctsio);
7570 	return (retval);
7571 }
7572 
7573 int
7574 ctl_report_timestamp(struct ctl_scsiio *ctsio)
7575 {
7576 	struct scsi_report_timestamp *cdb;
7577 	struct scsi_report_timestamp_data *data;
7578 	struct timeval tv;
7579 	int64_t timestamp;
7580 	int retval;
7581 	int alloc_len, total_len;
7582 
7583 	CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7584 
7585 	cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7586 
7587 	retval = CTL_RETVAL_COMPLETE;
7588 
7589 	total_len = sizeof(struct scsi_report_timestamp_data);
7590 	alloc_len = scsi_4btoul(cdb->length);
7591 
7592 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7593 	ctsio->kern_sg_entries = 0;
7594 	ctsio->kern_rel_offset = 0;
7595 	ctsio->kern_data_len = min(total_len, alloc_len);
7596 	ctsio->kern_total_len = ctsio->kern_data_len;
7597 
7598 	data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7599 	scsi_ulto2b(sizeof(*data) - 2, data->length);
7600 	data->origin = RTS_ORIG_OUTSIDE;
7601 	getmicrotime(&tv);
7602 	timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7603 	scsi_ulto4b(timestamp >> 16, data->timestamp);
7604 	scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7605 
7606 	ctl_set_success(ctsio);
7607 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7608 	ctsio->be_move_done = ctl_config_move_done;
7609 	ctl_datamove((union ctl_io *)ctsio);
7610 	return (retval);
7611 }
7612 
7613 int
7614 ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7615 {
7616 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
7617 	struct ctl_lun *lun = CTL_LUN(ctsio);
7618 	struct scsi_per_res_in *cdb;
7619 	int alloc_len, total_len = 0;
7620 	/* struct scsi_per_res_in_rsrv in_data; */
7621 	uint64_t key;
7622 
7623 	CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7624 
7625 	cdb = (struct scsi_per_res_in *)ctsio->cdb;
7626 
7627 	alloc_len = scsi_2btoul(cdb->length);
7628 
7629 retry:
7630 	mtx_lock(&lun->lun_lock);
7631 	switch (cdb->action) {
7632 	case SPRI_RK: /* read keys */
7633 		total_len = sizeof(struct scsi_per_res_in_keys) +
7634 			lun->pr_key_count *
7635 			sizeof(struct scsi_per_res_key);
7636 		break;
7637 	case SPRI_RR: /* read reservation */
7638 		if (lun->flags & CTL_LUN_PR_RESERVED)
7639 			total_len = sizeof(struct scsi_per_res_in_rsrv);
7640 		else
7641 			total_len = sizeof(struct scsi_per_res_in_header);
7642 		break;
7643 	case SPRI_RC: /* report capabilities */
7644 		total_len = sizeof(struct scsi_per_res_cap);
7645 		break;
7646 	case SPRI_RS: /* read full status */
7647 		total_len = sizeof(struct scsi_per_res_in_header) +
7648 		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7649 		    lun->pr_key_count;
7650 		break;
7651 	default:
7652 		panic("%s: Invalid PR type %#x", __func__, cdb->action);
7653 	}
7654 	mtx_unlock(&lun->lun_lock);
7655 
7656 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7657 	ctsio->kern_rel_offset = 0;
7658 	ctsio->kern_sg_entries = 0;
7659 	ctsio->kern_data_len = min(total_len, alloc_len);
7660 	ctsio->kern_total_len = ctsio->kern_data_len;
7661 
7662 	mtx_lock(&lun->lun_lock);
7663 	switch (cdb->action) {
7664 	case SPRI_RK: { // read keys
7665         struct scsi_per_res_in_keys *res_keys;
7666 		int i, key_count;
7667 
7668 		res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7669 
7670 		/*
7671 		 * We had to drop the lock to allocate our buffer, which
7672 		 * leaves time for someone to come in with another
7673 		 * persistent reservation.  (That is unlikely, though,
7674 		 * since this should be the only persistent reservation
7675 		 * command active right now.)
7676 		 */
7677 		if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7678 		    (lun->pr_key_count *
7679 		     sizeof(struct scsi_per_res_key)))){
7680 			mtx_unlock(&lun->lun_lock);
7681 			free(ctsio->kern_data_ptr, M_CTL);
7682 			printf("%s: reservation length changed, retrying\n",
7683 			       __func__);
7684 			goto retry;
7685 		}
7686 
7687 		scsi_ulto4b(lun->pr_generation, res_keys->header.generation);
7688 
7689 		scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7690 			     lun->pr_key_count, res_keys->header.length);
7691 
7692 		for (i = 0, key_count = 0; i < CTL_MAX_INITIATORS; i++) {
7693 			if ((key = ctl_get_prkey(lun, i)) == 0)
7694 				continue;
7695 
7696 			/*
7697 			 * We used lun->pr_key_count to calculate the
7698 			 * size to allocate.  If it turns out the number of
7699 			 * initiators with the registered flag set is
7700 			 * larger than that (i.e. they haven't been kept in
7701 			 * sync), we've got a problem.
7702 			 */
7703 			if (key_count >= lun->pr_key_count) {
7704 				key_count++;
7705 				continue;
7706 			}
7707 			scsi_u64to8b(key, res_keys->keys[key_count].key);
7708 			key_count++;
7709 		}
7710 		break;
7711 	}
7712 	case SPRI_RR: { // read reservation
7713 		struct scsi_per_res_in_rsrv *res;
7714 		int tmp_len, header_only;
7715 
7716 		res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7717 
7718 		scsi_ulto4b(lun->pr_generation, res->header.generation);
7719 
7720 		if (lun->flags & CTL_LUN_PR_RESERVED)
7721 		{
7722 			tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7723 			scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7724 				    res->header.length);
7725 			header_only = 0;
7726 		} else {
7727 			tmp_len = sizeof(struct scsi_per_res_in_header);
7728 			scsi_ulto4b(0, res->header.length);
7729 			header_only = 1;
7730 		}
7731 
7732 		/*
7733 		 * We had to drop the lock to allocate our buffer, which
7734 		 * leaves time for someone to come in with another
7735 		 * persistent reservation.  (That is unlikely, though,
7736 		 * since this should be the only persistent reservation
7737 		 * command active right now.)
7738 		 */
7739 		if (tmp_len != total_len) {
7740 			mtx_unlock(&lun->lun_lock);
7741 			free(ctsio->kern_data_ptr, M_CTL);
7742 			printf("%s: reservation status changed, retrying\n",
7743 			       __func__);
7744 			goto retry;
7745 		}
7746 
7747 		/*
7748 		 * No reservation held, so we're done.
7749 		 */
7750 		if (header_only != 0)
7751 			break;
7752 
7753 		/*
7754 		 * If the registration is an All Registrants type, the key
7755 		 * is 0, since it doesn't really matter.
7756 		 */
7757 		if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7758 			scsi_u64to8b(ctl_get_prkey(lun, lun->pr_res_idx),
7759 			    res->data.reservation);
7760 		}
7761 		res->data.scopetype = lun->pr_res_type;
7762 		break;
7763 	}
7764 	case SPRI_RC:     //report capabilities
7765 	{
7766 		struct scsi_per_res_cap *res_cap;
7767 		uint16_t type_mask;
7768 
7769 		res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7770 		scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7771 		res_cap->flags1 = SPRI_CRH;
7772 		res_cap->flags2 = SPRI_TMV | SPRI_ALLOW_5;
7773 		type_mask = SPRI_TM_WR_EX_AR |
7774 			    SPRI_TM_EX_AC_RO |
7775 			    SPRI_TM_WR_EX_RO |
7776 			    SPRI_TM_EX_AC |
7777 			    SPRI_TM_WR_EX |
7778 			    SPRI_TM_EX_AC_AR;
7779 		scsi_ulto2b(type_mask, res_cap->type_mask);
7780 		break;
7781 	}
7782 	case SPRI_RS: { // read full status
7783 		struct scsi_per_res_in_full *res_status;
7784 		struct scsi_per_res_in_full_desc *res_desc;
7785 		struct ctl_port *port;
7786 		int i, len;
7787 
7788 		res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7789 
7790 		/*
7791 		 * We had to drop the lock to allocate our buffer, which
7792 		 * leaves time for someone to come in with another
7793 		 * persistent reservation.  (That is unlikely, though,
7794 		 * since this should be the only persistent reservation
7795 		 * command active right now.)
7796 		 */
7797 		if (total_len < (sizeof(struct scsi_per_res_in_header) +
7798 		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7799 		     lun->pr_key_count)){
7800 			mtx_unlock(&lun->lun_lock);
7801 			free(ctsio->kern_data_ptr, M_CTL);
7802 			printf("%s: reservation length changed, retrying\n",
7803 			       __func__);
7804 			goto retry;
7805 		}
7806 
7807 		scsi_ulto4b(lun->pr_generation, res_status->header.generation);
7808 
7809 		res_desc = &res_status->desc[0];
7810 		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7811 			if ((key = ctl_get_prkey(lun, i)) == 0)
7812 				continue;
7813 
7814 			scsi_u64to8b(key, res_desc->res_key.key);
7815 			if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7816 			    (lun->pr_res_idx == i ||
7817 			     lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7818 				res_desc->flags = SPRI_FULL_R_HOLDER;
7819 				res_desc->scopetype = lun->pr_res_type;
7820 			}
7821 			scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7822 			    res_desc->rel_trgt_port_id);
7823 			len = 0;
7824 			port = softc->ctl_ports[i / CTL_MAX_INIT_PER_PORT];
7825 			if (port != NULL)
7826 				len = ctl_create_iid(port,
7827 				    i % CTL_MAX_INIT_PER_PORT,
7828 				    res_desc->transport_id);
7829 			scsi_ulto4b(len, res_desc->additional_length);
7830 			res_desc = (struct scsi_per_res_in_full_desc *)
7831 			    &res_desc->transport_id[len];
7832 		}
7833 		scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7834 		    res_status->header.length);
7835 		break;
7836 	}
7837 	default:
7838 		panic("%s: Invalid PR type %#x", __func__, cdb->action);
7839 	}
7840 	mtx_unlock(&lun->lun_lock);
7841 
7842 	ctl_set_success(ctsio);
7843 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7844 	ctsio->be_move_done = ctl_config_move_done;
7845 	ctl_datamove((union ctl_io *)ctsio);
7846 	return (CTL_RETVAL_COMPLETE);
7847 }
7848 
7849 /*
7850  * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
7851  * it should return.
7852  */
7853 static int
7854 ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
7855 		uint64_t sa_res_key, uint8_t type, uint32_t residx,
7856 		struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
7857 		struct scsi_per_res_out_parms* param)
7858 {
7859 	union ctl_ha_msg persis_io;
7860 	int i;
7861 
7862 	mtx_lock(&lun->lun_lock);
7863 	if (sa_res_key == 0) {
7864 		if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
7865 			/* validate scope and type */
7866 			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7867 			     SPR_LU_SCOPE) {
7868 				mtx_unlock(&lun->lun_lock);
7869 				ctl_set_invalid_field(/*ctsio*/ ctsio,
7870 						      /*sks_valid*/ 1,
7871 						      /*command*/ 1,
7872 						      /*field*/ 2,
7873 						      /*bit_valid*/ 1,
7874 						      /*bit*/ 4);
7875 				ctl_done((union ctl_io *)ctsio);
7876 				return (1);
7877 			}
7878 
7879 		        if (type>8 || type==2 || type==4 || type==0) {
7880 				mtx_unlock(&lun->lun_lock);
7881 				ctl_set_invalid_field(/*ctsio*/ ctsio,
7882        	           				      /*sks_valid*/ 1,
7883 						      /*command*/ 1,
7884 						      /*field*/ 2,
7885 						      /*bit_valid*/ 1,
7886 						      /*bit*/ 0);
7887 				ctl_done((union ctl_io *)ctsio);
7888 				return (1);
7889 		        }
7890 
7891 			/*
7892 			 * Unregister everybody else and build UA for
7893 			 * them
7894 			 */
7895 			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
7896 				if (i == residx || ctl_get_prkey(lun, i) == 0)
7897 					continue;
7898 
7899 				ctl_clr_prkey(lun, i);
7900 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7901 			}
7902 			lun->pr_key_count = 1;
7903 			lun->pr_res_type = type;
7904 			if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
7905 			    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
7906 				lun->pr_res_idx = residx;
7907 			lun->pr_generation++;
7908 			mtx_unlock(&lun->lun_lock);
7909 
7910 			/* send msg to other side */
7911 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7912 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7913 			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7914 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
7915 			persis_io.pr.pr_info.res_type = type;
7916 			memcpy(persis_io.pr.pr_info.sa_res_key,
7917 			       param->serv_act_res_key,
7918 			       sizeof(param->serv_act_res_key));
7919 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7920 			    sizeof(persis_io.pr), M_WAITOK);
7921 		} else {
7922 			/* not all registrants */
7923 			mtx_unlock(&lun->lun_lock);
7924 			free(ctsio->kern_data_ptr, M_CTL);
7925 			ctl_set_invalid_field(ctsio,
7926 					      /*sks_valid*/ 1,
7927 					      /*command*/ 0,
7928 					      /*field*/ 8,
7929 					      /*bit_valid*/ 0,
7930 					      /*bit*/ 0);
7931 			ctl_done((union ctl_io *)ctsio);
7932 			return (1);
7933 		}
7934 	} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
7935 		|| !(lun->flags & CTL_LUN_PR_RESERVED)) {
7936 		int found = 0;
7937 
7938 		if (res_key == sa_res_key) {
7939 			/* special case */
7940 			/*
7941 			 * The spec implies this is not good but doesn't
7942 			 * say what to do. There are two choices either
7943 			 * generate a res conflict or check condition
7944 			 * with illegal field in parameter data. Since
7945 			 * that is what is done when the sa_res_key is
7946 			 * zero I'll take that approach since this has
7947 			 * to do with the sa_res_key.
7948 			 */
7949 			mtx_unlock(&lun->lun_lock);
7950 			free(ctsio->kern_data_ptr, M_CTL);
7951 			ctl_set_invalid_field(ctsio,
7952 					      /*sks_valid*/ 1,
7953 					      /*command*/ 0,
7954 					      /*field*/ 8,
7955 					      /*bit_valid*/ 0,
7956 					      /*bit*/ 0);
7957 			ctl_done((union ctl_io *)ctsio);
7958 			return (1);
7959 		}
7960 
7961 		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7962 			if (ctl_get_prkey(lun, i) != sa_res_key)
7963 				continue;
7964 
7965 			found = 1;
7966 			ctl_clr_prkey(lun, i);
7967 			lun->pr_key_count--;
7968 			ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7969 		}
7970 		if (!found) {
7971 			mtx_unlock(&lun->lun_lock);
7972 			free(ctsio->kern_data_ptr, M_CTL);
7973 			ctl_set_reservation_conflict(ctsio);
7974 			ctl_done((union ctl_io *)ctsio);
7975 			return (CTL_RETVAL_COMPLETE);
7976 		}
7977 		lun->pr_generation++;
7978 		mtx_unlock(&lun->lun_lock);
7979 
7980 		/* send msg to other side */
7981 		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7982 		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7983 		persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7984 		persis_io.pr.pr_info.residx = lun->pr_res_idx;
7985 		persis_io.pr.pr_info.res_type = type;
7986 		memcpy(persis_io.pr.pr_info.sa_res_key,
7987 		       param->serv_act_res_key,
7988 		       sizeof(param->serv_act_res_key));
7989 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7990 		    sizeof(persis_io.pr), M_WAITOK);
7991 	} else {
7992 		/* Reserved but not all registrants */
7993 		/* sa_res_key is res holder */
7994 		if (sa_res_key == ctl_get_prkey(lun, lun->pr_res_idx)) {
7995 			/* validate scope and type */
7996 			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7997 			     SPR_LU_SCOPE) {
7998 				mtx_unlock(&lun->lun_lock);
7999 				ctl_set_invalid_field(/*ctsio*/ ctsio,
8000 						      /*sks_valid*/ 1,
8001 						      /*command*/ 1,
8002 						      /*field*/ 2,
8003 						      /*bit_valid*/ 1,
8004 						      /*bit*/ 4);
8005 				ctl_done((union ctl_io *)ctsio);
8006 				return (1);
8007 			}
8008 
8009 			if (type>8 || type==2 || type==4 || type==0) {
8010 				mtx_unlock(&lun->lun_lock);
8011 				ctl_set_invalid_field(/*ctsio*/ ctsio,
8012 						      /*sks_valid*/ 1,
8013 						      /*command*/ 1,
8014 						      /*field*/ 2,
8015 						      /*bit_valid*/ 1,
8016 						      /*bit*/ 0);
8017 				ctl_done((union ctl_io *)ctsio);
8018 				return (1);
8019 			}
8020 
8021 			/*
8022 			 * Do the following:
8023 			 * if sa_res_key != res_key remove all
8024 			 * registrants w/sa_res_key and generate UA
8025 			 * for these registrants(Registrations
8026 			 * Preempted) if it wasn't an exclusive
8027 			 * reservation generate UA(Reservations
8028 			 * Preempted) for all other registered nexuses
8029 			 * if the type has changed. Establish the new
8030 			 * reservation and holder. If res_key and
8031 			 * sa_res_key are the same do the above
8032 			 * except don't unregister the res holder.
8033 			 */
8034 
8035 			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
8036 				if (i == residx || ctl_get_prkey(lun, i) == 0)
8037 					continue;
8038 
8039 				if (sa_res_key == ctl_get_prkey(lun, i)) {
8040 					ctl_clr_prkey(lun, i);
8041 					lun->pr_key_count--;
8042 					ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8043 				} else if (type != lun->pr_res_type &&
8044 				    (lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8045 				     lun->pr_res_type == SPR_TYPE_EX_AC_RO)) {
8046 					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8047 				}
8048 			}
8049 			lun->pr_res_type = type;
8050 			if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8051 			    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8052 				lun->pr_res_idx = residx;
8053 			else
8054 				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8055 			lun->pr_generation++;
8056 			mtx_unlock(&lun->lun_lock);
8057 
8058 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8059 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8060 			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8061 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8062 			persis_io.pr.pr_info.res_type = type;
8063 			memcpy(persis_io.pr.pr_info.sa_res_key,
8064 			       param->serv_act_res_key,
8065 			       sizeof(param->serv_act_res_key));
8066 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8067 			    sizeof(persis_io.pr), M_WAITOK);
8068 		} else {
8069 			/*
8070 			 * sa_res_key is not the res holder just
8071 			 * remove registrants
8072 			 */
8073 			int found=0;
8074 
8075 			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8076 				if (sa_res_key != ctl_get_prkey(lun, i))
8077 					continue;
8078 
8079 				found = 1;
8080 				ctl_clr_prkey(lun, i);
8081 				lun->pr_key_count--;
8082 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8083 			}
8084 
8085 			if (!found) {
8086 				mtx_unlock(&lun->lun_lock);
8087 				free(ctsio->kern_data_ptr, M_CTL);
8088 				ctl_set_reservation_conflict(ctsio);
8089 				ctl_done((union ctl_io *)ctsio);
8090 		        	return (1);
8091 			}
8092 			lun->pr_generation++;
8093 			mtx_unlock(&lun->lun_lock);
8094 
8095 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8096 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8097 			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8098 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8099 			persis_io.pr.pr_info.res_type = type;
8100 			memcpy(persis_io.pr.pr_info.sa_res_key,
8101 			       param->serv_act_res_key,
8102 			       sizeof(param->serv_act_res_key));
8103 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8104 			    sizeof(persis_io.pr), M_WAITOK);
8105 		}
8106 	}
8107 	return (0);
8108 }
8109 
8110 static void
8111 ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8112 {
8113 	uint64_t sa_res_key;
8114 	int i;
8115 
8116 	sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8117 
8118 	if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8119 	 || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8120 	 || sa_res_key != ctl_get_prkey(lun, lun->pr_res_idx)) {
8121 		if (sa_res_key == 0) {
8122 			/*
8123 			 * Unregister everybody else and build UA for
8124 			 * them
8125 			 */
8126 			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
8127 				if (i == msg->pr.pr_info.residx ||
8128 				    ctl_get_prkey(lun, i) == 0)
8129 					continue;
8130 
8131 				ctl_clr_prkey(lun, i);
8132 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8133 			}
8134 
8135 			lun->pr_key_count = 1;
8136 			lun->pr_res_type = msg->pr.pr_info.res_type;
8137 			if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8138 			    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8139 				lun->pr_res_idx = msg->pr.pr_info.residx;
8140 		} else {
8141 		        for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8142 				if (sa_res_key == ctl_get_prkey(lun, i))
8143 					continue;
8144 
8145 				ctl_clr_prkey(lun, i);
8146 				lun->pr_key_count--;
8147 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8148 			}
8149 		}
8150 	} else {
8151 		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8152 			if (i == msg->pr.pr_info.residx ||
8153 			    ctl_get_prkey(lun, i) == 0)
8154 				continue;
8155 
8156 			if (sa_res_key == ctl_get_prkey(lun, i)) {
8157 				ctl_clr_prkey(lun, i);
8158 				lun->pr_key_count--;
8159 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8160 			} else if (msg->pr.pr_info.res_type != lun->pr_res_type
8161 			    && (lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8162 			     lun->pr_res_type == SPR_TYPE_EX_AC_RO)) {
8163 				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8164 			}
8165 		}
8166 		lun->pr_res_type = msg->pr.pr_info.res_type;
8167 		if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8168 		    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8169 			lun->pr_res_idx = msg->pr.pr_info.residx;
8170 		else
8171 			lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8172 	}
8173 	lun->pr_generation++;
8174 
8175 }
8176 
8177 int
8178 ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8179 {
8180 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
8181 	struct ctl_lun *lun = CTL_LUN(ctsio);
8182 	int retval;
8183 	u_int32_t param_len;
8184 	struct scsi_per_res_out *cdb;
8185 	struct scsi_per_res_out_parms* param;
8186 	uint32_t residx;
8187 	uint64_t res_key, sa_res_key, key;
8188 	uint8_t type;
8189 	union ctl_ha_msg persis_io;
8190 	int    i;
8191 
8192 	CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8193 
8194 	cdb = (struct scsi_per_res_out *)ctsio->cdb;
8195 	retval = CTL_RETVAL_COMPLETE;
8196 
8197 	/*
8198 	 * We only support whole-LUN scope.  The scope & type are ignored for
8199 	 * register, register and ignore existing key and clear.
8200 	 * We sometimes ignore scope and type on preempts too!!
8201 	 * Verify reservation type here as well.
8202 	 */
8203 	type = cdb->scope_type & SPR_TYPE_MASK;
8204 	if ((cdb->action == SPRO_RESERVE)
8205 	 || (cdb->action == SPRO_RELEASE)) {
8206 		if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8207 			ctl_set_invalid_field(/*ctsio*/ ctsio,
8208 					      /*sks_valid*/ 1,
8209 					      /*command*/ 1,
8210 					      /*field*/ 2,
8211 					      /*bit_valid*/ 1,
8212 					      /*bit*/ 4);
8213 			ctl_done((union ctl_io *)ctsio);
8214 			return (CTL_RETVAL_COMPLETE);
8215 		}
8216 
8217 		if (type>8 || type==2 || type==4 || type==0) {
8218 			ctl_set_invalid_field(/*ctsio*/ ctsio,
8219 					      /*sks_valid*/ 1,
8220 					      /*command*/ 1,
8221 					      /*field*/ 2,
8222 					      /*bit_valid*/ 1,
8223 					      /*bit*/ 0);
8224 			ctl_done((union ctl_io *)ctsio);
8225 			return (CTL_RETVAL_COMPLETE);
8226 		}
8227 	}
8228 
8229 	param_len = scsi_4btoul(cdb->length);
8230 
8231 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8232 		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8233 		ctsio->kern_data_len = param_len;
8234 		ctsio->kern_total_len = param_len;
8235 		ctsio->kern_rel_offset = 0;
8236 		ctsio->kern_sg_entries = 0;
8237 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8238 		ctsio->be_move_done = ctl_config_move_done;
8239 		ctl_datamove((union ctl_io *)ctsio);
8240 
8241 		return (CTL_RETVAL_COMPLETE);
8242 	}
8243 
8244 	param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8245 
8246 	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
8247 	res_key = scsi_8btou64(param->res_key.key);
8248 	sa_res_key = scsi_8btou64(param->serv_act_res_key);
8249 
8250 	/*
8251 	 * Validate the reservation key here except for SPRO_REG_IGNO
8252 	 * This must be done for all other service actions
8253 	 */
8254 	if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8255 		mtx_lock(&lun->lun_lock);
8256 		if ((key = ctl_get_prkey(lun, residx)) != 0) {
8257 			if (res_key != key) {
8258 				/*
8259 				 * The current key passed in doesn't match
8260 				 * the one the initiator previously
8261 				 * registered.
8262 				 */
8263 				mtx_unlock(&lun->lun_lock);
8264 				free(ctsio->kern_data_ptr, M_CTL);
8265 				ctl_set_reservation_conflict(ctsio);
8266 				ctl_done((union ctl_io *)ctsio);
8267 				return (CTL_RETVAL_COMPLETE);
8268 			}
8269 		} else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8270 			/*
8271 			 * We are not registered
8272 			 */
8273 			mtx_unlock(&lun->lun_lock);
8274 			free(ctsio->kern_data_ptr, M_CTL);
8275 			ctl_set_reservation_conflict(ctsio);
8276 			ctl_done((union ctl_io *)ctsio);
8277 			return (CTL_RETVAL_COMPLETE);
8278 		} else if (res_key != 0) {
8279 			/*
8280 			 * We are not registered and trying to register but
8281 			 * the register key isn't zero.
8282 			 */
8283 			mtx_unlock(&lun->lun_lock);
8284 			free(ctsio->kern_data_ptr, M_CTL);
8285 			ctl_set_reservation_conflict(ctsio);
8286 			ctl_done((union ctl_io *)ctsio);
8287 			return (CTL_RETVAL_COMPLETE);
8288 		}
8289 		mtx_unlock(&lun->lun_lock);
8290 	}
8291 
8292 	switch (cdb->action & SPRO_ACTION_MASK) {
8293 	case SPRO_REGISTER:
8294 	case SPRO_REG_IGNO: {
8295 		/*
8296 		 * We don't support any of these options, as we report in
8297 		 * the read capabilities request (see
8298 		 * ctl_persistent_reserve_in(), above).
8299 		 */
8300 		if ((param->flags & SPR_SPEC_I_PT)
8301 		 || (param->flags & SPR_ALL_TG_PT)
8302 		 || (param->flags & SPR_APTPL)) {
8303 			int bit_ptr;
8304 
8305 			if (param->flags & SPR_APTPL)
8306 				bit_ptr = 0;
8307 			else if (param->flags & SPR_ALL_TG_PT)
8308 				bit_ptr = 2;
8309 			else /* SPR_SPEC_I_PT */
8310 				bit_ptr = 3;
8311 
8312 			free(ctsio->kern_data_ptr, M_CTL);
8313 			ctl_set_invalid_field(ctsio,
8314 					      /*sks_valid*/ 1,
8315 					      /*command*/ 0,
8316 					      /*field*/ 20,
8317 					      /*bit_valid*/ 1,
8318 					      /*bit*/ bit_ptr);
8319 			ctl_done((union ctl_io *)ctsio);
8320 			return (CTL_RETVAL_COMPLETE);
8321 		}
8322 
8323 		mtx_lock(&lun->lun_lock);
8324 
8325 		/*
8326 		 * The initiator wants to clear the
8327 		 * key/unregister.
8328 		 */
8329 		if (sa_res_key == 0) {
8330 			if ((res_key == 0
8331 			  && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8332 			 || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8333 			  && ctl_get_prkey(lun, residx) == 0)) {
8334 				mtx_unlock(&lun->lun_lock);
8335 				goto done;
8336 			}
8337 
8338 			ctl_clr_prkey(lun, residx);
8339 			lun->pr_key_count--;
8340 
8341 			if (residx == lun->pr_res_idx) {
8342 				lun->flags &= ~CTL_LUN_PR_RESERVED;
8343 				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8344 
8345 				if ((lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8346 				     lun->pr_res_type == SPR_TYPE_EX_AC_RO) &&
8347 				    lun->pr_key_count) {
8348 					/*
8349 					 * If the reservation is a registrants
8350 					 * only type we need to generate a UA
8351 					 * for other registered inits.  The
8352 					 * sense code should be RESERVATIONS
8353 					 * RELEASED
8354 					 */
8355 
8356 					for (i = softc->init_min; i < softc->init_max; i++){
8357 						if (ctl_get_prkey(lun, i) == 0)
8358 							continue;
8359 						ctl_est_ua(lun, i,
8360 						    CTL_UA_RES_RELEASE);
8361 					}
8362 				}
8363 				lun->pr_res_type = 0;
8364 			} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8365 				if (lun->pr_key_count==0) {
8366 					lun->flags &= ~CTL_LUN_PR_RESERVED;
8367 					lun->pr_res_type = 0;
8368 					lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8369 				}
8370 			}
8371 			lun->pr_generation++;
8372 			mtx_unlock(&lun->lun_lock);
8373 
8374 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8375 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8376 			persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8377 			persis_io.pr.pr_info.residx = residx;
8378 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8379 			    sizeof(persis_io.pr), M_WAITOK);
8380 		} else /* sa_res_key != 0 */ {
8381 			/*
8382 			 * If we aren't registered currently then increment
8383 			 * the key count and set the registered flag.
8384 			 */
8385 			ctl_alloc_prkey(lun, residx);
8386 			if (ctl_get_prkey(lun, residx) == 0)
8387 				lun->pr_key_count++;
8388 			ctl_set_prkey(lun, residx, sa_res_key);
8389 			lun->pr_generation++;
8390 			mtx_unlock(&lun->lun_lock);
8391 
8392 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8393 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8394 			persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8395 			persis_io.pr.pr_info.residx = residx;
8396 			memcpy(persis_io.pr.pr_info.sa_res_key,
8397 			       param->serv_act_res_key,
8398 			       sizeof(param->serv_act_res_key));
8399 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8400 			    sizeof(persis_io.pr), M_WAITOK);
8401 		}
8402 
8403 		break;
8404 	}
8405 	case SPRO_RESERVE:
8406 		mtx_lock(&lun->lun_lock);
8407 		if (lun->flags & CTL_LUN_PR_RESERVED) {
8408 			/*
8409 			 * if this isn't the reservation holder and it's
8410 			 * not a "all registrants" type or if the type is
8411 			 * different then we have a conflict
8412 			 */
8413 			if ((lun->pr_res_idx != residx
8414 			  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8415 			 || lun->pr_res_type != type) {
8416 				mtx_unlock(&lun->lun_lock);
8417 				free(ctsio->kern_data_ptr, M_CTL);
8418 				ctl_set_reservation_conflict(ctsio);
8419 				ctl_done((union ctl_io *)ctsio);
8420 				return (CTL_RETVAL_COMPLETE);
8421 			}
8422 			mtx_unlock(&lun->lun_lock);
8423 		} else /* create a reservation */ {
8424 			/*
8425 			 * If it's not an "all registrants" type record
8426 			 * reservation holder
8427 			 */
8428 			if (type != SPR_TYPE_WR_EX_AR
8429 			 && type != SPR_TYPE_EX_AC_AR)
8430 				lun->pr_res_idx = residx; /* Res holder */
8431 			else
8432 				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8433 
8434 			lun->flags |= CTL_LUN_PR_RESERVED;
8435 			lun->pr_res_type = type;
8436 
8437 			mtx_unlock(&lun->lun_lock);
8438 
8439 			/* send msg to other side */
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_RESERVE;
8443 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8444 			persis_io.pr.pr_info.res_type = type;
8445 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8446 			    sizeof(persis_io.pr), M_WAITOK);
8447 		}
8448 		break;
8449 
8450 	case SPRO_RELEASE:
8451 		mtx_lock(&lun->lun_lock);
8452 		if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8453 			/* No reservation exists return good status */
8454 			mtx_unlock(&lun->lun_lock);
8455 			goto done;
8456 		}
8457 		/*
8458 		 * Is this nexus a reservation holder?
8459 		 */
8460 		if (lun->pr_res_idx != residx
8461 		 && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8462 			/*
8463 			 * not a res holder return good status but
8464 			 * do nothing
8465 			 */
8466 			mtx_unlock(&lun->lun_lock);
8467 			goto done;
8468 		}
8469 
8470 		if (lun->pr_res_type != type) {
8471 			mtx_unlock(&lun->lun_lock);
8472 			free(ctsio->kern_data_ptr, M_CTL);
8473 			ctl_set_illegal_pr_release(ctsio);
8474 			ctl_done((union ctl_io *)ctsio);
8475 			return (CTL_RETVAL_COMPLETE);
8476 		}
8477 
8478 		/* okay to release */
8479 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8480 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8481 		lun->pr_res_type = 0;
8482 
8483 		/*
8484 		 * If this isn't an exclusive access reservation and NUAR
8485 		 * is not set, generate UA for all other registrants.
8486 		 */
8487 		if (type != SPR_TYPE_EX_AC && type != SPR_TYPE_WR_EX &&
8488 		    (lun->MODE_CTRL.queue_flags & SCP_NUAR) == 0) {
8489 			for (i = softc->init_min; i < softc->init_max; i++) {
8490 				if (i == residx || ctl_get_prkey(lun, i) == 0)
8491 					continue;
8492 				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8493 			}
8494 		}
8495 		mtx_unlock(&lun->lun_lock);
8496 
8497 		/* Send msg to other side */
8498 		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8499 		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8500 		persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8501 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8502 		     sizeof(persis_io.pr), M_WAITOK);
8503 		break;
8504 
8505 	case SPRO_CLEAR:
8506 		/* send msg to other side */
8507 
8508 		mtx_lock(&lun->lun_lock);
8509 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8510 		lun->pr_res_type = 0;
8511 		lun->pr_key_count = 0;
8512 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8513 
8514 		ctl_clr_prkey(lun, residx);
8515 		for (i = 0; i < CTL_MAX_INITIATORS; i++)
8516 			if (ctl_get_prkey(lun, i) != 0) {
8517 				ctl_clr_prkey(lun, i);
8518 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8519 			}
8520 		lun->pr_generation++;
8521 		mtx_unlock(&lun->lun_lock);
8522 
8523 		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8524 		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8525 		persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8526 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8527 		     sizeof(persis_io.pr), M_WAITOK);
8528 		break;
8529 
8530 	case SPRO_PREEMPT:
8531 	case SPRO_PRE_ABO: {
8532 		int nretval;
8533 
8534 		nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8535 					  residx, ctsio, cdb, param);
8536 		if (nretval != 0)
8537 			return (CTL_RETVAL_COMPLETE);
8538 		break;
8539 	}
8540 	default:
8541 		panic("%s: Invalid PR type %#x", __func__, cdb->action);
8542 	}
8543 
8544 done:
8545 	free(ctsio->kern_data_ptr, M_CTL);
8546 	ctl_set_success(ctsio);
8547 	ctl_done((union ctl_io *)ctsio);
8548 
8549 	return (retval);
8550 }
8551 
8552 /*
8553  * This routine is for handling a message from the other SC pertaining to
8554  * persistent reserve out. All the error checking will have been done
8555  * so only perorming the action need be done here to keep the two
8556  * in sync.
8557  */
8558 static void
8559 ctl_hndl_per_res_out_on_other_sc(union ctl_io *io)
8560 {
8561 	struct ctl_softc *softc = CTL_SOFTC(io);
8562 	union ctl_ha_msg *msg = (union ctl_ha_msg *)&io->presio.pr_msg;
8563 	struct ctl_lun *lun;
8564 	int i;
8565 	uint32_t residx, targ_lun;
8566 
8567 	targ_lun = msg->hdr.nexus.targ_mapped_lun;
8568 	mtx_lock(&softc->ctl_lock);
8569 	if (targ_lun >= ctl_max_luns ||
8570 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
8571 		mtx_unlock(&softc->ctl_lock);
8572 		return;
8573 	}
8574 	mtx_lock(&lun->lun_lock);
8575 	mtx_unlock(&softc->ctl_lock);
8576 	if (lun->flags & CTL_LUN_DISABLED) {
8577 		mtx_unlock(&lun->lun_lock);
8578 		return;
8579 	}
8580 	residx = ctl_get_initindex(&msg->hdr.nexus);
8581 	switch(msg->pr.pr_info.action) {
8582 	case CTL_PR_REG_KEY:
8583 		ctl_alloc_prkey(lun, msg->pr.pr_info.residx);
8584 		if (ctl_get_prkey(lun, msg->pr.pr_info.residx) == 0)
8585 			lun->pr_key_count++;
8586 		ctl_set_prkey(lun, msg->pr.pr_info.residx,
8587 		    scsi_8btou64(msg->pr.pr_info.sa_res_key));
8588 		lun->pr_generation++;
8589 		break;
8590 
8591 	case CTL_PR_UNREG_KEY:
8592 		ctl_clr_prkey(lun, msg->pr.pr_info.residx);
8593 		lun->pr_key_count--;
8594 
8595 		/* XXX Need to see if the reservation has been released */
8596 		/* if so do we need to generate UA? */
8597 		if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8598 			lun->flags &= ~CTL_LUN_PR_RESERVED;
8599 			lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8600 
8601 			if ((lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8602 			     lun->pr_res_type == SPR_TYPE_EX_AC_RO) &&
8603 			    lun->pr_key_count) {
8604 				/*
8605 				 * If the reservation is a registrants
8606 				 * only type we need to generate a UA
8607 				 * for other registered inits.  The
8608 				 * sense code should be RESERVATIONS
8609 				 * RELEASED
8610 				 */
8611 
8612 				for (i = softc->init_min; i < softc->init_max; i++) {
8613 					if (ctl_get_prkey(lun, i) == 0)
8614 						continue;
8615 
8616 					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8617 				}
8618 			}
8619 			lun->pr_res_type = 0;
8620 		} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8621 			if (lun->pr_key_count==0) {
8622 				lun->flags &= ~CTL_LUN_PR_RESERVED;
8623 				lun->pr_res_type = 0;
8624 				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8625 			}
8626 		}
8627 		lun->pr_generation++;
8628 		break;
8629 
8630 	case CTL_PR_RESERVE:
8631 		lun->flags |= CTL_LUN_PR_RESERVED;
8632 		lun->pr_res_type = msg->pr.pr_info.res_type;
8633 		lun->pr_res_idx = msg->pr.pr_info.residx;
8634 
8635 		break;
8636 
8637 	case CTL_PR_RELEASE:
8638 		/*
8639 		 * If this isn't an exclusive access reservation and NUAR
8640 		 * is not set, generate UA for all other registrants.
8641 		 */
8642 		if (lun->pr_res_type != SPR_TYPE_EX_AC &&
8643 		    lun->pr_res_type != SPR_TYPE_WR_EX &&
8644 		    (lun->MODE_CTRL.queue_flags & SCP_NUAR) == 0) {
8645 			for (i = softc->init_min; i < softc->init_max; i++) {
8646 				if (i == residx || ctl_get_prkey(lun, i) == 0)
8647 					continue;
8648 				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8649 			}
8650 		}
8651 
8652 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8653 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8654 		lun->pr_res_type = 0;
8655 		break;
8656 
8657 	case CTL_PR_PREEMPT:
8658 		ctl_pro_preempt_other(lun, msg);
8659 		break;
8660 	case CTL_PR_CLEAR:
8661 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8662 		lun->pr_res_type = 0;
8663 		lun->pr_key_count = 0;
8664 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8665 
8666 		for (i=0; i < CTL_MAX_INITIATORS; i++) {
8667 			if (ctl_get_prkey(lun, i) == 0)
8668 				continue;
8669 			ctl_clr_prkey(lun, i);
8670 			ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8671 		}
8672 		lun->pr_generation++;
8673 		break;
8674 	}
8675 
8676 	mtx_unlock(&lun->lun_lock);
8677 }
8678 
8679 int
8680 ctl_read_write(struct ctl_scsiio *ctsio)
8681 {
8682 	struct ctl_lun *lun = CTL_LUN(ctsio);
8683 	struct ctl_lba_len_flags *lbalen;
8684 	uint64_t lba;
8685 	uint32_t num_blocks;
8686 	int flags, retval;
8687 	int isread;
8688 
8689 	CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8690 
8691 	flags = 0;
8692 	isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8693 	      || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8694 	switch (ctsio->cdb[0]) {
8695 	case READ_6:
8696 	case WRITE_6: {
8697 		struct scsi_rw_6 *cdb;
8698 
8699 		cdb = (struct scsi_rw_6 *)ctsio->cdb;
8700 
8701 		lba = scsi_3btoul(cdb->addr);
8702 		/* only 5 bits are valid in the most significant address byte */
8703 		lba &= 0x1fffff;
8704 		num_blocks = cdb->length;
8705 		/*
8706 		 * This is correct according to SBC-2.
8707 		 */
8708 		if (num_blocks == 0)
8709 			num_blocks = 256;
8710 		break;
8711 	}
8712 	case READ_10:
8713 	case WRITE_10: {
8714 		struct scsi_rw_10 *cdb;
8715 
8716 		cdb = (struct scsi_rw_10 *)ctsio->cdb;
8717 		if (cdb->byte2 & SRW10_FUA)
8718 			flags |= CTL_LLF_FUA;
8719 		if (cdb->byte2 & SRW10_DPO)
8720 			flags |= CTL_LLF_DPO;
8721 		lba = scsi_4btoul(cdb->addr);
8722 		num_blocks = scsi_2btoul(cdb->length);
8723 		break;
8724 	}
8725 	case WRITE_VERIFY_10: {
8726 		struct scsi_write_verify_10 *cdb;
8727 
8728 		cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
8729 		flags |= CTL_LLF_FUA;
8730 		if (cdb->byte2 & SWV_DPO)
8731 			flags |= CTL_LLF_DPO;
8732 		lba = scsi_4btoul(cdb->addr);
8733 		num_blocks = scsi_2btoul(cdb->length);
8734 		break;
8735 	}
8736 	case READ_12:
8737 	case WRITE_12: {
8738 		struct scsi_rw_12 *cdb;
8739 
8740 		cdb = (struct scsi_rw_12 *)ctsio->cdb;
8741 		if (cdb->byte2 & SRW12_FUA)
8742 			flags |= CTL_LLF_FUA;
8743 		if (cdb->byte2 & SRW12_DPO)
8744 			flags |= CTL_LLF_DPO;
8745 		lba = scsi_4btoul(cdb->addr);
8746 		num_blocks = scsi_4btoul(cdb->length);
8747 		break;
8748 	}
8749 	case WRITE_VERIFY_12: {
8750 		struct scsi_write_verify_12 *cdb;
8751 
8752 		cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
8753 		flags |= CTL_LLF_FUA;
8754 		if (cdb->byte2 & SWV_DPO)
8755 			flags |= CTL_LLF_DPO;
8756 		lba = scsi_4btoul(cdb->addr);
8757 		num_blocks = scsi_4btoul(cdb->length);
8758 		break;
8759 	}
8760 	case READ_16:
8761 	case WRITE_16: {
8762 		struct scsi_rw_16 *cdb;
8763 
8764 		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8765 		if (cdb->byte2 & SRW12_FUA)
8766 			flags |= CTL_LLF_FUA;
8767 		if (cdb->byte2 & SRW12_DPO)
8768 			flags |= CTL_LLF_DPO;
8769 		lba = scsi_8btou64(cdb->addr);
8770 		num_blocks = scsi_4btoul(cdb->length);
8771 		break;
8772 	}
8773 	case WRITE_ATOMIC_16: {
8774 		struct scsi_write_atomic_16 *cdb;
8775 
8776 		if (lun->be_lun->atomicblock == 0) {
8777 			ctl_set_invalid_opcode(ctsio);
8778 			ctl_done((union ctl_io *)ctsio);
8779 			return (CTL_RETVAL_COMPLETE);
8780 		}
8781 
8782 		cdb = (struct scsi_write_atomic_16 *)ctsio->cdb;
8783 		if (cdb->byte2 & SRW12_FUA)
8784 			flags |= CTL_LLF_FUA;
8785 		if (cdb->byte2 & SRW12_DPO)
8786 			flags |= CTL_LLF_DPO;
8787 		lba = scsi_8btou64(cdb->addr);
8788 		num_blocks = scsi_2btoul(cdb->length);
8789 		if (num_blocks > lun->be_lun->atomicblock) {
8790 			ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
8791 			    /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
8792 			    /*bit*/ 0);
8793 			ctl_done((union ctl_io *)ctsio);
8794 			return (CTL_RETVAL_COMPLETE);
8795 		}
8796 		break;
8797 	}
8798 	case WRITE_VERIFY_16: {
8799 		struct scsi_write_verify_16 *cdb;
8800 
8801 		cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
8802 		flags |= CTL_LLF_FUA;
8803 		if (cdb->byte2 & SWV_DPO)
8804 			flags |= CTL_LLF_DPO;
8805 		lba = scsi_8btou64(cdb->addr);
8806 		num_blocks = scsi_4btoul(cdb->length);
8807 		break;
8808 	}
8809 	default:
8810 		/*
8811 		 * We got a command we don't support.  This shouldn't
8812 		 * happen, commands should be filtered out above us.
8813 		 */
8814 		ctl_set_invalid_opcode(ctsio);
8815 		ctl_done((union ctl_io *)ctsio);
8816 
8817 		return (CTL_RETVAL_COMPLETE);
8818 		break; /* NOTREACHED */
8819 	}
8820 
8821 	/*
8822 	 * The first check is to make sure we're in bounds, the second
8823 	 * check is to catch wrap-around problems.  If the lba + num blocks
8824 	 * is less than the lba, then we've wrapped around and the block
8825 	 * range is invalid anyway.
8826 	 */
8827 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8828 	 || ((lba + num_blocks) < lba)) {
8829 		ctl_set_lba_out_of_range(ctsio,
8830 		    MAX(lba, lun->be_lun->maxlba + 1));
8831 		ctl_done((union ctl_io *)ctsio);
8832 		return (CTL_RETVAL_COMPLETE);
8833 	}
8834 
8835 	/*
8836 	 * According to SBC-3, a transfer length of 0 is not an error.
8837 	 * Note that this cannot happen with WRITE(6) or READ(6), since 0
8838 	 * translates to 256 blocks for those commands.
8839 	 */
8840 	if (num_blocks == 0) {
8841 		ctl_set_success(ctsio);
8842 		ctl_done((union ctl_io *)ctsio);
8843 		return (CTL_RETVAL_COMPLETE);
8844 	}
8845 
8846 	/* Set FUA and/or DPO if caches are disabled. */
8847 	if (isread) {
8848 		if ((lun->MODE_CACHING.flags1 & SCP_RCD) != 0)
8849 			flags |= CTL_LLF_FUA | CTL_LLF_DPO;
8850 	} else {
8851 		if ((lun->MODE_CACHING.flags1 & SCP_WCE) == 0)
8852 			flags |= CTL_LLF_FUA;
8853 	}
8854 
8855 	lbalen = (struct ctl_lba_len_flags *)
8856 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8857 	lbalen->lba = lba;
8858 	lbalen->len = num_blocks;
8859 	lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
8860 
8861 	ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
8862 	ctsio->kern_rel_offset = 0;
8863 
8864 	CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
8865 
8866 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8867 	return (retval);
8868 }
8869 
8870 static int
8871 ctl_cnw_cont(union ctl_io *io)
8872 {
8873 	struct ctl_lun *lun = CTL_LUN(io);
8874 	struct ctl_scsiio *ctsio;
8875 	struct ctl_lba_len_flags *lbalen;
8876 	int retval;
8877 
8878 	ctsio = &io->scsiio;
8879 	ctsio->io_hdr.status = CTL_STATUS_NONE;
8880 	ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
8881 	lbalen = (struct ctl_lba_len_flags *)
8882 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8883 	lbalen->flags &= ~CTL_LLF_COMPARE;
8884 	lbalen->flags |= CTL_LLF_WRITE;
8885 
8886 	CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
8887 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8888 	return (retval);
8889 }
8890 
8891 int
8892 ctl_cnw(struct ctl_scsiio *ctsio)
8893 {
8894 	struct ctl_lun *lun = CTL_LUN(ctsio);
8895 	struct ctl_lba_len_flags *lbalen;
8896 	uint64_t lba;
8897 	uint32_t num_blocks;
8898 	int flags, retval;
8899 
8900 	CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
8901 
8902 	flags = 0;
8903 	switch (ctsio->cdb[0]) {
8904 	case COMPARE_AND_WRITE: {
8905 		struct scsi_compare_and_write *cdb;
8906 
8907 		cdb = (struct scsi_compare_and_write *)ctsio->cdb;
8908 		if (cdb->byte2 & SRW10_FUA)
8909 			flags |= CTL_LLF_FUA;
8910 		if (cdb->byte2 & SRW10_DPO)
8911 			flags |= CTL_LLF_DPO;
8912 		lba = scsi_8btou64(cdb->addr);
8913 		num_blocks = cdb->length;
8914 		break;
8915 	}
8916 	default:
8917 		/*
8918 		 * We got a command we don't support.  This shouldn't
8919 		 * happen, commands should be filtered out above us.
8920 		 */
8921 		ctl_set_invalid_opcode(ctsio);
8922 		ctl_done((union ctl_io *)ctsio);
8923 
8924 		return (CTL_RETVAL_COMPLETE);
8925 		break; /* NOTREACHED */
8926 	}
8927 
8928 	/*
8929 	 * The first check is to make sure we're in bounds, the second
8930 	 * check is to catch wrap-around problems.  If the lba + num blocks
8931 	 * is less than the lba, then we've wrapped around and the block
8932 	 * range is invalid anyway.
8933 	 */
8934 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8935 	 || ((lba + num_blocks) < lba)) {
8936 		ctl_set_lba_out_of_range(ctsio,
8937 		    MAX(lba, lun->be_lun->maxlba + 1));
8938 		ctl_done((union ctl_io *)ctsio);
8939 		return (CTL_RETVAL_COMPLETE);
8940 	}
8941 
8942 	/*
8943 	 * According to SBC-3, a transfer length of 0 is not an error.
8944 	 */
8945 	if (num_blocks == 0) {
8946 		ctl_set_success(ctsio);
8947 		ctl_done((union ctl_io *)ctsio);
8948 		return (CTL_RETVAL_COMPLETE);
8949 	}
8950 
8951 	/* Set FUA if write cache is disabled. */
8952 	if ((lun->MODE_CACHING.flags1 & SCP_WCE) == 0)
8953 		flags |= CTL_LLF_FUA;
8954 
8955 	ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
8956 	ctsio->kern_rel_offset = 0;
8957 
8958 	/*
8959 	 * Set the IO_CONT flag, so that if this I/O gets passed to
8960 	 * ctl_data_submit_done(), it'll get passed back to
8961 	 * ctl_ctl_cnw_cont() for further processing.
8962 	 */
8963 	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
8964 	ctsio->io_cont = ctl_cnw_cont;
8965 
8966 	lbalen = (struct ctl_lba_len_flags *)
8967 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8968 	lbalen->lba = lba;
8969 	lbalen->len = num_blocks;
8970 	lbalen->flags = CTL_LLF_COMPARE | flags;
8971 
8972 	CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
8973 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8974 	return (retval);
8975 }
8976 
8977 int
8978 ctl_verify(struct ctl_scsiio *ctsio)
8979 {
8980 	struct ctl_lun *lun = CTL_LUN(ctsio);
8981 	struct ctl_lba_len_flags *lbalen;
8982 	uint64_t lba;
8983 	uint32_t num_blocks;
8984 	int bytchk, flags;
8985 	int retval;
8986 
8987 	CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
8988 
8989 	bytchk = 0;
8990 	flags = CTL_LLF_FUA;
8991 	switch (ctsio->cdb[0]) {
8992 	case VERIFY_10: {
8993 		struct scsi_verify_10 *cdb;
8994 
8995 		cdb = (struct scsi_verify_10 *)ctsio->cdb;
8996 		if (cdb->byte2 & SVFY_BYTCHK)
8997 			bytchk = 1;
8998 		if (cdb->byte2 & SVFY_DPO)
8999 			flags |= CTL_LLF_DPO;
9000 		lba = scsi_4btoul(cdb->addr);
9001 		num_blocks = scsi_2btoul(cdb->length);
9002 		break;
9003 	}
9004 	case VERIFY_12: {
9005 		struct scsi_verify_12 *cdb;
9006 
9007 		cdb = (struct scsi_verify_12 *)ctsio->cdb;
9008 		if (cdb->byte2 & SVFY_BYTCHK)
9009 			bytchk = 1;
9010 		if (cdb->byte2 & SVFY_DPO)
9011 			flags |= CTL_LLF_DPO;
9012 		lba = scsi_4btoul(cdb->addr);
9013 		num_blocks = scsi_4btoul(cdb->length);
9014 		break;
9015 	}
9016 	case VERIFY_16: {
9017 		struct scsi_rw_16 *cdb;
9018 
9019 		cdb = (struct scsi_rw_16 *)ctsio->cdb;
9020 		if (cdb->byte2 & SVFY_BYTCHK)
9021 			bytchk = 1;
9022 		if (cdb->byte2 & SVFY_DPO)
9023 			flags |= CTL_LLF_DPO;
9024 		lba = scsi_8btou64(cdb->addr);
9025 		num_blocks = scsi_4btoul(cdb->length);
9026 		break;
9027 	}
9028 	default:
9029 		/*
9030 		 * We got a command we don't support.  This shouldn't
9031 		 * happen, commands should be filtered out above us.
9032 		 */
9033 		ctl_set_invalid_opcode(ctsio);
9034 		ctl_done((union ctl_io *)ctsio);
9035 		return (CTL_RETVAL_COMPLETE);
9036 	}
9037 
9038 	/*
9039 	 * The first check is to make sure we're in bounds, the second
9040 	 * check is to catch wrap-around problems.  If the lba + num blocks
9041 	 * is less than the lba, then we've wrapped around and the block
9042 	 * range is invalid anyway.
9043 	 */
9044 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9045 	 || ((lba + num_blocks) < lba)) {
9046 		ctl_set_lba_out_of_range(ctsio,
9047 		    MAX(lba, lun->be_lun->maxlba + 1));
9048 		ctl_done((union ctl_io *)ctsio);
9049 		return (CTL_RETVAL_COMPLETE);
9050 	}
9051 
9052 	/*
9053 	 * According to SBC-3, a transfer length of 0 is not an error.
9054 	 */
9055 	if (num_blocks == 0) {
9056 		ctl_set_success(ctsio);
9057 		ctl_done((union ctl_io *)ctsio);
9058 		return (CTL_RETVAL_COMPLETE);
9059 	}
9060 
9061 	lbalen = (struct ctl_lba_len_flags *)
9062 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9063 	lbalen->lba = lba;
9064 	lbalen->len = num_blocks;
9065 	if (bytchk) {
9066 		lbalen->flags = CTL_LLF_COMPARE | flags;
9067 		ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9068 	} else {
9069 		lbalen->flags = CTL_LLF_VERIFY | flags;
9070 		ctsio->kern_total_len = 0;
9071 	}
9072 	ctsio->kern_rel_offset = 0;
9073 
9074 	CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9075 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9076 	return (retval);
9077 }
9078 
9079 int
9080 ctl_report_luns(struct ctl_scsiio *ctsio)
9081 {
9082 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9083 	struct ctl_port *port = CTL_PORT(ctsio);
9084 	struct ctl_lun *lun, *request_lun = CTL_LUN(ctsio);
9085 	struct scsi_report_luns *cdb;
9086 	struct scsi_report_luns_data *lun_data;
9087 	int num_filled, num_luns, num_port_luns, retval;
9088 	uint32_t alloc_len, lun_datalen;
9089 	uint32_t initidx, targ_lun_id, lun_id;
9090 
9091 	retval = CTL_RETVAL_COMPLETE;
9092 	cdb = (struct scsi_report_luns *)ctsio->cdb;
9093 
9094 	CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9095 
9096 	num_luns = 0;
9097 	num_port_luns = port->lun_map ? port->lun_map_size : ctl_max_luns;
9098 	mtx_lock(&softc->ctl_lock);
9099 	for (targ_lun_id = 0; targ_lun_id < num_port_luns; targ_lun_id++) {
9100 		if (ctl_lun_map_from_port(port, targ_lun_id) != UINT32_MAX)
9101 			num_luns++;
9102 	}
9103 	mtx_unlock(&softc->ctl_lock);
9104 
9105 	switch (cdb->select_report) {
9106 	case RPL_REPORT_DEFAULT:
9107 	case RPL_REPORT_ALL:
9108 	case RPL_REPORT_NONSUBSID:
9109 		break;
9110 	case RPL_REPORT_WELLKNOWN:
9111 	case RPL_REPORT_ADMIN:
9112 	case RPL_REPORT_CONGLOM:
9113 		num_luns = 0;
9114 		break;
9115 	default:
9116 		ctl_set_invalid_field(ctsio,
9117 				      /*sks_valid*/ 1,
9118 				      /*command*/ 1,
9119 				      /*field*/ 2,
9120 				      /*bit_valid*/ 0,
9121 				      /*bit*/ 0);
9122 		ctl_done((union ctl_io *)ctsio);
9123 		return (retval);
9124 		break; /* NOTREACHED */
9125 	}
9126 
9127 	alloc_len = scsi_4btoul(cdb->length);
9128 	/*
9129 	 * The initiator has to allocate at least 16 bytes for this request,
9130 	 * so he can at least get the header and the first LUN.  Otherwise
9131 	 * we reject the request (per SPC-3 rev 14, section 6.21).
9132 	 */
9133 	if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9134 	    sizeof(struct scsi_report_luns_lundata))) {
9135 		ctl_set_invalid_field(ctsio,
9136 				      /*sks_valid*/ 1,
9137 				      /*command*/ 1,
9138 				      /*field*/ 6,
9139 				      /*bit_valid*/ 0,
9140 				      /*bit*/ 0);
9141 		ctl_done((union ctl_io *)ctsio);
9142 		return (retval);
9143 	}
9144 
9145 	lun_datalen = sizeof(*lun_data) +
9146 		(num_luns * sizeof(struct scsi_report_luns_lundata));
9147 
9148 	ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9149 	lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9150 	ctsio->kern_sg_entries = 0;
9151 
9152 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9153 
9154 	mtx_lock(&softc->ctl_lock);
9155 	for (targ_lun_id = 0, num_filled = 0;
9156 	    targ_lun_id < num_port_luns && num_filled < num_luns;
9157 	    targ_lun_id++) {
9158 		lun_id = ctl_lun_map_from_port(port, targ_lun_id);
9159 		if (lun_id == UINT32_MAX)
9160 			continue;
9161 		lun = softc->ctl_luns[lun_id];
9162 		if (lun == NULL)
9163 			continue;
9164 
9165 		be64enc(lun_data->luns[num_filled++].lundata,
9166 		    ctl_encode_lun(targ_lun_id));
9167 
9168 		/*
9169 		 * According to SPC-3, rev 14 section 6.21:
9170 		 *
9171 		 * "The execution of a REPORT LUNS command to any valid and
9172 		 * installed logical unit shall clear the REPORTED LUNS DATA
9173 		 * HAS CHANGED unit attention condition for all logical
9174 		 * units of that target with respect to the requesting
9175 		 * initiator. A valid and installed logical unit is one
9176 		 * having a PERIPHERAL QUALIFIER of 000b in the standard
9177 		 * INQUIRY data (see 6.4.2)."
9178 		 *
9179 		 * If request_lun is NULL, the LUN this report luns command
9180 		 * was issued to is either disabled or doesn't exist. In that
9181 		 * case, we shouldn't clear any pending lun change unit
9182 		 * attention.
9183 		 */
9184 		if (request_lun != NULL) {
9185 			mtx_lock(&lun->lun_lock);
9186 			ctl_clr_ua(lun, initidx, CTL_UA_LUN_CHANGE);
9187 			mtx_unlock(&lun->lun_lock);
9188 		}
9189 	}
9190 	mtx_unlock(&softc->ctl_lock);
9191 
9192 	/*
9193 	 * It's quite possible that we've returned fewer LUNs than we allocated
9194 	 * space for.  Trim it.
9195 	 */
9196 	lun_datalen = sizeof(*lun_data) +
9197 		(num_filled * sizeof(struct scsi_report_luns_lundata));
9198 	ctsio->kern_rel_offset = 0;
9199 	ctsio->kern_sg_entries = 0;
9200 	ctsio->kern_data_len = min(lun_datalen, alloc_len);
9201 	ctsio->kern_total_len = ctsio->kern_data_len;
9202 
9203 	/*
9204 	 * We set this to the actual data length, regardless of how much
9205 	 * space we actually have to return results.  If the user looks at
9206 	 * this value, he'll know whether or not he allocated enough space
9207 	 * and reissue the command if necessary.  We don't support well
9208 	 * known logical units, so if the user asks for that, return none.
9209 	 */
9210 	scsi_ulto4b(lun_datalen - 8, lun_data->length);
9211 
9212 	/*
9213 	 * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9214 	 * this request.
9215 	 */
9216 	ctl_set_success(ctsio);
9217 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9218 	ctsio->be_move_done = ctl_config_move_done;
9219 	ctl_datamove((union ctl_io *)ctsio);
9220 	return (retval);
9221 }
9222 
9223 int
9224 ctl_request_sense(struct ctl_scsiio *ctsio)
9225 {
9226 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9227 	struct ctl_lun *lun = CTL_LUN(ctsio);
9228 	struct scsi_request_sense *cdb;
9229 	struct scsi_sense_data *sense_ptr, *ps;
9230 	uint32_t initidx;
9231 	int have_error;
9232 	u_int sense_len = SSD_FULL_SIZE;
9233 	scsi_sense_data_type sense_format;
9234 	ctl_ua_type ua_type;
9235 	uint8_t asc = 0, ascq = 0;
9236 
9237 	cdb = (struct scsi_request_sense *)ctsio->cdb;
9238 
9239 	CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9240 
9241 	/*
9242 	 * Determine which sense format the user wants.
9243 	 */
9244 	if (cdb->byte2 & SRS_DESC)
9245 		sense_format = SSD_TYPE_DESC;
9246 	else
9247 		sense_format = SSD_TYPE_FIXED;
9248 
9249 	ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9250 	sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9251 	ctsio->kern_sg_entries = 0;
9252 	ctsio->kern_rel_offset = 0;
9253 
9254 	/*
9255 	 * struct scsi_sense_data, which is currently set to 256 bytes, is
9256 	 * larger than the largest allowed value for the length field in the
9257 	 * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9258 	 */
9259 	ctsio->kern_data_len = cdb->length;
9260 	ctsio->kern_total_len = cdb->length;
9261 
9262 	/*
9263 	 * If we don't have a LUN, we don't have any pending sense.
9264 	 */
9265 	if (lun == NULL ||
9266 	    ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
9267 	     softc->ha_link < CTL_HA_LINK_UNKNOWN)) {
9268 		/* "Logical unit not supported" */
9269 		ctl_set_sense_data(sense_ptr, &sense_len, NULL, sense_format,
9270 		    /*current_error*/ 1,
9271 		    /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
9272 		    /*asc*/ 0x25,
9273 		    /*ascq*/ 0x00,
9274 		    SSD_ELEM_NONE);
9275 		goto send;
9276 	}
9277 
9278 	have_error = 0;
9279 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9280 	/*
9281 	 * Check for pending sense, and then for pending unit attentions.
9282 	 * Pending sense gets returned first, then pending unit attentions.
9283 	 */
9284 	mtx_lock(&lun->lun_lock);
9285 	ps = lun->pending_sense[initidx / CTL_MAX_INIT_PER_PORT];
9286 	if (ps != NULL)
9287 		ps += initidx % CTL_MAX_INIT_PER_PORT;
9288 	if (ps != NULL && ps->error_code != 0) {
9289 		scsi_sense_data_type stored_format;
9290 
9291 		/*
9292 		 * Check to see which sense format was used for the stored
9293 		 * sense data.
9294 		 */
9295 		stored_format = scsi_sense_type(ps);
9296 
9297 		/*
9298 		 * If the user requested a different sense format than the
9299 		 * one we stored, then we need to convert it to the other
9300 		 * format.  If we're going from descriptor to fixed format
9301 		 * sense data, we may lose things in translation, depending
9302 		 * on what options were used.
9303 		 *
9304 		 * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9305 		 * for some reason we'll just copy it out as-is.
9306 		 */
9307 		if ((stored_format == SSD_TYPE_FIXED)
9308 		 && (sense_format == SSD_TYPE_DESC))
9309 			ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9310 			    ps, (struct scsi_sense_data_desc *)sense_ptr);
9311 		else if ((stored_format == SSD_TYPE_DESC)
9312 		      && (sense_format == SSD_TYPE_FIXED))
9313 			ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9314 			    ps, (struct scsi_sense_data_fixed *)sense_ptr);
9315 		else
9316 			memcpy(sense_ptr, ps, sizeof(*sense_ptr));
9317 
9318 		ps->error_code = 0;
9319 		have_error = 1;
9320 	} else {
9321 		ua_type = ctl_build_ua(lun, initidx, sense_ptr, &sense_len,
9322 		    sense_format);
9323 		if (ua_type != CTL_UA_NONE)
9324 			have_error = 1;
9325 	}
9326 	if (have_error == 0) {
9327 		/*
9328 		 * Report informational exception if have one and allowed.
9329 		 */
9330 		if (lun->MODE_IE.mrie != SIEP_MRIE_NO) {
9331 			asc = lun->ie_asc;
9332 			ascq = lun->ie_ascq;
9333 		}
9334 		ctl_set_sense_data(sense_ptr, &sense_len, lun, sense_format,
9335 		    /*current_error*/ 1,
9336 		    /*sense_key*/ SSD_KEY_NO_SENSE,
9337 		    /*asc*/ asc,
9338 		    /*ascq*/ ascq,
9339 		    SSD_ELEM_NONE);
9340 	}
9341 	mtx_unlock(&lun->lun_lock);
9342 
9343 send:
9344 	/*
9345 	 * We report the SCSI status as OK, since the status of the command
9346 	 * itself is OK.  We're reporting sense as parameter data.
9347 	 */
9348 	ctl_set_success(ctsio);
9349 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9350 	ctsio->be_move_done = ctl_config_move_done;
9351 	ctl_datamove((union ctl_io *)ctsio);
9352 	return (CTL_RETVAL_COMPLETE);
9353 }
9354 
9355 int
9356 ctl_tur(struct ctl_scsiio *ctsio)
9357 {
9358 
9359 	CTL_DEBUG_PRINT(("ctl_tur\n"));
9360 
9361 	ctl_set_success(ctsio);
9362 	ctl_done((union ctl_io *)ctsio);
9363 
9364 	return (CTL_RETVAL_COMPLETE);
9365 }
9366 
9367 /*
9368  * SCSI VPD page 0x00, the Supported VPD Pages page.
9369  */
9370 static int
9371 ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9372 {
9373 	struct ctl_lun *lun = CTL_LUN(ctsio);
9374 	struct scsi_vpd_supported_pages *pages;
9375 	int sup_page_size;
9376 	int p;
9377 
9378 	sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9379 	    SCSI_EVPD_NUM_SUPPORTED_PAGES;
9380 	ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9381 	pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9382 	ctsio->kern_rel_offset = 0;
9383 	ctsio->kern_sg_entries = 0;
9384 	ctsio->kern_data_len = min(sup_page_size, alloc_len);
9385 	ctsio->kern_total_len = ctsio->kern_data_len;
9386 
9387 	/*
9388 	 * The control device is always connected.  The disk device, on the
9389 	 * other hand, may not be online all the time.  Need to change this
9390 	 * to figure out whether the disk device is actually online or not.
9391 	 */
9392 	if (lun != NULL)
9393 		pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9394 				lun->be_lun->lun_type;
9395 	else
9396 		pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9397 
9398 	p = 0;
9399 	/* Supported VPD pages */
9400 	pages->page_list[p++] = SVPD_SUPPORTED_PAGES;
9401 	/* Serial Number */
9402 	pages->page_list[p++] = SVPD_UNIT_SERIAL_NUMBER;
9403 	/* Device Identification */
9404 	pages->page_list[p++] = SVPD_DEVICE_ID;
9405 	/* Extended INQUIRY Data */
9406 	pages->page_list[p++] = SVPD_EXTENDED_INQUIRY_DATA;
9407 	/* Mode Page Policy */
9408 	pages->page_list[p++] = SVPD_MODE_PAGE_POLICY;
9409 	/* SCSI Ports */
9410 	pages->page_list[p++] = SVPD_SCSI_PORTS;
9411 	/* Third-party Copy */
9412 	pages->page_list[p++] = SVPD_SCSI_TPC;
9413 	/* SCSI Feature Sets */
9414 	pages->page_list[p++] = SVPD_SCSI_SFS;
9415 	if (lun != NULL && lun->be_lun->lun_type == T_DIRECT) {
9416 		/* Block limits */
9417 		pages->page_list[p++] = SVPD_BLOCK_LIMITS;
9418 		/* Block Device Characteristics */
9419 		pages->page_list[p++] = SVPD_BDC;
9420 		/* Logical Block Provisioning */
9421 		pages->page_list[p++] = SVPD_LBP;
9422 	}
9423 	pages->length = p;
9424 
9425 	ctl_set_success(ctsio);
9426 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9427 	ctsio->be_move_done = ctl_config_move_done;
9428 	ctl_datamove((union ctl_io *)ctsio);
9429 	return (CTL_RETVAL_COMPLETE);
9430 }
9431 
9432 /*
9433  * SCSI VPD page 0x80, the Unit Serial Number page.
9434  */
9435 static int
9436 ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9437 {
9438 	struct ctl_lun *lun = CTL_LUN(ctsio);
9439 	struct scsi_vpd_unit_serial_number *sn_ptr;
9440 	int data_len;
9441 
9442 	data_len = 4 + CTL_SN_LEN;
9443 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9444 	sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9445 	ctsio->kern_rel_offset = 0;
9446 	ctsio->kern_sg_entries = 0;
9447 	ctsio->kern_data_len = min(data_len, alloc_len);
9448 	ctsio->kern_total_len = ctsio->kern_data_len;
9449 
9450 	/*
9451 	 * The control device is always connected.  The disk device, on the
9452 	 * other hand, may not be online all the time.  Need to change this
9453 	 * to figure out whether the disk device is actually online or not.
9454 	 */
9455 	if (lun != NULL)
9456 		sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9457 				  lun->be_lun->lun_type;
9458 	else
9459 		sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9460 
9461 	sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9462 	sn_ptr->length = CTL_SN_LEN;
9463 	/*
9464 	 * If we don't have a LUN, we just leave the serial number as
9465 	 * all spaces.
9466 	 */
9467 	if (lun != NULL) {
9468 		strncpy((char *)sn_ptr->serial_num,
9469 			(char *)lun->be_lun->serial_num, CTL_SN_LEN);
9470 	} else
9471 		memset(sn_ptr->serial_num, 0x20, CTL_SN_LEN);
9472 
9473 	ctl_set_success(ctsio);
9474 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9475 	ctsio->be_move_done = ctl_config_move_done;
9476 	ctl_datamove((union ctl_io *)ctsio);
9477 	return (CTL_RETVAL_COMPLETE);
9478 }
9479 
9480 /*
9481  * SCSI VPD page 0x86, the Extended INQUIRY Data page.
9482  */
9483 static int
9484 ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9485 {
9486 	struct ctl_lun *lun = CTL_LUN(ctsio);
9487 	struct scsi_vpd_extended_inquiry_data *eid_ptr;
9488 	int data_len;
9489 
9490 	data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
9491 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9492 	eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9493 	ctsio->kern_sg_entries = 0;
9494 	ctsio->kern_rel_offset = 0;
9495 	ctsio->kern_data_len = min(data_len, alloc_len);
9496 	ctsio->kern_total_len = ctsio->kern_data_len;
9497 
9498 	/*
9499 	 * The control device is always connected.  The disk device, on the
9500 	 * other hand, may not be online all the time.
9501 	 */
9502 	if (lun != NULL)
9503 		eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9504 				     lun->be_lun->lun_type;
9505 	else
9506 		eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9507 	eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9508 	scsi_ulto2b(data_len - 4, eid_ptr->page_length);
9509 	/*
9510 	 * We support head of queue, ordered and simple tags.
9511 	 */
9512 	eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9513 	/*
9514 	 * Volatile cache supported.
9515 	 */
9516 	eid_ptr->flags3 = SVPD_EID_V_SUP;
9517 
9518 	/*
9519 	 * This means that we clear the REPORTED LUNS DATA HAS CHANGED unit
9520 	 * attention for a particular IT nexus on all LUNs once we report
9521 	 * it to that nexus once.  This bit is required as of SPC-4.
9522 	 */
9523 	eid_ptr->flags4 = SVPD_EID_LUICLR;
9524 
9525 	/*
9526 	 * We support revert to defaults (RTD) bit in MODE SELECT.
9527 	 */
9528 	eid_ptr->flags5 = SVPD_EID_RTD_SUP;
9529 
9530 	/*
9531 	 * XXX KDM in order to correctly answer this, we would need
9532 	 * information from the SIM to determine how much sense data it
9533 	 * can send.  So this would really be a path inquiry field, most
9534 	 * likely.  This can be set to a maximum of 252 according to SPC-4,
9535 	 * but the hardware may or may not be able to support that much.
9536 	 * 0 just means that the maximum sense data length is not reported.
9537 	 */
9538 	eid_ptr->max_sense_length = 0;
9539 
9540 	ctl_set_success(ctsio);
9541 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9542 	ctsio->be_move_done = ctl_config_move_done;
9543 	ctl_datamove((union ctl_io *)ctsio);
9544 	return (CTL_RETVAL_COMPLETE);
9545 }
9546 
9547 static int
9548 ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
9549 {
9550 	struct ctl_lun *lun = CTL_LUN(ctsio);
9551 	struct scsi_vpd_mode_page_policy *mpp_ptr;
9552 	int data_len;
9553 
9554 	data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9555 	    sizeof(struct scsi_vpd_mode_page_policy_descr);
9556 
9557 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9558 	mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
9559 	ctsio->kern_rel_offset = 0;
9560 	ctsio->kern_sg_entries = 0;
9561 	ctsio->kern_data_len = min(data_len, alloc_len);
9562 	ctsio->kern_total_len = ctsio->kern_data_len;
9563 
9564 	/*
9565 	 * The control device is always connected.  The disk device, on the
9566 	 * other hand, may not be online all the time.
9567 	 */
9568 	if (lun != NULL)
9569 		mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9570 				     lun->be_lun->lun_type;
9571 	else
9572 		mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9573 	mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
9574 	scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
9575 	mpp_ptr->descr[0].page_code = 0x3f;
9576 	mpp_ptr->descr[0].subpage_code = 0xff;
9577 	mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
9578 
9579 	ctl_set_success(ctsio);
9580 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9581 	ctsio->be_move_done = ctl_config_move_done;
9582 	ctl_datamove((union ctl_io *)ctsio);
9583 	return (CTL_RETVAL_COMPLETE);
9584 }
9585 
9586 /*
9587  * SCSI VPD page 0x83, the Device Identification page.
9588  */
9589 static int
9590 ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9591 {
9592 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9593 	struct ctl_port *port = CTL_PORT(ctsio);
9594 	struct ctl_lun *lun = CTL_LUN(ctsio);
9595 	struct scsi_vpd_device_id *devid_ptr;
9596 	struct scsi_vpd_id_descriptor *desc;
9597 	int data_len, g;
9598 	uint8_t proto;
9599 
9600 	data_len = sizeof(struct scsi_vpd_device_id) +
9601 	    sizeof(struct scsi_vpd_id_descriptor) +
9602 		sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9603 	    sizeof(struct scsi_vpd_id_descriptor) +
9604 		sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9605 	if (lun && lun->lun_devid)
9606 		data_len += lun->lun_devid->len;
9607 	if (port && port->port_devid)
9608 		data_len += port->port_devid->len;
9609 	if (port && port->target_devid)
9610 		data_len += port->target_devid->len;
9611 
9612 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9613 	devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9614 	ctsio->kern_sg_entries = 0;
9615 	ctsio->kern_rel_offset = 0;
9616 	ctsio->kern_sg_entries = 0;
9617 	ctsio->kern_data_len = min(data_len, alloc_len);
9618 	ctsio->kern_total_len = ctsio->kern_data_len;
9619 
9620 	/*
9621 	 * The control device is always connected.  The disk device, on the
9622 	 * other hand, may not be online all the time.
9623 	 */
9624 	if (lun != NULL)
9625 		devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9626 				     lun->be_lun->lun_type;
9627 	else
9628 		devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9629 	devid_ptr->page_code = SVPD_DEVICE_ID;
9630 	scsi_ulto2b(data_len - 4, devid_ptr->length);
9631 
9632 	if (port && port->port_type == CTL_PORT_FC)
9633 		proto = SCSI_PROTO_FC << 4;
9634 	else if (port && port->port_type == CTL_PORT_SAS)
9635 		proto = SCSI_PROTO_SAS << 4;
9636 	else if (port && port->port_type == CTL_PORT_ISCSI)
9637 		proto = SCSI_PROTO_ISCSI << 4;
9638 	else
9639 		proto = SCSI_PROTO_SPI << 4;
9640 	desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
9641 
9642 	/*
9643 	 * We're using a LUN association here.  i.e., this device ID is a
9644 	 * per-LUN identifier.
9645 	 */
9646 	if (lun && lun->lun_devid) {
9647 		memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
9648 		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9649 		    lun->lun_devid->len);
9650 	}
9651 
9652 	/*
9653 	 * This is for the WWPN which is a port association.
9654 	 */
9655 	if (port && port->port_devid) {
9656 		memcpy(desc, port->port_devid->data, port->port_devid->len);
9657 		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9658 		    port->port_devid->len);
9659 	}
9660 
9661 	/*
9662 	 * This is for the Relative Target Port(type 4h) identifier
9663 	 */
9664 	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9665 	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9666 	    SVPD_ID_TYPE_RELTARG;
9667 	desc->length = 4;
9668 	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
9669 	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9670 	    sizeof(struct scsi_vpd_id_rel_trgt_port_id));
9671 
9672 	/*
9673 	 * This is for the Target Port Group(type 5h) identifier
9674 	 */
9675 	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9676 	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9677 	    SVPD_ID_TYPE_TPORTGRP;
9678 	desc->length = 4;
9679 	if (softc->is_single ||
9680 	    (port && port->status & CTL_PORT_STATUS_HA_SHARED))
9681 		g = 1;
9682 	else
9683 		g = 2 + ctsio->io_hdr.nexus.targ_port / softc->port_cnt;
9684 	scsi_ulto2b(g, &desc->identifier[2]);
9685 	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9686 	    sizeof(struct scsi_vpd_id_trgt_port_grp_id));
9687 
9688 	/*
9689 	 * This is for the Target identifier
9690 	 */
9691 	if (port && port->target_devid) {
9692 		memcpy(desc, port->target_devid->data, port->target_devid->len);
9693 	}
9694 
9695 	ctl_set_success(ctsio);
9696 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9697 	ctsio->be_move_done = ctl_config_move_done;
9698 	ctl_datamove((union ctl_io *)ctsio);
9699 	return (CTL_RETVAL_COMPLETE);
9700 }
9701 
9702 static int
9703 ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
9704 {
9705 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9706 	struct ctl_lun *lun = CTL_LUN(ctsio);
9707 	struct scsi_vpd_scsi_ports *sp;
9708 	struct scsi_vpd_port_designation *pd;
9709 	struct scsi_vpd_port_designation_cont *pdc;
9710 	struct ctl_port *port;
9711 	int data_len, num_target_ports, iid_len, id_len;
9712 
9713 	num_target_ports = 0;
9714 	iid_len = 0;
9715 	id_len = 0;
9716 	mtx_lock(&softc->ctl_lock);
9717 	STAILQ_FOREACH(port, &softc->port_list, links) {
9718 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9719 			continue;
9720 		if (lun != NULL &&
9721 		    ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
9722 			continue;
9723 		num_target_ports++;
9724 		if (port->init_devid)
9725 			iid_len += port->init_devid->len;
9726 		if (port->port_devid)
9727 			id_len += port->port_devid->len;
9728 	}
9729 	mtx_unlock(&softc->ctl_lock);
9730 
9731 	data_len = sizeof(struct scsi_vpd_scsi_ports) +
9732 	    num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
9733 	     sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
9734 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9735 	sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
9736 	ctsio->kern_sg_entries = 0;
9737 	ctsio->kern_rel_offset = 0;
9738 	ctsio->kern_sg_entries = 0;
9739 	ctsio->kern_data_len = min(data_len, alloc_len);
9740 	ctsio->kern_total_len = ctsio->kern_data_len;
9741 
9742 	/*
9743 	 * The control device is always connected.  The disk device, on the
9744 	 * other hand, may not be online all the time.  Need to change this
9745 	 * to figure out whether the disk device is actually online or not.
9746 	 */
9747 	if (lun != NULL)
9748 		sp->device = (SID_QUAL_LU_CONNECTED << 5) |
9749 				  lun->be_lun->lun_type;
9750 	else
9751 		sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9752 
9753 	sp->page_code = SVPD_SCSI_PORTS;
9754 	scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
9755 	    sp->page_length);
9756 	pd = &sp->design[0];
9757 
9758 	mtx_lock(&softc->ctl_lock);
9759 	STAILQ_FOREACH(port, &softc->port_list, links) {
9760 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9761 			continue;
9762 		if (lun != NULL &&
9763 		    ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
9764 			continue;
9765 		scsi_ulto2b(port->targ_port, pd->relative_port_id);
9766 		if (port->init_devid) {
9767 			iid_len = port->init_devid->len;
9768 			memcpy(pd->initiator_transportid,
9769 			    port->init_devid->data, port->init_devid->len);
9770 		} else
9771 			iid_len = 0;
9772 		scsi_ulto2b(iid_len, pd->initiator_transportid_length);
9773 		pdc = (struct scsi_vpd_port_designation_cont *)
9774 		    (&pd->initiator_transportid[iid_len]);
9775 		if (port->port_devid) {
9776 			id_len = port->port_devid->len;
9777 			memcpy(pdc->target_port_descriptors,
9778 			    port->port_devid->data, port->port_devid->len);
9779 		} else
9780 			id_len = 0;
9781 		scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
9782 		pd = (struct scsi_vpd_port_designation *)
9783 		    ((uint8_t *)pdc->target_port_descriptors + id_len);
9784 	}
9785 	mtx_unlock(&softc->ctl_lock);
9786 
9787 	ctl_set_success(ctsio);
9788 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9789 	ctsio->be_move_done = ctl_config_move_done;
9790 	ctl_datamove((union ctl_io *)ctsio);
9791 	return (CTL_RETVAL_COMPLETE);
9792 }
9793 
9794 static int
9795 ctl_inquiry_evpd_sfs(struct ctl_scsiio *ctsio, int alloc_len)
9796 {
9797 	struct ctl_lun *lun = CTL_LUN(ctsio);
9798 	struct scsi_vpd_sfs *sfs_ptr;
9799 	int sfs_page_size, n;
9800 
9801 	sfs_page_size = sizeof(*sfs_ptr) + 5 * 2;
9802 	ctsio->kern_data_ptr = malloc(sfs_page_size, M_CTL, M_WAITOK | M_ZERO);
9803 	sfs_ptr = (struct scsi_vpd_sfs *)ctsio->kern_data_ptr;
9804 	ctsio->kern_sg_entries = 0;
9805 	ctsio->kern_rel_offset = 0;
9806 	ctsio->kern_sg_entries = 0;
9807 	ctsio->kern_data_len = min(sfs_page_size, alloc_len);
9808 	ctsio->kern_total_len = ctsio->kern_data_len;
9809 
9810 	/*
9811 	 * The control device is always connected.  The disk device, on the
9812 	 * other hand, may not be online all the time.  Need to change this
9813 	 * to figure out whether the disk device is actually online or not.
9814 	 */
9815 	if (lun != NULL)
9816 		sfs_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9817 				  lun->be_lun->lun_type;
9818 	else
9819 		sfs_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9820 
9821 	sfs_ptr->page_code = SVPD_SCSI_SFS;
9822 	n = 0;
9823 	/* Discovery 2016 */
9824 	scsi_ulto2b(0x0001, &sfs_ptr->codes[2 * n++]);
9825 	if (lun != NULL && lun->be_lun->lun_type == T_DIRECT) {
9826 		 /* SBC Base 2016 */
9827 		scsi_ulto2b(0x0101, &sfs_ptr->codes[2 * n++]);
9828 		 /* SBC Base 2010 */
9829 		scsi_ulto2b(0x0102, &sfs_ptr->codes[2 * n++]);
9830 		if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9831 			/* Basic Provisioning 2016 */
9832 			scsi_ulto2b(0x0103, &sfs_ptr->codes[2 * n++]);
9833 		}
9834 		/* Drive Maintenance 2016 */
9835 		//scsi_ulto2b(0x0104, &sfs_ptr->codes[2 * n++]);
9836 	}
9837 	scsi_ulto2b(4 + 2 * n, sfs_ptr->page_length);
9838 
9839 	ctl_set_success(ctsio);
9840 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9841 	ctsio->be_move_done = ctl_config_move_done;
9842 	ctl_datamove((union ctl_io *)ctsio);
9843 	return (CTL_RETVAL_COMPLETE);
9844 }
9845 
9846 static int
9847 ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
9848 {
9849 	struct ctl_lun *lun = CTL_LUN(ctsio);
9850 	struct scsi_vpd_block_limits *bl_ptr;
9851 	const char *val;
9852 	uint64_t ival;
9853 
9854 	ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
9855 	bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
9856 	ctsio->kern_sg_entries = 0;
9857 	ctsio->kern_rel_offset = 0;
9858 	ctsio->kern_sg_entries = 0;
9859 	ctsio->kern_data_len = min(sizeof(*bl_ptr), alloc_len);
9860 	ctsio->kern_total_len = ctsio->kern_data_len;
9861 
9862 	/*
9863 	 * The control device is always connected.  The disk device, on the
9864 	 * other hand, may not be online all the time.  Need to change this
9865 	 * to figure out whether the disk device is actually online or not.
9866 	 */
9867 	if (lun != NULL)
9868 		bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9869 				  lun->be_lun->lun_type;
9870 	else
9871 		bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9872 
9873 	bl_ptr->page_code = SVPD_BLOCK_LIMITS;
9874 	scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
9875 	bl_ptr->max_cmp_write_len = 0xff;
9876 	scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
9877 	if (lun != NULL) {
9878 		scsi_ulto4b(lun->be_lun->opttxferlen, bl_ptr->opt_txfer_len);
9879 		if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9880 			ival = 0xffffffff;
9881 			val = dnvlist_get_string(lun->be_lun->options,
9882 			    "unmap_max_lba", NULL);
9883 			if (val != NULL)
9884 				ctl_expand_number(val, &ival);
9885 			scsi_ulto4b(ival, bl_ptr->max_unmap_lba_cnt);
9886 			ival = 0xffffffff;
9887 			val = dnvlist_get_string(lun->be_lun->options,
9888 			    "unmap_max_descr", NULL);
9889 			if (val != NULL)
9890 				ctl_expand_number(val, &ival);
9891 			scsi_ulto4b(ival, bl_ptr->max_unmap_blk_cnt);
9892 			if (lun->be_lun->ublockexp != 0) {
9893 				scsi_ulto4b((1 << lun->be_lun->ublockexp),
9894 				    bl_ptr->opt_unmap_grain);
9895 				scsi_ulto4b(0x80000000 | lun->be_lun->ublockoff,
9896 				    bl_ptr->unmap_grain_align);
9897 			}
9898 		}
9899 		scsi_ulto4b(lun->be_lun->atomicblock,
9900 		    bl_ptr->max_atomic_transfer_length);
9901 		scsi_ulto4b(0, bl_ptr->atomic_alignment);
9902 		scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
9903 		scsi_ulto4b(0, bl_ptr->max_atomic_transfer_length_with_atomic_boundary);
9904 		scsi_ulto4b(0, bl_ptr->max_atomic_boundary_size);
9905 		ival = UINT64_MAX;
9906 		val = dnvlist_get_string(lun->be_lun->options,
9907 		    "write_same_max_lba", NULL);
9908 		if (val != NULL)
9909 			ctl_expand_number(val, &ival);
9910 		scsi_u64to8b(ival, bl_ptr->max_write_same_length);
9911 		if (lun->be_lun->maxlba + 1 > ival)
9912 			bl_ptr->flags |= SVPD_BL_WSNZ;
9913 	}
9914 
9915 	ctl_set_success(ctsio);
9916 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9917 	ctsio->be_move_done = ctl_config_move_done;
9918 	ctl_datamove((union ctl_io *)ctsio);
9919 	return (CTL_RETVAL_COMPLETE);
9920 }
9921 
9922 static int
9923 ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
9924 {
9925 	struct ctl_lun *lun = CTL_LUN(ctsio);
9926 	struct scsi_vpd_block_device_characteristics *bdc_ptr;
9927 	const char *value;
9928 	u_int i;
9929 
9930 	ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
9931 	bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
9932 	ctsio->kern_sg_entries = 0;
9933 	ctsio->kern_rel_offset = 0;
9934 	ctsio->kern_data_len = min(sizeof(*bdc_ptr), alloc_len);
9935 	ctsio->kern_total_len = ctsio->kern_data_len;
9936 
9937 	/*
9938 	 * The control device is always connected.  The disk device, on the
9939 	 * other hand, may not be online all the time.  Need to change this
9940 	 * to figure out whether the disk device is actually online or not.
9941 	 */
9942 	if (lun != NULL)
9943 		bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9944 				  lun->be_lun->lun_type;
9945 	else
9946 		bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9947 	bdc_ptr->page_code = SVPD_BDC;
9948 	scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
9949 	if (lun != NULL &&
9950 	    (value = dnvlist_get_string(lun->be_lun->options, "rpm", NULL)) != NULL)
9951 		i = strtol(value, NULL, 0);
9952 	else
9953 		i = CTL_DEFAULT_ROTATION_RATE;
9954 	scsi_ulto2b(i, bdc_ptr->medium_rotation_rate);
9955 	if (lun != NULL &&
9956 	    (value = dnvlist_get_string(lun->be_lun->options, "formfactor", NULL)) != NULL)
9957 		i = strtol(value, NULL, 0);
9958 	else
9959 		i = 0;
9960 	bdc_ptr->wab_wac_ff = (i & 0x0f);
9961 	bdc_ptr->flags = SVPD_RBWZ | SVPD_FUAB | SVPD_VBULS;
9962 
9963 	ctl_set_success(ctsio);
9964 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9965 	ctsio->be_move_done = ctl_config_move_done;
9966 	ctl_datamove((union ctl_io *)ctsio);
9967 	return (CTL_RETVAL_COMPLETE);
9968 }
9969 
9970 static int
9971 ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
9972 {
9973 	struct ctl_lun *lun = CTL_LUN(ctsio);
9974 	struct scsi_vpd_logical_block_prov *lbp_ptr;
9975 	const char *value;
9976 
9977 	ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
9978 	lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
9979 	ctsio->kern_sg_entries = 0;
9980 	ctsio->kern_rel_offset = 0;
9981 	ctsio->kern_data_len = min(sizeof(*lbp_ptr), alloc_len);
9982 	ctsio->kern_total_len = ctsio->kern_data_len;
9983 
9984 	/*
9985 	 * The control device is always connected.  The disk device, on the
9986 	 * other hand, may not be online all the time.  Need to change this
9987 	 * to figure out whether the disk device is actually online or not.
9988 	 */
9989 	if (lun != NULL)
9990 		lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9991 				  lun->be_lun->lun_type;
9992 	else
9993 		lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9994 
9995 	lbp_ptr->page_code = SVPD_LBP;
9996 	scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
9997 	lbp_ptr->threshold_exponent = CTL_LBP_EXPONENT;
9998 	if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9999 		lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
10000 		    SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
10001 		value = dnvlist_get_string(lun->be_lun->options,
10002 		    "provisioning_type", NULL);
10003 		if (value != NULL) {
10004 			if (strcmp(value, "resource") == 0)
10005 				lbp_ptr->prov_type = SVPD_LBP_RESOURCE;
10006 			else if (strcmp(value, "thin") == 0)
10007 				lbp_ptr->prov_type = SVPD_LBP_THIN;
10008 		} else
10009 			lbp_ptr->prov_type = SVPD_LBP_THIN;
10010 	}
10011 
10012 	ctl_set_success(ctsio);
10013 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10014 	ctsio->be_move_done = ctl_config_move_done;
10015 	ctl_datamove((union ctl_io *)ctsio);
10016 	return (CTL_RETVAL_COMPLETE);
10017 }
10018 
10019 /*
10020  * INQUIRY with the EVPD bit set.
10021  */
10022 static int
10023 ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
10024 {
10025 	struct ctl_lun *lun = CTL_LUN(ctsio);
10026 	struct scsi_inquiry *cdb;
10027 	int alloc_len, retval;
10028 
10029 	cdb = (struct scsi_inquiry *)ctsio->cdb;
10030 	alloc_len = scsi_2btoul(cdb->length);
10031 
10032 	switch (cdb->page_code) {
10033 	case SVPD_SUPPORTED_PAGES:
10034 		retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
10035 		break;
10036 	case SVPD_UNIT_SERIAL_NUMBER:
10037 		retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
10038 		break;
10039 	case SVPD_DEVICE_ID:
10040 		retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
10041 		break;
10042 	case SVPD_EXTENDED_INQUIRY_DATA:
10043 		retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
10044 		break;
10045 	case SVPD_MODE_PAGE_POLICY:
10046 		retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
10047 		break;
10048 	case SVPD_SCSI_PORTS:
10049 		retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10050 		break;
10051 	case SVPD_SCSI_TPC:
10052 		retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
10053 		break;
10054 	case SVPD_SCSI_SFS:
10055 		retval = ctl_inquiry_evpd_sfs(ctsio, alloc_len);
10056 		break;
10057 	case SVPD_BLOCK_LIMITS:
10058 		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10059 			goto err;
10060 		retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10061 		break;
10062 	case SVPD_BDC:
10063 		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10064 			goto err;
10065 		retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
10066 		break;
10067 	case SVPD_LBP:
10068 		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10069 			goto err;
10070 		retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10071 		break;
10072 	default:
10073 err:
10074 		ctl_set_invalid_field(ctsio,
10075 				      /*sks_valid*/ 1,
10076 				      /*command*/ 1,
10077 				      /*field*/ 2,
10078 				      /*bit_valid*/ 0,
10079 				      /*bit*/ 0);
10080 		ctl_done((union ctl_io *)ctsio);
10081 		retval = CTL_RETVAL_COMPLETE;
10082 		break;
10083 	}
10084 
10085 	return (retval);
10086 }
10087 
10088 /*
10089  * Standard INQUIRY data.
10090  */
10091 static int
10092 ctl_inquiry_std(struct ctl_scsiio *ctsio)
10093 {
10094 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
10095 	struct ctl_port *port = CTL_PORT(ctsio);
10096 	struct ctl_lun *lun = CTL_LUN(ctsio);
10097 	struct scsi_inquiry_data *inq_ptr;
10098 	struct scsi_inquiry *cdb;
10099 	const char *val;
10100 	uint32_t alloc_len, data_len;
10101 	ctl_port_type port_type;
10102 
10103 	port_type = port->port_type;
10104 	if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10105 		port_type = CTL_PORT_SCSI;
10106 
10107 	cdb = (struct scsi_inquiry *)ctsio->cdb;
10108 	alloc_len = scsi_2btoul(cdb->length);
10109 
10110 	/*
10111 	 * We malloc the full inquiry data size here and fill it
10112 	 * in.  If the user only asks for less, we'll give him
10113 	 * that much.
10114 	 */
10115 	data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
10116 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10117 	inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10118 	ctsio->kern_sg_entries = 0;
10119 	ctsio->kern_rel_offset = 0;
10120 	ctsio->kern_data_len = min(data_len, alloc_len);
10121 	ctsio->kern_total_len = ctsio->kern_data_len;
10122 
10123 	if (lun != NULL) {
10124 		if ((lun->flags & CTL_LUN_PRIMARY_SC) ||
10125 		    softc->ha_link >= CTL_HA_LINK_UNKNOWN) {
10126 			inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10127 			    lun->be_lun->lun_type;
10128 		} else {
10129 			inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) |
10130 			    lun->be_lun->lun_type;
10131 		}
10132 		if (lun->flags & CTL_LUN_REMOVABLE)
10133 			inq_ptr->dev_qual2 |= SID_RMB;
10134 	} else
10135 		inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10136 
10137 	/* RMB in byte 2 is 0 */
10138 	inq_ptr->version = SCSI_REV_SPC5;
10139 
10140 	/*
10141 	 * According to SAM-3, even if a device only supports a single
10142 	 * level of LUN addressing, it should still set the HISUP bit:
10143 	 *
10144 	 * 4.9.1 Logical unit numbers overview
10145 	 *
10146 	 * All logical unit number formats described in this standard are
10147 	 * hierarchical in structure even when only a single level in that
10148 	 * hierarchy is used. The HISUP bit shall be set to one in the
10149 	 * standard INQUIRY data (see SPC-2) when any logical unit number
10150 	 * format described in this standard is used.  Non-hierarchical
10151 	 * formats are outside the scope of this standard.
10152 	 *
10153 	 * Therefore we set the HiSup bit here.
10154 	 *
10155 	 * The response format is 2, per SPC-3.
10156 	 */
10157 	inq_ptr->response_format = SID_HiSup | 2;
10158 
10159 	inq_ptr->additional_length = data_len -
10160 	    (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10161 	CTL_DEBUG_PRINT(("additional_length = %d\n",
10162 			 inq_ptr->additional_length));
10163 
10164 	inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10165 	if (port_type == CTL_PORT_SCSI)
10166 		inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10167 	inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10168 	inq_ptr->flags = SID_CmdQue;
10169 	if (port_type == CTL_PORT_SCSI)
10170 		inq_ptr->flags |= SID_WBus16 | SID_Sync;
10171 
10172 	/*
10173 	 * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10174 	 * We have 8 bytes for the vendor name, and 16 bytes for the device
10175 	 * name and 4 bytes for the revision.
10176 	 */
10177 	if (lun == NULL || (val = dnvlist_get_string(lun->be_lun->options,
10178 	    "vendor", NULL)) == NULL) {
10179 		strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10180 	} else {
10181 		memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10182 		strncpy(inq_ptr->vendor, val,
10183 		    min(sizeof(inq_ptr->vendor), strlen(val)));
10184 	}
10185 	if (lun == NULL) {
10186 		strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10187 		    sizeof(inq_ptr->product));
10188 	} else if ((val = dnvlist_get_string(lun->be_lun->options, "product",
10189 	    NULL)) == NULL) {
10190 		switch (lun->be_lun->lun_type) {
10191 		case T_DIRECT:
10192 			strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10193 			    sizeof(inq_ptr->product));
10194 			break;
10195 		case T_PROCESSOR:
10196 			strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10197 			    sizeof(inq_ptr->product));
10198 			break;
10199 		case T_CDROM:
10200 			strncpy(inq_ptr->product, CTL_CDROM_PRODUCT,
10201 			    sizeof(inq_ptr->product));
10202 			break;
10203 		default:
10204 			strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10205 			    sizeof(inq_ptr->product));
10206 			break;
10207 		}
10208 	} else {
10209 		memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10210 		strncpy(inq_ptr->product, val,
10211 		    min(sizeof(inq_ptr->product), strlen(val)));
10212 	}
10213 
10214 	/*
10215 	 * XXX make this a macro somewhere so it automatically gets
10216 	 * incremented when we make changes.
10217 	 */
10218 	if (lun == NULL || (val = dnvlist_get_string(lun->be_lun->options,
10219 	    "revision", NULL)) == NULL) {
10220 		strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10221 	} else {
10222 		memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10223 		strncpy(inq_ptr->revision, val,
10224 		    min(sizeof(inq_ptr->revision), strlen(val)));
10225 	}
10226 
10227 	/*
10228 	 * For parallel SCSI, we support double transition and single
10229 	 * transition clocking.  We also support QAS (Quick Arbitration
10230 	 * and Selection) and Information Unit transfers on both the
10231 	 * control and array devices.
10232 	 */
10233 	if (port_type == CTL_PORT_SCSI)
10234 		inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10235 				    SID_SPI_IUS;
10236 
10237 	/* SAM-6 (no version claimed) */
10238 	scsi_ulto2b(0x00C0, inq_ptr->version1);
10239 	/* SPC-5 (no version claimed) */
10240 	scsi_ulto2b(0x05C0, inq_ptr->version2);
10241 	if (port_type == CTL_PORT_FC) {
10242 		/* FCP-2 ANSI INCITS.350:2003 */
10243 		scsi_ulto2b(0x0917, inq_ptr->version3);
10244 	} else if (port_type == CTL_PORT_SCSI) {
10245 		/* SPI-4 ANSI INCITS.362:200x */
10246 		scsi_ulto2b(0x0B56, inq_ptr->version3);
10247 	} else if (port_type == CTL_PORT_ISCSI) {
10248 		/* iSCSI (no version claimed) */
10249 		scsi_ulto2b(0x0960, inq_ptr->version3);
10250 	} else if (port_type == CTL_PORT_SAS) {
10251 		/* SAS (no version claimed) */
10252 		scsi_ulto2b(0x0BE0, inq_ptr->version3);
10253 	} else if (port_type == CTL_PORT_UMASS) {
10254 		/* USB Mass Storage Class Bulk-Only Transport, Revision 1.0 */
10255 		scsi_ulto2b(0x1730, inq_ptr->version3);
10256 	}
10257 
10258 	if (lun == NULL) {
10259 		/* SBC-4 (no version claimed) */
10260 		scsi_ulto2b(0x0600, inq_ptr->version4);
10261 	} else {
10262 		switch (lun->be_lun->lun_type) {
10263 		case T_DIRECT:
10264 			/* SBC-4 (no version claimed) */
10265 			scsi_ulto2b(0x0600, inq_ptr->version4);
10266 			break;
10267 		case T_PROCESSOR:
10268 			break;
10269 		case T_CDROM:
10270 			/* MMC-6 (no version claimed) */
10271 			scsi_ulto2b(0x04E0, inq_ptr->version4);
10272 			break;
10273 		default:
10274 			break;
10275 		}
10276 	}
10277 
10278 	ctl_set_success(ctsio);
10279 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10280 	ctsio->be_move_done = ctl_config_move_done;
10281 	ctl_datamove((union ctl_io *)ctsio);
10282 	return (CTL_RETVAL_COMPLETE);
10283 }
10284 
10285 int
10286 ctl_inquiry(struct ctl_scsiio *ctsio)
10287 {
10288 	struct scsi_inquiry *cdb;
10289 	int retval;
10290 
10291 	CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10292 
10293 	cdb = (struct scsi_inquiry *)ctsio->cdb;
10294 	if (cdb->byte2 & SI_EVPD)
10295 		retval = ctl_inquiry_evpd(ctsio);
10296 	else if (cdb->page_code == 0)
10297 		retval = ctl_inquiry_std(ctsio);
10298 	else {
10299 		ctl_set_invalid_field(ctsio,
10300 				      /*sks_valid*/ 1,
10301 				      /*command*/ 1,
10302 				      /*field*/ 2,
10303 				      /*bit_valid*/ 0,
10304 				      /*bit*/ 0);
10305 		ctl_done((union ctl_io *)ctsio);
10306 		return (CTL_RETVAL_COMPLETE);
10307 	}
10308 
10309 	return (retval);
10310 }
10311 
10312 int
10313 ctl_get_config(struct ctl_scsiio *ctsio)
10314 {
10315 	struct ctl_lun *lun = CTL_LUN(ctsio);
10316 	struct scsi_get_config_header *hdr;
10317 	struct scsi_get_config_feature *feature;
10318 	struct scsi_get_config *cdb;
10319 	uint32_t alloc_len, data_len;
10320 	int rt, starting;
10321 
10322 	cdb = (struct scsi_get_config *)ctsio->cdb;
10323 	rt = (cdb->rt & SGC_RT_MASK);
10324 	starting = scsi_2btoul(cdb->starting_feature);
10325 	alloc_len = scsi_2btoul(cdb->length);
10326 
10327 	data_len = sizeof(struct scsi_get_config_header) +
10328 	    sizeof(struct scsi_get_config_feature) + 8 +
10329 	    sizeof(struct scsi_get_config_feature) + 8 +
10330 	    sizeof(struct scsi_get_config_feature) + 4 +
10331 	    sizeof(struct scsi_get_config_feature) + 4 +
10332 	    sizeof(struct scsi_get_config_feature) + 8 +
10333 	    sizeof(struct scsi_get_config_feature) +
10334 	    sizeof(struct scsi_get_config_feature) + 4 +
10335 	    sizeof(struct scsi_get_config_feature) + 4 +
10336 	    sizeof(struct scsi_get_config_feature) + 4 +
10337 	    sizeof(struct scsi_get_config_feature) + 4 +
10338 	    sizeof(struct scsi_get_config_feature) + 4 +
10339 	    sizeof(struct scsi_get_config_feature) + 4;
10340 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10341 	ctsio->kern_sg_entries = 0;
10342 	ctsio->kern_rel_offset = 0;
10343 
10344 	hdr = (struct scsi_get_config_header *)ctsio->kern_data_ptr;
10345 	if (lun->flags & CTL_LUN_NO_MEDIA)
10346 		scsi_ulto2b(0x0000, hdr->current_profile);
10347 	else
10348 		scsi_ulto2b(0x0010, hdr->current_profile);
10349 	feature = (struct scsi_get_config_feature *)(hdr + 1);
10350 
10351 	if (starting > 0x003b)
10352 		goto done;
10353 	if (starting > 0x003a)
10354 		goto f3b;
10355 	if (starting > 0x002b)
10356 		goto f3a;
10357 	if (starting > 0x002a)
10358 		goto f2b;
10359 	if (starting > 0x001f)
10360 		goto f2a;
10361 	if (starting > 0x001e)
10362 		goto f1f;
10363 	if (starting > 0x001d)
10364 		goto f1e;
10365 	if (starting > 0x0010)
10366 		goto f1d;
10367 	if (starting > 0x0003)
10368 		goto f10;
10369 	if (starting > 0x0002)
10370 		goto f3;
10371 	if (starting > 0x0001)
10372 		goto f2;
10373 	if (starting > 0x0000)
10374 		goto f1;
10375 
10376 	/* Profile List */
10377 	scsi_ulto2b(0x0000, feature->feature_code);
10378 	feature->flags = SGC_F_PERSISTENT | SGC_F_CURRENT;
10379 	feature->add_length = 8;
10380 	scsi_ulto2b(0x0008, &feature->feature_data[0]);	/* CD-ROM */
10381 	feature->feature_data[2] = 0x00;
10382 	scsi_ulto2b(0x0010, &feature->feature_data[4]);	/* DVD-ROM */
10383 	feature->feature_data[6] = 0x01;
10384 	feature = (struct scsi_get_config_feature *)
10385 	    &feature->feature_data[feature->add_length];
10386 
10387 f1:	/* Core */
10388 	scsi_ulto2b(0x0001, feature->feature_code);
10389 	feature->flags = 0x08 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10390 	feature->add_length = 8;
10391 	scsi_ulto4b(0x00000000, &feature->feature_data[0]);
10392 	feature->feature_data[4] = 0x03;
10393 	feature = (struct scsi_get_config_feature *)
10394 	    &feature->feature_data[feature->add_length];
10395 
10396 f2:	/* Morphing */
10397 	scsi_ulto2b(0x0002, feature->feature_code);
10398 	feature->flags = 0x04 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10399 	feature->add_length = 4;
10400 	feature->feature_data[0] = 0x02;
10401 	feature = (struct scsi_get_config_feature *)
10402 	    &feature->feature_data[feature->add_length];
10403 
10404 f3:	/* Removable Medium */
10405 	scsi_ulto2b(0x0003, feature->feature_code);
10406 	feature->flags = 0x04 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10407 	feature->add_length = 4;
10408 	feature->feature_data[0] = 0x39;
10409 	feature = (struct scsi_get_config_feature *)
10410 	    &feature->feature_data[feature->add_length];
10411 
10412 	if (rt == SGC_RT_CURRENT && (lun->flags & CTL_LUN_NO_MEDIA))
10413 		goto done;
10414 
10415 f10:	/* Random Read */
10416 	scsi_ulto2b(0x0010, feature->feature_code);
10417 	feature->flags = 0x00;
10418 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10419 		feature->flags |= SGC_F_CURRENT;
10420 	feature->add_length = 8;
10421 	scsi_ulto4b(lun->be_lun->blocksize, &feature->feature_data[0]);
10422 	scsi_ulto2b(1, &feature->feature_data[4]);
10423 	feature->feature_data[6] = 0x00;
10424 	feature = (struct scsi_get_config_feature *)
10425 	    &feature->feature_data[feature->add_length];
10426 
10427 f1d:	/* Multi-Read */
10428 	scsi_ulto2b(0x001D, feature->feature_code);
10429 	feature->flags = 0x00;
10430 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10431 		feature->flags |= SGC_F_CURRENT;
10432 	feature->add_length = 0;
10433 	feature = (struct scsi_get_config_feature *)
10434 	    &feature->feature_data[feature->add_length];
10435 
10436 f1e:	/* CD Read */
10437 	scsi_ulto2b(0x001E, feature->feature_code);
10438 	feature->flags = 0x00;
10439 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10440 		feature->flags |= SGC_F_CURRENT;
10441 	feature->add_length = 4;
10442 	feature->feature_data[0] = 0x00;
10443 	feature = (struct scsi_get_config_feature *)
10444 	    &feature->feature_data[feature->add_length];
10445 
10446 f1f:	/* DVD Read */
10447 	scsi_ulto2b(0x001F, feature->feature_code);
10448 	feature->flags = 0x08;
10449 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10450 		feature->flags |= SGC_F_CURRENT;
10451 	feature->add_length = 4;
10452 	feature->feature_data[0] = 0x01;
10453 	feature->feature_data[2] = 0x03;
10454 	feature = (struct scsi_get_config_feature *)
10455 	    &feature->feature_data[feature->add_length];
10456 
10457 f2a:	/* DVD+RW */
10458 	scsi_ulto2b(0x002A, feature->feature_code);
10459 	feature->flags = 0x04;
10460 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10461 		feature->flags |= SGC_F_CURRENT;
10462 	feature->add_length = 4;
10463 	feature->feature_data[0] = 0x00;
10464 	feature->feature_data[1] = 0x00;
10465 	feature = (struct scsi_get_config_feature *)
10466 	    &feature->feature_data[feature->add_length];
10467 
10468 f2b:	/* DVD+R */
10469 	scsi_ulto2b(0x002B, feature->feature_code);
10470 	feature->flags = 0x00;
10471 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10472 		feature->flags |= SGC_F_CURRENT;
10473 	feature->add_length = 4;
10474 	feature->feature_data[0] = 0x00;
10475 	feature = (struct scsi_get_config_feature *)
10476 	    &feature->feature_data[feature->add_length];
10477 
10478 f3a:	/* DVD+RW Dual Layer */
10479 	scsi_ulto2b(0x003A, feature->feature_code);
10480 	feature->flags = 0x00;
10481 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10482 		feature->flags |= SGC_F_CURRENT;
10483 	feature->add_length = 4;
10484 	feature->feature_data[0] = 0x00;
10485 	feature->feature_data[1] = 0x00;
10486 	feature = (struct scsi_get_config_feature *)
10487 	    &feature->feature_data[feature->add_length];
10488 
10489 f3b:	/* DVD+R Dual Layer */
10490 	scsi_ulto2b(0x003B, feature->feature_code);
10491 	feature->flags = 0x00;
10492 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10493 		feature->flags |= SGC_F_CURRENT;
10494 	feature->add_length = 4;
10495 	feature->feature_data[0] = 0x00;
10496 	feature = (struct scsi_get_config_feature *)
10497 	    &feature->feature_data[feature->add_length];
10498 
10499 done:
10500 	data_len = (uint8_t *)feature - (uint8_t *)hdr;
10501 	if (rt == SGC_RT_SPECIFIC && data_len > 4) {
10502 		feature = (struct scsi_get_config_feature *)(hdr + 1);
10503 		if (scsi_2btoul(feature->feature_code) == starting)
10504 			feature = (struct scsi_get_config_feature *)
10505 			    &feature->feature_data[feature->add_length];
10506 		data_len = (uint8_t *)feature - (uint8_t *)hdr;
10507 	}
10508 	scsi_ulto4b(data_len - 4, hdr->data_length);
10509 	ctsio->kern_data_len = min(data_len, alloc_len);
10510 	ctsio->kern_total_len = ctsio->kern_data_len;
10511 
10512 	ctl_set_success(ctsio);
10513 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10514 	ctsio->be_move_done = ctl_config_move_done;
10515 	ctl_datamove((union ctl_io *)ctsio);
10516 	return (CTL_RETVAL_COMPLETE);
10517 }
10518 
10519 int
10520 ctl_get_event_status(struct ctl_scsiio *ctsio)
10521 {
10522 	struct scsi_get_event_status_header *hdr;
10523 	struct scsi_get_event_status *cdb;
10524 	uint32_t alloc_len, data_len;
10525 
10526 	cdb = (struct scsi_get_event_status *)ctsio->cdb;
10527 	if ((cdb->byte2 & SGESN_POLLED) == 0) {
10528 		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1, /*command*/ 1,
10529 		    /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
10530 		ctl_done((union ctl_io *)ctsio);
10531 		return (CTL_RETVAL_COMPLETE);
10532 	}
10533 	alloc_len = scsi_2btoul(cdb->length);
10534 
10535 	data_len = sizeof(struct scsi_get_event_status_header);
10536 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10537 	ctsio->kern_sg_entries = 0;
10538 	ctsio->kern_rel_offset = 0;
10539 	ctsio->kern_data_len = min(data_len, alloc_len);
10540 	ctsio->kern_total_len = ctsio->kern_data_len;
10541 
10542 	hdr = (struct scsi_get_event_status_header *)ctsio->kern_data_ptr;
10543 	scsi_ulto2b(0, hdr->descr_length);
10544 	hdr->nea_class = SGESN_NEA;
10545 	hdr->supported_class = 0;
10546 
10547 	ctl_set_success(ctsio);
10548 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10549 	ctsio->be_move_done = ctl_config_move_done;
10550 	ctl_datamove((union ctl_io *)ctsio);
10551 	return (CTL_RETVAL_COMPLETE);
10552 }
10553 
10554 int
10555 ctl_mechanism_status(struct ctl_scsiio *ctsio)
10556 {
10557 	struct scsi_mechanism_status_header *hdr;
10558 	struct scsi_mechanism_status *cdb;
10559 	uint32_t alloc_len, data_len;
10560 
10561 	cdb = (struct scsi_mechanism_status *)ctsio->cdb;
10562 	alloc_len = scsi_2btoul(cdb->length);
10563 
10564 	data_len = sizeof(struct scsi_mechanism_status_header);
10565 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10566 	ctsio->kern_sg_entries = 0;
10567 	ctsio->kern_rel_offset = 0;
10568 	ctsio->kern_data_len = min(data_len, alloc_len);
10569 	ctsio->kern_total_len = ctsio->kern_data_len;
10570 
10571 	hdr = (struct scsi_mechanism_status_header *)ctsio->kern_data_ptr;
10572 	hdr->state1 = 0x00;
10573 	hdr->state2 = 0xe0;
10574 	scsi_ulto3b(0, hdr->lba);
10575 	hdr->slots_num = 0;
10576 	scsi_ulto2b(0, hdr->slots_length);
10577 
10578 	ctl_set_success(ctsio);
10579 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10580 	ctsio->be_move_done = ctl_config_move_done;
10581 	ctl_datamove((union ctl_io *)ctsio);
10582 	return (CTL_RETVAL_COMPLETE);
10583 }
10584 
10585 static void
10586 ctl_ultomsf(uint32_t lba, uint8_t *buf)
10587 {
10588 
10589 	lba += 150;
10590 	buf[0] = 0;
10591 	buf[1] = bin2bcd((lba / 75) / 60);
10592 	buf[2] = bin2bcd((lba / 75) % 60);
10593 	buf[3] = bin2bcd(lba % 75);
10594 }
10595 
10596 int
10597 ctl_read_toc(struct ctl_scsiio *ctsio)
10598 {
10599 	struct ctl_lun *lun = CTL_LUN(ctsio);
10600 	struct scsi_read_toc_hdr *hdr;
10601 	struct scsi_read_toc_type01_descr *descr;
10602 	struct scsi_read_toc *cdb;
10603 	uint32_t alloc_len, data_len;
10604 	int format, msf;
10605 
10606 	cdb = (struct scsi_read_toc *)ctsio->cdb;
10607 	msf = (cdb->byte2 & CD_MSF) != 0;
10608 	format = cdb->format;
10609 	alloc_len = scsi_2btoul(cdb->data_len);
10610 
10611 	data_len = sizeof(struct scsi_read_toc_hdr);
10612 	if (format == 0)
10613 		data_len += 2 * sizeof(struct scsi_read_toc_type01_descr);
10614 	else
10615 		data_len += sizeof(struct scsi_read_toc_type01_descr);
10616 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10617 	ctsio->kern_sg_entries = 0;
10618 	ctsio->kern_rel_offset = 0;
10619 	ctsio->kern_data_len = min(data_len, alloc_len);
10620 	ctsio->kern_total_len = ctsio->kern_data_len;
10621 
10622 	hdr = (struct scsi_read_toc_hdr *)ctsio->kern_data_ptr;
10623 	if (format == 0) {
10624 		scsi_ulto2b(0x12, hdr->data_length);
10625 		hdr->first = 1;
10626 		hdr->last = 1;
10627 		descr = (struct scsi_read_toc_type01_descr *)(hdr + 1);
10628 		descr->addr_ctl = 0x14;
10629 		descr->track_number = 1;
10630 		if (msf)
10631 			ctl_ultomsf(0, descr->track_start);
10632 		else
10633 			scsi_ulto4b(0, descr->track_start);
10634 		descr++;
10635 		descr->addr_ctl = 0x14;
10636 		descr->track_number = 0xaa;
10637 		if (msf)
10638 			ctl_ultomsf(lun->be_lun->maxlba+1, descr->track_start);
10639 		else
10640 			scsi_ulto4b(lun->be_lun->maxlba+1, descr->track_start);
10641 	} else {
10642 		scsi_ulto2b(0x0a, hdr->data_length);
10643 		hdr->first = 1;
10644 		hdr->last = 1;
10645 		descr = (struct scsi_read_toc_type01_descr *)(hdr + 1);
10646 		descr->addr_ctl = 0x14;
10647 		descr->track_number = 1;
10648 		if (msf)
10649 			ctl_ultomsf(0, descr->track_start);
10650 		else
10651 			scsi_ulto4b(0, descr->track_start);
10652 	}
10653 
10654 	ctl_set_success(ctsio);
10655 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10656 	ctsio->be_move_done = ctl_config_move_done;
10657 	ctl_datamove((union ctl_io *)ctsio);
10658 	return (CTL_RETVAL_COMPLETE);
10659 }
10660 
10661 /*
10662  * For known CDB types, parse the LBA and length.
10663  */
10664 static int
10665 ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10666 {
10667 
10668 	KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
10669 	    ("%s: unexpected I/O type %x", __func__, io->io_hdr.io_type));
10670 
10671 	switch (io->scsiio.cdb[0]) {
10672 	case COMPARE_AND_WRITE: {
10673 		struct scsi_compare_and_write *cdb;
10674 
10675 		cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10676 
10677 		*lba = scsi_8btou64(cdb->addr);
10678 		*len = cdb->length;
10679 		break;
10680 	}
10681 	case READ_6:
10682 	case WRITE_6: {
10683 		struct scsi_rw_6 *cdb;
10684 
10685 		cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10686 
10687 		*lba = scsi_3btoul(cdb->addr);
10688 		/* only 5 bits are valid in the most significant address byte */
10689 		*lba &= 0x1fffff;
10690 		*len = cdb->length;
10691 		break;
10692 	}
10693 	case READ_10:
10694 	case WRITE_10: {
10695 		struct scsi_rw_10 *cdb;
10696 
10697 		cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10698 
10699 		*lba = scsi_4btoul(cdb->addr);
10700 		*len = scsi_2btoul(cdb->length);
10701 		break;
10702 	}
10703 	case WRITE_VERIFY_10: {
10704 		struct scsi_write_verify_10 *cdb;
10705 
10706 		cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10707 
10708 		*lba = scsi_4btoul(cdb->addr);
10709 		*len = scsi_2btoul(cdb->length);
10710 		break;
10711 	}
10712 	case READ_12:
10713 	case WRITE_12: {
10714 		struct scsi_rw_12 *cdb;
10715 
10716 		cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10717 
10718 		*lba = scsi_4btoul(cdb->addr);
10719 		*len = scsi_4btoul(cdb->length);
10720 		break;
10721 	}
10722 	case WRITE_VERIFY_12: {
10723 		struct scsi_write_verify_12 *cdb;
10724 
10725 		cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10726 
10727 		*lba = scsi_4btoul(cdb->addr);
10728 		*len = scsi_4btoul(cdb->length);
10729 		break;
10730 	}
10731 	case READ_16:
10732 	case WRITE_16: {
10733 		struct scsi_rw_16 *cdb;
10734 
10735 		cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10736 
10737 		*lba = scsi_8btou64(cdb->addr);
10738 		*len = scsi_4btoul(cdb->length);
10739 		break;
10740 	}
10741 	case WRITE_ATOMIC_16: {
10742 		struct scsi_write_atomic_16 *cdb;
10743 
10744 		cdb = (struct scsi_write_atomic_16 *)io->scsiio.cdb;
10745 
10746 		*lba = scsi_8btou64(cdb->addr);
10747 		*len = scsi_2btoul(cdb->length);
10748 		break;
10749 	}
10750 	case WRITE_VERIFY_16: {
10751 		struct scsi_write_verify_16 *cdb;
10752 
10753 		cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10754 
10755 		*lba = scsi_8btou64(cdb->addr);
10756 		*len = scsi_4btoul(cdb->length);
10757 		break;
10758 	}
10759 	case WRITE_SAME_10: {
10760 		struct scsi_write_same_10 *cdb;
10761 
10762 		cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10763 
10764 		*lba = scsi_4btoul(cdb->addr);
10765 		*len = scsi_2btoul(cdb->length);
10766 		break;
10767 	}
10768 	case WRITE_SAME_16: {
10769 		struct scsi_write_same_16 *cdb;
10770 
10771 		cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10772 
10773 		*lba = scsi_8btou64(cdb->addr);
10774 		*len = scsi_4btoul(cdb->length);
10775 		break;
10776 	}
10777 	case VERIFY_10: {
10778 		struct scsi_verify_10 *cdb;
10779 
10780 		cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10781 
10782 		*lba = scsi_4btoul(cdb->addr);
10783 		*len = scsi_2btoul(cdb->length);
10784 		break;
10785 	}
10786 	case VERIFY_12: {
10787 		struct scsi_verify_12 *cdb;
10788 
10789 		cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10790 
10791 		*lba = scsi_4btoul(cdb->addr);
10792 		*len = scsi_4btoul(cdb->length);
10793 		break;
10794 	}
10795 	case VERIFY_16: {
10796 		struct scsi_verify_16 *cdb;
10797 
10798 		cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10799 
10800 		*lba = scsi_8btou64(cdb->addr);
10801 		*len = scsi_4btoul(cdb->length);
10802 		break;
10803 	}
10804 	case UNMAP: {
10805 		*lba = 0;
10806 		*len = UINT64_MAX;
10807 		break;
10808 	}
10809 	case SERVICE_ACTION_IN: {	/* GET LBA STATUS */
10810 		struct scsi_get_lba_status *cdb;
10811 
10812 		cdb = (struct scsi_get_lba_status *)io->scsiio.cdb;
10813 		*lba = scsi_8btou64(cdb->addr);
10814 		*len = UINT32_MAX;
10815 		break;
10816 	}
10817 	default:
10818 		*lba = 0;
10819 		*len = UINT64_MAX;
10820 		return (1);
10821 	}
10822 
10823 	return (0);
10824 }
10825 
10826 static ctl_action
10827 ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2,
10828     bool seq)
10829 {
10830 	uint64_t endlba1, endlba2;
10831 
10832 	endlba1 = lba1 + len1 - (seq ? 0 : 1);
10833 	endlba2 = lba2 + len2 - 1;
10834 
10835 	if ((endlba1 < lba2) || (endlba2 < lba1))
10836 		return (CTL_ACTION_PASS);
10837 	else
10838 		return (CTL_ACTION_BLOCK);
10839 }
10840 
10841 static int
10842 ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
10843 {
10844 	struct ctl_ptr_len_flags *ptrlen;
10845 	struct scsi_unmap_desc *buf, *end, *range;
10846 	uint64_t lba;
10847 	uint32_t len;
10848 
10849 	KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
10850 	    ("%s: unexpected I/O type %x", __func__, io->io_hdr.io_type));
10851 
10852 	/* If not UNMAP -- go other way. */
10853 	if (io->scsiio.cdb[0] != UNMAP)
10854 		return (CTL_ACTION_SKIP);
10855 
10856 	/* If UNMAP without data -- block and wait for data. */
10857 	ptrlen = (struct ctl_ptr_len_flags *)
10858 	    &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10859 	if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
10860 	    ptrlen->ptr == NULL)
10861 		return (CTL_ACTION_BLOCK);
10862 
10863 	/* UNMAP with data -- check for collision. */
10864 	buf = (struct scsi_unmap_desc *)ptrlen->ptr;
10865 	end = buf + ptrlen->len / sizeof(*buf);
10866 	for (range = buf; range < end; range++) {
10867 		lba = scsi_8btou64(range->lba);
10868 		len = scsi_4btoul(range->length);
10869 		if ((lba < lba2 + len2) && (lba + len > lba2))
10870 			return (CTL_ACTION_BLOCK);
10871 	}
10872 	return (CTL_ACTION_PASS);
10873 }
10874 
10875 static ctl_action
10876 ctl_extent_check(union ctl_io *io1, union ctl_io *io2, bool seq)
10877 {
10878 	uint64_t lba1, lba2;
10879 	uint64_t len1, len2;
10880 	int retval;
10881 
10882 	retval = ctl_get_lba_len(io2, &lba2, &len2);
10883 	KASSERT(retval == 0, ("ctl_get_lba_len() error"));
10884 
10885 	retval = ctl_extent_check_unmap(io1, lba2, len2);
10886 	if (retval != CTL_ACTION_SKIP)
10887 		return (retval);
10888 
10889 	retval = ctl_get_lba_len(io1, &lba1, &len1);
10890 	KASSERT(retval == 0, ("ctl_get_lba_len() error"));
10891 
10892 	if (seq && (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE))
10893 		seq = FALSE;
10894 	return (ctl_extent_check_lba(lba1, len1, lba2, len2, seq));
10895 }
10896 
10897 static ctl_action
10898 ctl_seq_check(union ctl_io *io1, union ctl_io *io2)
10899 {
10900 	uint64_t lba1, lba2;
10901 	uint64_t len1, len2;
10902 	int retval;
10903 
10904 	if (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE)
10905 		return (CTL_ACTION_PASS);
10906 	retval = ctl_get_lba_len(io1, &lba1, &len1);
10907 	KASSERT(retval == 0, ("ctl_get_lba_len() error"));
10908 	retval = ctl_get_lba_len(io2, &lba2, &len2);
10909 	KASSERT(retval == 0, ("ctl_get_lba_len() error"));
10910 
10911 	if (lba1 + len1 == lba2)
10912 		return (CTL_ACTION_BLOCK);
10913 	return (CTL_ACTION_PASS);
10914 }
10915 
10916 static ctl_action
10917 ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
10918     const uint8_t *serialize_row, union ctl_io *ooa_io)
10919 {
10920 
10921 	/*
10922 	 * The initiator attempted multiple untagged commands at the same
10923 	 * time.  Can't do that.
10924 	 */
10925 	if (__predict_false(pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10926 	 && __predict_false(ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10927 	 && ((pending_io->io_hdr.nexus.targ_port ==
10928 	      ooa_io->io_hdr.nexus.targ_port)
10929 	  && (pending_io->io_hdr.nexus.initid ==
10930 	      ooa_io->io_hdr.nexus.initid))
10931 	 && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
10932 	      CTL_FLAG_STATUS_SENT)) == 0))
10933 		return (CTL_ACTION_OVERLAP);
10934 
10935 	/*
10936 	 * The initiator attempted to send multiple tagged commands with
10937 	 * the same ID.  (It's fine if different initiators have the same
10938 	 * tag ID.)
10939 	 *
10940 	 * Even if all of those conditions are true, we don't kill the I/O
10941 	 * if the command ahead of us has been aborted.  We won't end up
10942 	 * sending it to the FETD, and it's perfectly legal to resend a
10943 	 * command with the same tag number as long as the previous
10944 	 * instance of this tag number has been aborted somehow.
10945 	 */
10946 	if (__predict_true(pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10947 	 && __predict_true(ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10948 	 && __predict_false(pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
10949 	 && ((pending_io->io_hdr.nexus.targ_port ==
10950 	      ooa_io->io_hdr.nexus.targ_port)
10951 	  && (pending_io->io_hdr.nexus.initid ==
10952 	      ooa_io->io_hdr.nexus.initid))
10953 	 && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
10954 	      CTL_FLAG_STATUS_SENT)) == 0))
10955 		return (CTL_ACTION_OVERLAP_TAG);
10956 
10957 	/*
10958 	 * If we get a head of queue tag, SAM-3 says that we should
10959 	 * immediately execute it.
10960 	 *
10961 	 * What happens if this command would normally block for some other
10962 	 * reason?  e.g. a request sense with a head of queue tag
10963 	 * immediately after a write.  Normally that would block, but this
10964 	 * will result in its getting executed immediately...
10965 	 *
10966 	 * We currently return "pass" instead of "skip", so we'll end up
10967 	 * going through the rest of the queue to check for overlapped tags.
10968 	 *
10969 	 * XXX KDM check for other types of blockage first??
10970 	 */
10971 	if (__predict_false(pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE))
10972 		return (CTL_ACTION_PASS);
10973 
10974 	/*
10975 	 * Simple tags get blocked until all head of queue and ordered tags
10976 	 * ahead of them have completed.  I'm lumping untagged commands in
10977 	 * with simple tags here.  XXX KDM is that the right thing to do?
10978 	 */
10979 	if (__predict_false(ooa_io->scsiio.tag_type == CTL_TAG_ORDERED) ||
10980 	    __predict_false(ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE))
10981 		return (CTL_ACTION_BLOCK);
10982 
10983 	/* Unsupported command in OOA queue. */
10984 	if (__predict_false(ooa_io->scsiio.seridx == CTL_SERIDX_INVLD))
10985 		return (CTL_ACTION_PASS);
10986 
10987 	switch (serialize_row[ooa_io->scsiio.seridx]) {
10988 	case CTL_SER_SEQ:
10989 		if (lun->be_lun->serseq != CTL_LUN_SERSEQ_OFF)
10990 			return (ctl_seq_check(ooa_io, pending_io));
10991 		/* FALLTHROUGH */
10992 	case CTL_SER_PASS:
10993 		return (CTL_ACTION_PASS);
10994 	case CTL_SER_EXTENTOPT:
10995 		if ((lun->MODE_CTRL.queue_flags & SCP_QUEUE_ALG_MASK) ==
10996 		    SCP_QUEUE_ALG_UNRESTRICTED)
10997 			return (CTL_ACTION_PASS);
10998 		/* FALLTHROUGH */
10999 	case CTL_SER_EXTENT:
11000 		return (ctl_extent_check(ooa_io, pending_io,
11001 		    (lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
11002 	case CTL_SER_BLOCKOPT:
11003 		if ((lun->MODE_CTRL.queue_flags & SCP_QUEUE_ALG_MASK) ==
11004 		    SCP_QUEUE_ALG_UNRESTRICTED)
11005 			return (CTL_ACTION_PASS);
11006 		/* FALLTHROUGH */
11007 	case CTL_SER_BLOCK:
11008 		return (CTL_ACTION_BLOCK);
11009 	default:
11010 		__assert_unreachable();
11011 	}
11012 }
11013 
11014 /*
11015  * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
11016  * Assumptions:
11017  * - pending_io is generally either incoming, or on the blocked queue
11018  * - starting I/O is the I/O we want to start the check with.
11019  */
11020 static ctl_action
11021 ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
11022 	      union ctl_io **starting_io)
11023 {
11024 	union ctl_io *ooa_io = *starting_io;
11025 	const uint8_t *serialize_row;
11026 	ctl_action action;
11027 
11028 	mtx_assert(&lun->lun_lock, MA_OWNED);
11029 
11030 	/*
11031 	 * Aborted commands are not going to be executed and may even
11032 	 * not report completion, so we don't care about their order.
11033 	 * Let them complete ASAP to clean the OOA queue.
11034 	 */
11035 	if (__predict_false(pending_io->io_hdr.flags & CTL_FLAG_ABORT))
11036 		return (CTL_ACTION_SKIP);
11037 
11038 	/*
11039 	 * Ordered tags have to block until all items ahead of them have
11040 	 * completed.  If we get called with an ordered tag, we always
11041 	 * block, if something else is ahead of us in the queue.
11042 	 */
11043 	if ((pending_io->scsiio.tag_type == CTL_TAG_ORDERED) &&
11044 	    (ooa_io != NULL))
11045 		return (CTL_ACTION_BLOCK);
11046 
11047 	serialize_row = ctl_serialize_table[pending_io->scsiio.seridx];
11048 
11049 	/*
11050 	 * Run back along the OOA queue, starting with the current
11051 	 * blocked I/O and going through every I/O before it on the
11052 	 * queue.  If starting_io is NULL, we'll just end up returning
11053 	 * CTL_ACTION_PASS.
11054 	 */
11055 	for (; ooa_io != NULL;
11056 	     ooa_io = (union ctl_io *)LIST_NEXT(&ooa_io->io_hdr, ooa_links)) {
11057 		action = ctl_check_for_blockage(lun, pending_io, serialize_row,
11058 		    ooa_io);
11059 		if (action != CTL_ACTION_PASS) {
11060 			*starting_io = ooa_io;
11061 			return (action);
11062 		}
11063 	}
11064 
11065 	*starting_io = NULL;
11066 	return (CTL_ACTION_PASS);
11067 }
11068 
11069 /*
11070  * Try to unblock the specified I/O.
11071  *
11072  * skip parameter allows explicitly skip present blocker of the I/O,
11073  * starting from the previous one on OOA queue.  It can be used when
11074  * we know for sure that the blocker I/O does no longer count.
11075  */
11076 static void
11077 ctl_try_unblock_io(struct ctl_lun *lun, union ctl_io *io, bool skip)
11078 {
11079 	struct ctl_softc *softc = lun->ctl_softc;
11080 	union ctl_io *bio, *obio;
11081 	const struct ctl_cmd_entry *entry;
11082 	union ctl_ha_msg msg_info;
11083 	ctl_action action;
11084 
11085 	mtx_assert(&lun->lun_lock, MA_OWNED);
11086 
11087 	if (io->io_hdr.blocker == NULL)
11088 		return;
11089 
11090 	obio = bio = io->io_hdr.blocker;
11091 	if (skip)
11092 		bio = (union ctl_io *)LIST_NEXT(&bio->io_hdr, ooa_links);
11093 	action = ctl_check_ooa(lun, io, &bio);
11094 	if (action == CTL_ACTION_BLOCK) {
11095 		/* Still blocked, but may be by different I/O now. */
11096 		if (bio != obio) {
11097 			TAILQ_REMOVE(&obio->io_hdr.blocked_queue,
11098 			    &io->io_hdr, blocked_links);
11099 			TAILQ_INSERT_TAIL(&bio->io_hdr.blocked_queue,
11100 			    &io->io_hdr, blocked_links);
11101 			io->io_hdr.blocker = bio;
11102 		}
11103 		return;
11104 	}
11105 
11106 	/* No longer blocked, one way or another. */
11107 	TAILQ_REMOVE(&obio->io_hdr.blocked_queue, &io->io_hdr, blocked_links);
11108 	io->io_hdr.blocker = NULL;
11109 
11110 	switch (action) {
11111 	case CTL_ACTION_PASS:
11112 	case CTL_ACTION_SKIP:
11113 
11114 		/* Serializing commands from the other SC retire there. */
11115 		if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) &&
11116 		    (softc->ha_mode != CTL_HA_MODE_XFER)) {
11117 			io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11118 			msg_info.hdr.original_sc = io->io_hdr.remote_io;
11119 			msg_info.hdr.serializing_sc = io;
11120 			msg_info.hdr.msg_type = CTL_MSG_R2R;
11121 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11122 			    sizeof(msg_info.hdr), M_NOWAIT);
11123 			break;
11124 		}
11125 
11126 		/*
11127 		 * Check this I/O for LUN state changes that may have happened
11128 		 * while this command was blocked. The LUN state may have been
11129 		 * changed by a command ahead of us in the queue.
11130 		 */
11131 		entry = ctl_get_cmd_entry(&io->scsiio, NULL);
11132 		if (ctl_scsiio_lun_check(lun, entry, &io->scsiio) != 0) {
11133 			ctl_done(io);
11134 			break;
11135 		}
11136 
11137 		io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11138 		ctl_enqueue_rtr(io);
11139 		break;
11140 	default:
11141 		__assert_unreachable();
11142 	case CTL_ACTION_OVERLAP:
11143 		ctl_set_overlapped_cmd(&io->scsiio);
11144 		goto error;
11145 	case CTL_ACTION_OVERLAP_TAG:
11146 		ctl_set_overlapped_tag(&io->scsiio,
11147 		    io->scsiio.tag_num & 0xff);
11148 error:
11149 		/* Serializing commands from the other SC are done here. */
11150 		if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) &&
11151 		    (softc->ha_mode != CTL_HA_MODE_XFER)) {
11152 			ctl_try_unblock_others(lun, io, TRUE);
11153 			LIST_REMOVE(&io->io_hdr, ooa_links);
11154 
11155 			ctl_copy_sense_data_back(io, &msg_info);
11156 			msg_info.hdr.original_sc = io->io_hdr.remote_io;
11157 			msg_info.hdr.serializing_sc = NULL;
11158 			msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
11159 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11160 			    sizeof(msg_info.scsi), M_WAITOK);
11161 			ctl_free_io(io);
11162 			break;
11163 		}
11164 
11165 		ctl_done(io);
11166 		break;
11167 	}
11168 }
11169 
11170 /*
11171  * Try to unblock I/Os blocked by the specified I/O.
11172  *
11173  * skip parameter allows explicitly skip the specified I/O as blocker,
11174  * starting from the previous one on the OOA queue.  It can be used when
11175  * we know for sure that the specified I/O does no longer count (done).
11176  * It has to be still on OOA queue though so that we know where to start.
11177  */
11178 static void
11179 ctl_try_unblock_others(struct ctl_lun *lun, union ctl_io *bio, bool skip)
11180 {
11181 	union ctl_io *io, *next_io;
11182 
11183 	mtx_assert(&lun->lun_lock, MA_OWNED);
11184 
11185 	for (io = (union ctl_io *)TAILQ_FIRST(&bio->io_hdr.blocked_queue);
11186 	     io != NULL; io = next_io) {
11187 		next_io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr, blocked_links);
11188 
11189 		KASSERT(io->io_hdr.blocker != NULL,
11190 		    ("I/O %p on blocked list without blocker", io));
11191 		ctl_try_unblock_io(lun, io, skip);
11192 	}
11193 	KASSERT(!skip || TAILQ_EMPTY(&bio->io_hdr.blocked_queue),
11194 	    ("blocked_queue is not empty after skipping %p", bio));
11195 }
11196 
11197 /*
11198  * This routine (with one exception) checks LUN flags that can be set by
11199  * commands ahead of us in the OOA queue.  These flags have to be checked
11200  * when a command initially comes in, and when we pull a command off the
11201  * blocked queue and are preparing to execute it.  The reason we have to
11202  * check these flags for commands on the blocked queue is that the LUN
11203  * state may have been changed by a command ahead of us while we're on the
11204  * blocked queue.
11205  *
11206  * Ordering is somewhat important with these checks, so please pay
11207  * careful attention to the placement of any new checks.
11208  */
11209 static int
11210 ctl_scsiio_lun_check(struct ctl_lun *lun,
11211     const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11212 {
11213 	struct ctl_softc *softc = lun->ctl_softc;
11214 	int retval;
11215 	uint32_t residx;
11216 
11217 	retval = 0;
11218 
11219 	mtx_assert(&lun->lun_lock, MA_OWNED);
11220 
11221 	/*
11222 	 * If this shelf is a secondary shelf controller, we may have to
11223 	 * reject some commands disallowed by HA mode and link state.
11224 	 */
11225 	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11226 		if (softc->ha_link == CTL_HA_LINK_OFFLINE &&
11227 		    (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11228 			ctl_set_lun_unavail(ctsio);
11229 			retval = 1;
11230 			goto bailout;
11231 		}
11232 		if ((lun->flags & CTL_LUN_PEER_SC_PRIMARY) == 0 &&
11233 		    (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11234 			ctl_set_lun_transit(ctsio);
11235 			retval = 1;
11236 			goto bailout;
11237 		}
11238 		if (softc->ha_mode == CTL_HA_MODE_ACT_STBY &&
11239 		    (entry->flags & CTL_CMD_FLAG_OK_ON_STANDBY) == 0) {
11240 			ctl_set_lun_standby(ctsio);
11241 			retval = 1;
11242 			goto bailout;
11243 		}
11244 
11245 		/* The rest of checks are only done on executing side */
11246 		if (softc->ha_mode == CTL_HA_MODE_XFER)
11247 			goto bailout;
11248 	}
11249 
11250 	if (entry->pattern & CTL_LUN_PAT_WRITE) {
11251 		if (lun->be_lun->flags & CTL_LUN_FLAG_READONLY) {
11252 			ctl_set_hw_write_protected(ctsio);
11253 			retval = 1;
11254 			goto bailout;
11255 		}
11256 		if ((lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0) {
11257 			ctl_set_sense(ctsio, /*current_error*/ 1,
11258 			    /*sense_key*/ SSD_KEY_DATA_PROTECT,
11259 			    /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
11260 			retval = 1;
11261 			goto bailout;
11262 		}
11263 	}
11264 
11265 	/*
11266 	 * Check for a reservation conflict.  If this command isn't allowed
11267 	 * even on reserved LUNs, and if this initiator isn't the one who
11268 	 * reserved us, reject the command with a reservation conflict.
11269 	 */
11270 	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11271 	if ((lun->flags & CTL_LUN_RESERVED)
11272 	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11273 		if (lun->res_idx != residx) {
11274 			ctl_set_reservation_conflict(ctsio);
11275 			retval = 1;
11276 			goto bailout;
11277 		}
11278 	}
11279 
11280 	if ((lun->flags & CTL_LUN_PR_RESERVED) == 0 ||
11281 	    (entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV)) {
11282 		/* No reservation or command is allowed. */;
11283 	} else if ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_WRESV) &&
11284 	    (lun->pr_res_type == SPR_TYPE_WR_EX ||
11285 	     lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
11286 	     lun->pr_res_type == SPR_TYPE_WR_EX_AR)) {
11287 		/* The command is allowed for Write Exclusive resv. */;
11288 	} else {
11289 		/*
11290 		 * if we aren't registered or it's a res holder type
11291 		 * reservation and this isn't the res holder then set a
11292 		 * conflict.
11293 		 */
11294 		if (ctl_get_prkey(lun, residx) == 0 ||
11295 		    (residx != lun->pr_res_idx && lun->pr_res_type < 4)) {
11296 			ctl_set_reservation_conflict(ctsio);
11297 			retval = 1;
11298 			goto bailout;
11299 		}
11300 	}
11301 
11302 	if ((entry->flags & CTL_CMD_FLAG_OK_ON_NO_MEDIA) == 0) {
11303 		if (lun->flags & CTL_LUN_EJECTED)
11304 			ctl_set_lun_ejected(ctsio);
11305 		else if (lun->flags & CTL_LUN_NO_MEDIA) {
11306 			if (lun->flags & CTL_LUN_REMOVABLE)
11307 				ctl_set_lun_no_media(ctsio);
11308 			else
11309 				ctl_set_lun_int_reqd(ctsio);
11310 		} else if (lun->flags & CTL_LUN_STOPPED)
11311 			ctl_set_lun_stopped(ctsio);
11312 		else
11313 			goto bailout;
11314 		retval = 1;
11315 		goto bailout;
11316 	}
11317 
11318 bailout:
11319 	return (retval);
11320 }
11321 
11322 static void
11323 ctl_failover_io(union ctl_io *io, int have_lock)
11324 {
11325 	ctl_set_busy(&io->scsiio);
11326 	ctl_done(io);
11327 }
11328 
11329 static void
11330 ctl_failover_lun(union ctl_io *rio)
11331 {
11332 	struct ctl_softc *softc = CTL_SOFTC(rio);
11333 	struct ctl_lun *lun;
11334 	struct ctl_io_hdr *io, *next_io;
11335 	uint32_t targ_lun;
11336 
11337 	targ_lun = rio->io_hdr.nexus.targ_mapped_lun;
11338 	CTL_DEBUG_PRINT(("FAILOVER for lun %u\n", targ_lun));
11339 
11340 	/* Find and lock the LUN. */
11341 	mtx_lock(&softc->ctl_lock);
11342 	if (targ_lun > ctl_max_luns ||
11343 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11344 		mtx_unlock(&softc->ctl_lock);
11345 		return;
11346 	}
11347 	mtx_lock(&lun->lun_lock);
11348 	mtx_unlock(&softc->ctl_lock);
11349 	if (lun->flags & CTL_LUN_DISABLED) {
11350 		mtx_unlock(&lun->lun_lock);
11351 		return;
11352 	}
11353 
11354 	if (softc->ha_mode == CTL_HA_MODE_XFER) {
11355 		LIST_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11356 			/* We are master */
11357 			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11358 				if (io->flags & CTL_FLAG_IO_ACTIVE) {
11359 					io->flags |= CTL_FLAG_ABORT |
11360 					    CTL_FLAG_FAILOVER;
11361 					ctl_try_unblock_io(lun,
11362 					    (union ctl_io *)io, FALSE);
11363 				} else { /* This can be only due to DATAMOVE */
11364 					io->msg_type = CTL_MSG_DATAMOVE_DONE;
11365 					io->flags &= ~CTL_FLAG_DMA_INPROG;
11366 					io->flags |= CTL_FLAG_IO_ACTIVE;
11367 					io->port_status = 31340;
11368 					ctl_enqueue_isc((union ctl_io *)io);
11369 				}
11370 			} else
11371 			/* We are slave */
11372 			if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11373 				io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11374 				if (io->flags & CTL_FLAG_IO_ACTIVE) {
11375 					io->flags |= CTL_FLAG_FAILOVER;
11376 				} else {
11377 					ctl_set_busy(&((union ctl_io *)io)->
11378 					    scsiio);
11379 					ctl_done((union ctl_io *)io);
11380 				}
11381 			}
11382 		}
11383 	} else { /* SERIALIZE modes */
11384 		LIST_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11385 			/* We are master */
11386 			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11387 				if (io->blocker != NULL) {
11388 					TAILQ_REMOVE(&io->blocker->io_hdr.blocked_queue,
11389 					    io, blocked_links);
11390 					io->blocker = NULL;
11391 				}
11392 				ctl_try_unblock_others(lun, (union ctl_io *)io,
11393 				    TRUE);
11394 				LIST_REMOVE(io, ooa_links);
11395 				ctl_free_io((union ctl_io *)io);
11396 			} else
11397 			/* We are slave */
11398 			if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11399 				io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11400 				if (!(io->flags & CTL_FLAG_IO_ACTIVE)) {
11401 					ctl_set_busy(&((union ctl_io *)io)->
11402 					    scsiio);
11403 					ctl_done((union ctl_io *)io);
11404 				}
11405 			}
11406 		}
11407 	}
11408 	mtx_unlock(&lun->lun_lock);
11409 }
11410 
11411 static void
11412 ctl_scsiio_precheck(struct ctl_scsiio *ctsio)
11413 {
11414 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
11415 	struct ctl_lun *lun;
11416 	const struct ctl_cmd_entry *entry;
11417 	union ctl_io *bio;
11418 	uint32_t initidx, targ_lun;
11419 
11420 	lun = NULL;
11421 	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11422 	if (targ_lun < ctl_max_luns)
11423 		lun = softc->ctl_luns[targ_lun];
11424 	if (lun) {
11425 		/*
11426 		 * If the LUN is invalid, pretend that it doesn't exist.
11427 		 * It will go away as soon as all pending I/O has been
11428 		 * completed.
11429 		 */
11430 		mtx_lock(&lun->lun_lock);
11431 		if (lun->flags & CTL_LUN_DISABLED) {
11432 			mtx_unlock(&lun->lun_lock);
11433 			lun = NULL;
11434 		}
11435 	}
11436 	CTL_LUN(ctsio) = lun;
11437 	if (lun) {
11438 		CTL_BACKEND_LUN(ctsio) = lun->be_lun;
11439 
11440 		/*
11441 		 * Every I/O goes into the OOA queue for a particular LUN,
11442 		 * and stays there until completion.
11443 		 */
11444 #ifdef CTL_TIME_IO
11445 		if (LIST_EMPTY(&lun->ooa_queue))
11446 			lun->idle_time += getsbinuptime() - lun->last_busy;
11447 #endif
11448 		LIST_INSERT_HEAD(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
11449 	}
11450 
11451 	/* Get command entry and return error if it is unsuppotyed. */
11452 	entry = ctl_validate_command(ctsio);
11453 	if (entry == NULL) {
11454 		if (lun)
11455 			mtx_unlock(&lun->lun_lock);
11456 		return;
11457 	}
11458 
11459 	ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11460 	ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11461 
11462 	/*
11463 	 * Check to see whether we can send this command to LUNs that don't
11464 	 * exist.  This should pretty much only be the case for inquiry
11465 	 * and request sense.  Further checks, below, really require having
11466 	 * a LUN, so we can't really check the command anymore.  Just put
11467 	 * it on the rtr queue.
11468 	 */
11469 	if (lun == NULL) {
11470 		if (entry->flags & CTL_CMD_FLAG_OK_ON_NO_LUN) {
11471 			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11472 			ctl_enqueue_rtr((union ctl_io *)ctsio);
11473 			return;
11474 		}
11475 
11476 		ctl_set_unsupported_lun(ctsio);
11477 		ctl_done((union ctl_io *)ctsio);
11478 		CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11479 		return;
11480 	} else {
11481 		/*
11482 		 * Make sure we support this particular command on this LUN.
11483 		 * e.g., we don't support writes to the control LUN.
11484 		 */
11485 		if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11486 			mtx_unlock(&lun->lun_lock);
11487 			ctl_set_invalid_opcode(ctsio);
11488 			ctl_done((union ctl_io *)ctsio);
11489 			return;
11490 		}
11491 	}
11492 
11493 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11494 
11495 	/*
11496 	 * If we've got a request sense, it'll clear the contingent
11497 	 * allegiance condition.  Otherwise, if we have a CA condition for
11498 	 * this initiator, clear it, because it sent down a command other
11499 	 * than request sense.
11500 	 */
11501 	if (ctsio->cdb[0] != REQUEST_SENSE) {
11502 		struct scsi_sense_data *ps;
11503 
11504 		ps = lun->pending_sense[initidx / CTL_MAX_INIT_PER_PORT];
11505 		if (ps != NULL)
11506 			ps[initidx % CTL_MAX_INIT_PER_PORT].error_code = 0;
11507 	}
11508 
11509 	/*
11510 	 * If the command has this flag set, it handles its own unit
11511 	 * attention reporting, we shouldn't do anything.  Otherwise we
11512 	 * check for any pending unit attentions, and send them back to the
11513 	 * initiator.  We only do this when a command initially comes in,
11514 	 * not when we pull it off the blocked queue.
11515 	 *
11516 	 * According to SAM-3, section 5.3.2, the order that things get
11517 	 * presented back to the host is basically unit attentions caused
11518 	 * by some sort of reset event, busy status, reservation conflicts
11519 	 * or task set full, and finally any other status.
11520 	 *
11521 	 * One issue here is that some of the unit attentions we report
11522 	 * don't fall into the "reset" category (e.g. "reported luns data
11523 	 * has changed").  So reporting it here, before the reservation
11524 	 * check, may be technically wrong.  I guess the only thing to do
11525 	 * would be to check for and report the reset events here, and then
11526 	 * check for the other unit attention types after we check for a
11527 	 * reservation conflict.
11528 	 *
11529 	 * XXX KDM need to fix this
11530 	 */
11531 	if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11532 		ctl_ua_type ua_type;
11533 		u_int sense_len = 0;
11534 
11535 		ua_type = ctl_build_ua(lun, initidx, &ctsio->sense_data,
11536 		    &sense_len, SSD_TYPE_NONE);
11537 		if (ua_type != CTL_UA_NONE) {
11538 			mtx_unlock(&lun->lun_lock);
11539 			ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11540 			ctsio->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
11541 			ctsio->sense_len = sense_len;
11542 			ctl_done((union ctl_io *)ctsio);
11543 			return;
11544 		}
11545 	}
11546 
11547 	if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
11548 		mtx_unlock(&lun->lun_lock);
11549 		ctl_done((union ctl_io *)ctsio);
11550 		return;
11551 	}
11552 
11553 	/*
11554 	 * XXX CHD this is where we want to send IO to other side if
11555 	 * this LUN is secondary on this SC. We will need to make a copy
11556 	 * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11557 	 * the copy we send as FROM_OTHER.
11558 	 * We also need to stuff the address of the original IO so we can
11559 	 * find it easily. Something similar will need be done on the other
11560 	 * side so when we are done we can find the copy.
11561 	 */
11562 	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
11563 	    (lun->flags & CTL_LUN_PEER_SC_PRIMARY) != 0 &&
11564 	    (entry->flags & CTL_CMD_FLAG_RUN_HERE) == 0) {
11565 		union ctl_ha_msg msg_info;
11566 		int isc_retval;
11567 
11568 		ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11569 		ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11570 		mtx_unlock(&lun->lun_lock);
11571 
11572 		msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11573 		msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11574 		msg_info.hdr.serializing_sc = NULL;
11575 		msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11576 		msg_info.scsi.tag_num = ctsio->tag_num;
11577 		msg_info.scsi.tag_type = ctsio->tag_type;
11578 		memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11579 		msg_info.scsi.cdb_len = ctsio->cdb_len;
11580 		msg_info.scsi.priority = ctsio->priority;
11581 
11582 		if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11583 		    sizeof(msg_info.scsi) - sizeof(msg_info.scsi.sense_data),
11584 		    M_WAITOK)) > CTL_HA_STATUS_SUCCESS) {
11585 			ctl_set_busy(ctsio);
11586 			ctl_done((union ctl_io *)ctsio);
11587 			return;
11588 		}
11589 		return;
11590 	}
11591 
11592 	bio = (union ctl_io *)LIST_NEXT(&ctsio->io_hdr, ooa_links);
11593 	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio, &bio)) {
11594 	case CTL_ACTION_PASS:
11595 	case CTL_ACTION_SKIP:
11596 		ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11597 		mtx_unlock(&lun->lun_lock);
11598 		ctl_enqueue_rtr((union ctl_io *)ctsio);
11599 		break;
11600 	case CTL_ACTION_BLOCK:
11601 		ctsio->io_hdr.blocker = bio;
11602 		TAILQ_INSERT_TAIL(&bio->io_hdr.blocked_queue, &ctsio->io_hdr,
11603 				  blocked_links);
11604 		mtx_unlock(&lun->lun_lock);
11605 		break;
11606 	case CTL_ACTION_OVERLAP:
11607 		mtx_unlock(&lun->lun_lock);
11608 		ctl_set_overlapped_cmd(ctsio);
11609 		ctl_done((union ctl_io *)ctsio);
11610 		break;
11611 	case CTL_ACTION_OVERLAP_TAG:
11612 		mtx_unlock(&lun->lun_lock);
11613 		ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11614 		ctl_done((union ctl_io *)ctsio);
11615 		break;
11616 	default:
11617 		__assert_unreachable();
11618 	}
11619 }
11620 
11621 const struct ctl_cmd_entry *
11622 ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11623 {
11624 	const struct ctl_cmd_entry *entry;
11625 	int service_action;
11626 
11627 	entry = &ctl_cmd_table[ctsio->cdb[0]];
11628 	if (sa)
11629 		*sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11630 	if (entry->flags & CTL_CMD_FLAG_SA5) {
11631 		service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11632 		entry = &((const struct ctl_cmd_entry *)
11633 		    entry->execute)[service_action];
11634 	}
11635 	return (entry);
11636 }
11637 
11638 const struct ctl_cmd_entry *
11639 ctl_validate_command(struct ctl_scsiio *ctsio)
11640 {
11641 	const struct ctl_cmd_entry *entry;
11642 	int i, sa;
11643 	uint8_t diff;
11644 
11645 	entry = ctl_get_cmd_entry(ctsio, &sa);
11646 	ctsio->seridx = entry->seridx;
11647 	if (entry->execute == NULL) {
11648 		if (sa)
11649 			ctl_set_invalid_field(ctsio,
11650 					      /*sks_valid*/ 1,
11651 					      /*command*/ 1,
11652 					      /*field*/ 1,
11653 					      /*bit_valid*/ 1,
11654 					      /*bit*/ 4);
11655 		else
11656 			ctl_set_invalid_opcode(ctsio);
11657 		ctl_done((union ctl_io *)ctsio);
11658 		return (NULL);
11659 	}
11660 	KASSERT(entry->length > 0,
11661 	    ("Not defined length for command 0x%02x/0x%02x",
11662 	     ctsio->cdb[0], ctsio->cdb[1]));
11663 	for (i = 1; i < entry->length; i++) {
11664 		diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11665 		if (diff == 0)
11666 			continue;
11667 		ctl_set_invalid_field(ctsio,
11668 				      /*sks_valid*/ 1,
11669 				      /*command*/ 1,
11670 				      /*field*/ i,
11671 				      /*bit_valid*/ 1,
11672 				      /*bit*/ fls(diff) - 1);
11673 		ctl_done((union ctl_io *)ctsio);
11674 		return (NULL);
11675 	}
11676 	return (entry);
11677 }
11678 
11679 static int
11680 ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11681 {
11682 
11683 	switch (lun_type) {
11684 	case T_DIRECT:
11685 		if ((entry->flags & CTL_CMD_FLAG_OK_ON_DIRECT) == 0)
11686 			return (0);
11687 		break;
11688 	case T_PROCESSOR:
11689 		if ((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0)
11690 			return (0);
11691 		break;
11692 	case T_CDROM:
11693 		if ((entry->flags & CTL_CMD_FLAG_OK_ON_CDROM) == 0)
11694 			return (0);
11695 		break;
11696 	default:
11697 		return (0);
11698 	}
11699 	return (1);
11700 }
11701 
11702 static int
11703 ctl_scsiio(struct ctl_scsiio *ctsio)
11704 {
11705 	int retval;
11706 	const struct ctl_cmd_entry *entry;
11707 
11708 	retval = CTL_RETVAL_COMPLETE;
11709 
11710 	CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11711 
11712 	entry = ctl_get_cmd_entry(ctsio, NULL);
11713 
11714 	/*
11715 	 * If this I/O has been aborted, just send it straight to
11716 	 * ctl_done() without executing it.
11717 	 */
11718 	if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11719 		ctl_done((union ctl_io *)ctsio);
11720 		goto bailout;
11721 	}
11722 
11723 	/*
11724 	 * All the checks should have been handled by ctl_scsiio_precheck().
11725 	 * We should be clear now to just execute the I/O.
11726 	 */
11727 	retval = entry->execute(ctsio);
11728 
11729 bailout:
11730 	return (retval);
11731 }
11732 
11733 static int
11734 ctl_target_reset(union ctl_io *io)
11735 {
11736 	struct ctl_softc *softc = CTL_SOFTC(io);
11737 	struct ctl_port *port = CTL_PORT(io);
11738 	struct ctl_lun *lun;
11739 	uint32_t initidx;
11740 	ctl_ua_type ua_type;
11741 
11742 	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11743 		union ctl_ha_msg msg_info;
11744 
11745 		msg_info.hdr.nexus = io->io_hdr.nexus;
11746 		msg_info.task.task_action = io->taskio.task_action;
11747 		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11748 		msg_info.hdr.original_sc = NULL;
11749 		msg_info.hdr.serializing_sc = NULL;
11750 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11751 		    sizeof(msg_info.task), M_WAITOK);
11752 	}
11753 
11754 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
11755 	if (io->taskio.task_action == CTL_TASK_TARGET_RESET)
11756 		ua_type = CTL_UA_TARG_RESET;
11757 	else
11758 		ua_type = CTL_UA_BUS_RESET;
11759 	mtx_lock(&softc->ctl_lock);
11760 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
11761 		if (port != NULL &&
11762 		    ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
11763 			continue;
11764 		ctl_do_lun_reset(lun, initidx, ua_type);
11765 	}
11766 	mtx_unlock(&softc->ctl_lock);
11767 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11768 	return (0);
11769 }
11770 
11771 /*
11772  * The LUN should always be set.  The I/O is optional, and is used to
11773  * distinguish between I/Os sent by this initiator, and by other
11774  * initiators.  We set unit attention for initiators other than this one.
11775  * SAM-3 is vague on this point.  It does say that a unit attention should
11776  * be established for other initiators when a LUN is reset (see section
11777  * 5.7.3), but it doesn't specifically say that the unit attention should
11778  * be established for this particular initiator when a LUN is reset.  Here
11779  * is the relevant text, from SAM-3 rev 8:
11780  *
11781  * 5.7.2 When a SCSI initiator port aborts its own tasks
11782  *
11783  * When a SCSI initiator port causes its own task(s) to be aborted, no
11784  * notification that the task(s) have been aborted shall be returned to
11785  * the SCSI initiator port other than the completion response for the
11786  * command or task management function action that caused the task(s) to
11787  * be aborted and notification(s) associated with related effects of the
11788  * action (e.g., a reset unit attention condition).
11789  *
11790  * XXX KDM for now, we're setting unit attention for all initiators.
11791  */
11792 static void
11793 ctl_do_lun_reset(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua_type)
11794 {
11795 	struct ctl_io_hdr *xioh;
11796 	int i;
11797 
11798 	mtx_lock(&lun->lun_lock);
11799 	/* Abort tasks. */
11800 	LIST_FOREACH(xioh, &lun->ooa_queue, ooa_links) {
11801 		xioh->flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
11802 		ctl_try_unblock_io(lun, (union ctl_io *)xioh, FALSE);
11803 	}
11804 	/* Clear CA. */
11805 	for (i = 0; i < ctl_max_ports; i++) {
11806 		free(lun->pending_sense[i], M_CTL);
11807 		lun->pending_sense[i] = NULL;
11808 	}
11809 	/* Clear reservation. */
11810 	lun->flags &= ~CTL_LUN_RESERVED;
11811 	/* Clear prevent media removal. */
11812 	if (lun->prevent) {
11813 		for (i = 0; i < CTL_MAX_INITIATORS; i++)
11814 			ctl_clear_mask(lun->prevent, i);
11815 		lun->prevent_count = 0;
11816 	}
11817 	/* Clear TPC status */
11818 	ctl_tpc_lun_clear(lun, -1);
11819 	/* Establish UA. */
11820 #if 0
11821 	ctl_est_ua_all(lun, initidx, ua_type);
11822 #else
11823 	ctl_est_ua_all(lun, -1, ua_type);
11824 #endif
11825 	mtx_unlock(&lun->lun_lock);
11826 }
11827 
11828 static int
11829 ctl_lun_reset(union ctl_io *io)
11830 {
11831 	struct ctl_softc *softc = CTL_SOFTC(io);
11832 	struct ctl_lun *lun;
11833 	uint32_t targ_lun, initidx;
11834 
11835 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11836 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
11837 	mtx_lock(&softc->ctl_lock);
11838 	if (targ_lun >= ctl_max_luns ||
11839 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11840 		mtx_unlock(&softc->ctl_lock);
11841 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11842 		return (1);
11843 	}
11844 	ctl_do_lun_reset(lun, initidx, CTL_UA_LUN_RESET);
11845 	mtx_unlock(&softc->ctl_lock);
11846 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11847 
11848 	if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0) {
11849 		union ctl_ha_msg msg_info;
11850 
11851 		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11852 		msg_info.hdr.nexus = io->io_hdr.nexus;
11853 		msg_info.task.task_action = CTL_TASK_LUN_RESET;
11854 		msg_info.hdr.original_sc = NULL;
11855 		msg_info.hdr.serializing_sc = NULL;
11856 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11857 		    sizeof(msg_info.task), M_WAITOK);
11858 	}
11859 	return (0);
11860 }
11861 
11862 static void
11863 ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
11864     int other_sc)
11865 {
11866 	struct ctl_io_hdr *xioh;
11867 
11868 	mtx_assert(&lun->lun_lock, MA_OWNED);
11869 
11870 	/*
11871 	 * Run through the OOA queue and attempt to find the given I/O.
11872 	 * The target port, initiator ID, tag type and tag number have to
11873 	 * match the values that we got from the initiator.  If we have an
11874 	 * untagged command to abort, simply abort the first untagged command
11875 	 * we come to.  We only allow one untagged command at a time of course.
11876 	 */
11877 	LIST_FOREACH(xioh, &lun->ooa_queue, ooa_links) {
11878 		union ctl_io *xio = (union ctl_io *)xioh;
11879 		if ((targ_port == UINT32_MAX ||
11880 		     targ_port == xioh->nexus.targ_port) &&
11881 		    (init_id == UINT32_MAX ||
11882 		     init_id == xioh->nexus.initid)) {
11883 			if (targ_port != xioh->nexus.targ_port ||
11884 			    init_id != xioh->nexus.initid)
11885 				xioh->flags |= CTL_FLAG_ABORT_STATUS;
11886 			xioh->flags |= CTL_FLAG_ABORT;
11887 			if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11888 				union ctl_ha_msg msg_info;
11889 
11890 				msg_info.hdr.nexus = xioh->nexus;
11891 				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
11892 				msg_info.task.tag_num = xio->scsiio.tag_num;
11893 				msg_info.task.tag_type = xio->scsiio.tag_type;
11894 				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11895 				msg_info.hdr.original_sc = NULL;
11896 				msg_info.hdr.serializing_sc = NULL;
11897 				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11898 				    sizeof(msg_info.task), M_NOWAIT);
11899 			}
11900 			ctl_try_unblock_io(lun, xio, FALSE);
11901 		}
11902 	}
11903 }
11904 
11905 static int
11906 ctl_abort_task_set(union ctl_io *io)
11907 {
11908 	struct ctl_softc *softc = CTL_SOFTC(io);
11909 	struct ctl_lun *lun;
11910 	uint32_t targ_lun;
11911 
11912 	/*
11913 	 * Look up the LUN.
11914 	 */
11915 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11916 	mtx_lock(&softc->ctl_lock);
11917 	if (targ_lun >= ctl_max_luns ||
11918 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11919 		mtx_unlock(&softc->ctl_lock);
11920 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11921 		return (1);
11922 	}
11923 
11924 	mtx_lock(&lun->lun_lock);
11925 	mtx_unlock(&softc->ctl_lock);
11926 	if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
11927 		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
11928 		    io->io_hdr.nexus.initid,
11929 		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11930 	} else { /* CTL_TASK_CLEAR_TASK_SET */
11931 		ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
11932 		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11933 	}
11934 	mtx_unlock(&lun->lun_lock);
11935 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11936 	return (0);
11937 }
11938 
11939 static void
11940 ctl_i_t_nexus_loss(struct ctl_softc *softc, uint32_t initidx,
11941     ctl_ua_type ua_type)
11942 {
11943 	struct ctl_lun *lun;
11944 	struct scsi_sense_data *ps;
11945 	uint32_t p, i;
11946 
11947 	p = initidx / CTL_MAX_INIT_PER_PORT;
11948 	i = initidx % CTL_MAX_INIT_PER_PORT;
11949 	mtx_lock(&softc->ctl_lock);
11950 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
11951 		mtx_lock(&lun->lun_lock);
11952 		/* Abort tasks. */
11953 		ctl_abort_tasks_lun(lun, p, i, 1);
11954 		/* Clear CA. */
11955 		ps = lun->pending_sense[p];
11956 		if (ps != NULL)
11957 			ps[i].error_code = 0;
11958 		/* Clear reservation. */
11959 		if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == initidx))
11960 			lun->flags &= ~CTL_LUN_RESERVED;
11961 		/* Clear prevent media removal. */
11962 		if (lun->prevent && ctl_is_set(lun->prevent, initidx)) {
11963 			ctl_clear_mask(lun->prevent, initidx);
11964 			lun->prevent_count--;
11965 		}
11966 		/* Clear TPC status */
11967 		ctl_tpc_lun_clear(lun, initidx);
11968 		/* Establish UA. */
11969 		ctl_est_ua(lun, initidx, ua_type);
11970 		mtx_unlock(&lun->lun_lock);
11971 	}
11972 	mtx_unlock(&softc->ctl_lock);
11973 }
11974 
11975 static int
11976 ctl_i_t_nexus_reset(union ctl_io *io)
11977 {
11978 	struct ctl_softc *softc = CTL_SOFTC(io);
11979 	uint32_t initidx;
11980 
11981 	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11982 		union ctl_ha_msg msg_info;
11983 
11984 		msg_info.hdr.nexus = io->io_hdr.nexus;
11985 		msg_info.task.task_action = CTL_TASK_I_T_NEXUS_RESET;
11986 		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11987 		msg_info.hdr.original_sc = NULL;
11988 		msg_info.hdr.serializing_sc = NULL;
11989 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11990 		    sizeof(msg_info.task), M_WAITOK);
11991 	}
11992 
11993 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
11994 	ctl_i_t_nexus_loss(softc, initidx, CTL_UA_I_T_NEXUS_LOSS);
11995 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11996 	return (0);
11997 }
11998 
11999 static int
12000 ctl_abort_task(union ctl_io *io)
12001 {
12002 	struct ctl_softc *softc = CTL_SOFTC(io);
12003 	struct ctl_io_hdr *xioh;
12004 	struct ctl_lun *lun;
12005 	uint32_t targ_lun;
12006 
12007 	/*
12008 	 * Look up the LUN.
12009 	 */
12010 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12011 	mtx_lock(&softc->ctl_lock);
12012 	if (targ_lun >= ctl_max_luns ||
12013 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12014 		mtx_unlock(&softc->ctl_lock);
12015 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12016 		return (1);
12017 	}
12018 
12019 	mtx_lock(&lun->lun_lock);
12020 	mtx_unlock(&softc->ctl_lock);
12021 	/*
12022 	 * Run through the OOA queue and attempt to find the given I/O.
12023 	 * The target port, initiator ID, tag type and tag number have to
12024 	 * match the values that we got from the initiator.  If we have an
12025 	 * untagged command to abort, simply abort the first untagged command
12026 	 * we come to.  We only allow one untagged command at a time of course.
12027 	 */
12028 	LIST_FOREACH(xioh, &lun->ooa_queue, ooa_links) {
12029 		union ctl_io *xio = (union ctl_io *)xioh;
12030 		if ((xioh->nexus.targ_port != io->io_hdr.nexus.targ_port)
12031 		 || (xioh->nexus.initid != io->io_hdr.nexus.initid)
12032 		 || (xioh->flags & CTL_FLAG_ABORT))
12033 			continue;
12034 
12035 		/*
12036 		 * If the abort says that the task is untagged, the
12037 		 * task in the queue must be untagged.  Otherwise,
12038 		 * we just check to see whether the tag numbers
12039 		 * match.  This is because the QLogic firmware
12040 		 * doesn't pass back the tag type in an abort
12041 		 * request.
12042 		 */
12043 #if 0
12044 		if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
12045 		  && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
12046 		 || (xio->scsiio.tag_num == io->taskio.tag_num)) {
12047 #else
12048 		/*
12049 		 * XXX KDM we've got problems with FC, because it
12050 		 * doesn't send down a tag type with aborts.  So we
12051 		 * can only really go by the tag number...
12052 		 * This may cause problems with parallel SCSI.
12053 		 * Need to figure that out!!
12054 		 */
12055 		if (xio->scsiio.tag_num == io->taskio.tag_num) {
12056 #endif
12057 			xioh->flags |= CTL_FLAG_ABORT;
12058 			if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0 &&
12059 			    !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12060 				union ctl_ha_msg msg_info;
12061 
12062 				msg_info.hdr.nexus = io->io_hdr.nexus;
12063 				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
12064 				msg_info.task.tag_num = io->taskio.tag_num;
12065 				msg_info.task.tag_type = io->taskio.tag_type;
12066 				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12067 				msg_info.hdr.original_sc = NULL;
12068 				msg_info.hdr.serializing_sc = NULL;
12069 				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12070 				    sizeof(msg_info.task), M_NOWAIT);
12071 			}
12072 			ctl_try_unblock_io(lun, xio, FALSE);
12073 		}
12074 	}
12075 	mtx_unlock(&lun->lun_lock);
12076 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12077 	return (0);
12078 }
12079 
12080 static int
12081 ctl_query_task(union ctl_io *io, int task_set)
12082 {
12083 	struct ctl_softc *softc = CTL_SOFTC(io);
12084 	struct ctl_io_hdr *xioh;
12085 	struct ctl_lun *lun;
12086 	int found = 0;
12087 	uint32_t targ_lun;
12088 
12089 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12090 	mtx_lock(&softc->ctl_lock);
12091 	if (targ_lun >= ctl_max_luns ||
12092 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12093 		mtx_unlock(&softc->ctl_lock);
12094 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12095 		return (1);
12096 	}
12097 	mtx_lock(&lun->lun_lock);
12098 	mtx_unlock(&softc->ctl_lock);
12099 	LIST_FOREACH(xioh, &lun->ooa_queue, ooa_links) {
12100 		union ctl_io *xio = (union ctl_io *)xioh;
12101 		if ((xioh->nexus.targ_port != io->io_hdr.nexus.targ_port)
12102 		 || (xioh->nexus.initid != io->io_hdr.nexus.initid)
12103 		 || (xioh->flags & CTL_FLAG_ABORT))
12104 			continue;
12105 
12106 		if (task_set || xio->scsiio.tag_num == io->taskio.tag_num) {
12107 			found = 1;
12108 			break;
12109 		}
12110 	}
12111 	mtx_unlock(&lun->lun_lock);
12112 	if (found)
12113 		io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12114 	else
12115 		io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12116 	return (0);
12117 }
12118 
12119 static int
12120 ctl_query_async_event(union ctl_io *io)
12121 {
12122 	struct ctl_softc *softc = CTL_SOFTC(io);
12123 	struct ctl_lun *lun;
12124 	ctl_ua_type ua;
12125 	uint32_t targ_lun, initidx;
12126 
12127 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12128 	mtx_lock(&softc->ctl_lock);
12129 	if (targ_lun >= ctl_max_luns ||
12130 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12131 		mtx_unlock(&softc->ctl_lock);
12132 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12133 		return (1);
12134 	}
12135 	mtx_lock(&lun->lun_lock);
12136 	mtx_unlock(&softc->ctl_lock);
12137 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
12138 	ua = ctl_build_qae(lun, initidx, io->taskio.task_resp);
12139 	mtx_unlock(&lun->lun_lock);
12140 	if (ua != CTL_UA_NONE)
12141 		io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12142 	else
12143 		io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12144 	return (0);
12145 }
12146 
12147 static void
12148 ctl_run_task(union ctl_io *io)
12149 {
12150 	int retval = 1;
12151 
12152 	CTL_DEBUG_PRINT(("ctl_run_task\n"));
12153 	KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12154 	    ("ctl_run_task: Unextected io_type %d\n", io->io_hdr.io_type));
12155 	io->taskio.task_status = CTL_TASK_FUNCTION_NOT_SUPPORTED;
12156 	bzero(io->taskio.task_resp, sizeof(io->taskio.task_resp));
12157 	switch (io->taskio.task_action) {
12158 	case CTL_TASK_ABORT_TASK:
12159 		retval = ctl_abort_task(io);
12160 		break;
12161 	case CTL_TASK_ABORT_TASK_SET:
12162 	case CTL_TASK_CLEAR_TASK_SET:
12163 		retval = ctl_abort_task_set(io);
12164 		break;
12165 	case CTL_TASK_CLEAR_ACA:
12166 		break;
12167 	case CTL_TASK_I_T_NEXUS_RESET:
12168 		retval = ctl_i_t_nexus_reset(io);
12169 		break;
12170 	case CTL_TASK_LUN_RESET:
12171 		retval = ctl_lun_reset(io);
12172 		break;
12173 	case CTL_TASK_TARGET_RESET:
12174 	case CTL_TASK_BUS_RESET:
12175 		retval = ctl_target_reset(io);
12176 		break;
12177 	case CTL_TASK_PORT_LOGIN:
12178 		break;
12179 	case CTL_TASK_PORT_LOGOUT:
12180 		break;
12181 	case CTL_TASK_QUERY_TASK:
12182 		retval = ctl_query_task(io, 0);
12183 		break;
12184 	case CTL_TASK_QUERY_TASK_SET:
12185 		retval = ctl_query_task(io, 1);
12186 		break;
12187 	case CTL_TASK_QUERY_ASYNC_EVENT:
12188 		retval = ctl_query_async_event(io);
12189 		break;
12190 	default:
12191 		printf("%s: got unknown task management event %d\n",
12192 		       __func__, io->taskio.task_action);
12193 		break;
12194 	}
12195 	if (retval == 0)
12196 		io->io_hdr.status = CTL_SUCCESS;
12197 	else
12198 		io->io_hdr.status = CTL_ERROR;
12199 	ctl_done(io);
12200 }
12201 
12202 /*
12203  * For HA operation.  Handle commands that come in from the other
12204  * controller.
12205  */
12206 static void
12207 ctl_handle_isc(union ctl_io *io)
12208 {
12209 	struct ctl_softc *softc = CTL_SOFTC(io);
12210 	struct ctl_lun *lun;
12211 	const struct ctl_cmd_entry *entry;
12212 	uint32_t targ_lun;
12213 
12214 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12215 	switch (io->io_hdr.msg_type) {
12216 	case CTL_MSG_SERIALIZE:
12217 		ctl_serialize_other_sc_cmd(&io->scsiio);
12218 		break;
12219 	case CTL_MSG_R2R:		/* Only used in SER_ONLY mode. */
12220 		entry = ctl_get_cmd_entry(&io->scsiio, NULL);
12221 		if (targ_lun >= ctl_max_luns ||
12222 		    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12223 			ctl_done(io);
12224 			break;
12225 		}
12226 		mtx_lock(&lun->lun_lock);
12227 		if (ctl_scsiio_lun_check(lun, entry, &io->scsiio) != 0) {
12228 			mtx_unlock(&lun->lun_lock);
12229 			ctl_done(io);
12230 			break;
12231 		}
12232 		io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12233 		mtx_unlock(&lun->lun_lock);
12234 		ctl_enqueue_rtr(io);
12235 		break;
12236 	case CTL_MSG_FINISH_IO:
12237 		if (softc->ha_mode == CTL_HA_MODE_XFER) {
12238 			ctl_done(io);
12239 			break;
12240 		}
12241 		if (targ_lun >= ctl_max_luns ||
12242 		    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12243 			ctl_free_io(io);
12244 			break;
12245 		}
12246 		mtx_lock(&lun->lun_lock);
12247 		ctl_try_unblock_others(lun, io, TRUE);
12248 		LIST_REMOVE(&io->io_hdr, ooa_links);
12249 		mtx_unlock(&lun->lun_lock);
12250 		ctl_free_io(io);
12251 		break;
12252 	case CTL_MSG_PERS_ACTION:
12253 		ctl_hndl_per_res_out_on_other_sc(io);
12254 		ctl_free_io(io);
12255 		break;
12256 	case CTL_MSG_BAD_JUJU:
12257 		ctl_done(io);
12258 		break;
12259 	case CTL_MSG_DATAMOVE:		/* Only used in XFER mode */
12260 		ctl_datamove_remote(io);
12261 		break;
12262 	case CTL_MSG_DATAMOVE_DONE:	/* Only used in XFER mode */
12263 		ctl_datamove_done(io, false);
12264 		break;
12265 	case CTL_MSG_FAILOVER:
12266 		ctl_failover_lun(io);
12267 		ctl_free_io(io);
12268 		break;
12269 	default:
12270 		printf("%s: Invalid message type %d\n",
12271 		       __func__, io->io_hdr.msg_type);
12272 		ctl_free_io(io);
12273 		break;
12274 	}
12275 
12276 }
12277 
12278 /*
12279  * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12280  * there is no match.
12281  */
12282 static ctl_lun_error_pattern
12283 ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12284 {
12285 	const struct ctl_cmd_entry *entry;
12286 	ctl_lun_error_pattern filtered_pattern, pattern;
12287 
12288 	pattern = desc->error_pattern;
12289 
12290 	/*
12291 	 * XXX KDM we need more data passed into this function to match a
12292 	 * custom pattern, and we actually need to implement custom pattern
12293 	 * matching.
12294 	 */
12295 	if (pattern & CTL_LUN_PAT_CMD)
12296 		return (CTL_LUN_PAT_CMD);
12297 
12298 	if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12299 		return (CTL_LUN_PAT_ANY);
12300 
12301 	entry = ctl_get_cmd_entry(ctsio, NULL);
12302 
12303 	filtered_pattern = entry->pattern & pattern;
12304 
12305 	/*
12306 	 * If the user requested specific flags in the pattern (e.g.
12307 	 * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12308 	 * flags.
12309 	 *
12310 	 * If the user did not specify any flags, it doesn't matter whether
12311 	 * or not the command supports the flags.
12312 	 */
12313 	if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12314 	     (pattern & ~CTL_LUN_PAT_MASK))
12315 		return (CTL_LUN_PAT_NONE);
12316 
12317 	/*
12318 	 * If the user asked for a range check, see if the requested LBA
12319 	 * range overlaps with this command's LBA range.
12320 	 */
12321 	if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12322 		uint64_t lba1;
12323 		uint64_t len1;
12324 		ctl_action action;
12325 		int retval;
12326 
12327 		retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12328 		if (retval != 0)
12329 			return (CTL_LUN_PAT_NONE);
12330 
12331 		action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12332 					      desc->lba_range.len, FALSE);
12333 		/*
12334 		 * A "pass" means that the LBA ranges don't overlap, so
12335 		 * this doesn't match the user's range criteria.
12336 		 */
12337 		if (action == CTL_ACTION_PASS)
12338 			return (CTL_LUN_PAT_NONE);
12339 	}
12340 
12341 	return (filtered_pattern);
12342 }
12343 
12344 static void
12345 ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12346 {
12347 	struct ctl_error_desc *desc, *desc2;
12348 
12349 	mtx_assert(&lun->lun_lock, MA_OWNED);
12350 
12351 	STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12352 		ctl_lun_error_pattern pattern;
12353 		/*
12354 		 * Check to see whether this particular command matches
12355 		 * the pattern in the descriptor.
12356 		 */
12357 		pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12358 		if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12359 			continue;
12360 
12361 		switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12362 		case CTL_LUN_INJ_ABORTED:
12363 			ctl_set_aborted(&io->scsiio);
12364 			break;
12365 		case CTL_LUN_INJ_MEDIUM_ERR:
12366 			ctl_set_medium_error(&io->scsiio,
12367 			    (io->io_hdr.flags & CTL_FLAG_DATA_MASK) !=
12368 			     CTL_FLAG_DATA_OUT);
12369 			break;
12370 		case CTL_LUN_INJ_UA:
12371 			/* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12372 			 * OCCURRED */
12373 			ctl_set_ua(&io->scsiio, 0x29, 0x00);
12374 			break;
12375 		case CTL_LUN_INJ_CUSTOM:
12376 			/*
12377 			 * We're assuming the user knows what he is doing.
12378 			 * Just copy the sense information without doing
12379 			 * checks.
12380 			 */
12381 			bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12382 			      MIN(sizeof(desc->custom_sense),
12383 				  sizeof(io->scsiio.sense_data)));
12384 			io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12385 			io->scsiio.sense_len = SSD_FULL_SIZE;
12386 			io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12387 			break;
12388 		case CTL_LUN_INJ_NONE:
12389 		default:
12390 			/*
12391 			 * If this is an error injection type we don't know
12392 			 * about, clear the continuous flag (if it is set)
12393 			 * so it will get deleted below.
12394 			 */
12395 			desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12396 			break;
12397 		}
12398 		/*
12399 		 * By default, each error injection action is a one-shot
12400 		 */
12401 		if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12402 			continue;
12403 
12404 		STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12405 
12406 		free(desc, M_CTL);
12407 	}
12408 }
12409 
12410 #ifdef CTL_IO_DELAY
12411 static void
12412 ctl_datamove_timer_wakeup(void *arg)
12413 {
12414 	union ctl_io *io;
12415 
12416 	io = (union ctl_io *)arg;
12417 
12418 	ctl_datamove(io);
12419 }
12420 #endif /* CTL_IO_DELAY */
12421 
12422 static void
12423 ctl_datamove_done_process(union ctl_io *io)
12424 {
12425 #ifdef CTL_TIME_IO
12426 	struct bintime cur_bt;
12427 #endif
12428 
12429 	KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
12430 	    ("%s: unexpected I/O type %x", __func__, io->io_hdr.io_type));
12431 
12432 #ifdef CTL_TIME_IO
12433 	getbinuptime(&cur_bt);
12434 	bintime_sub(&cur_bt, &io->io_hdr.dma_start_bt);
12435 	bintime_add(&io->io_hdr.dma_bt, &cur_bt);
12436 #endif
12437 	io->io_hdr.num_dmas++;
12438 
12439 	if ((io->io_hdr.port_status != 0) &&
12440 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
12441 	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
12442 		ctl_set_internal_failure(&io->scsiio, /*sks_valid*/ 1,
12443 		    /*retry_count*/ io->io_hdr.port_status);
12444 	} else if (io->scsiio.kern_data_resid != 0 &&
12445 	    (io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT &&
12446 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
12447 	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
12448 		ctl_set_invalid_field_ciu(&io->scsiio);
12449 	} else if (ctl_debug & CTL_DEBUG_CDB_DATA)
12450 		ctl_data_print(io);
12451 }
12452 
12453 void
12454 ctl_datamove_done(union ctl_io *io, bool samethr)
12455 {
12456 
12457 	ctl_datamove_done_process(io);
12458 	io->scsiio.be_move_done(io, samethr);
12459 }
12460 
12461 void
12462 ctl_datamove(union ctl_io *io)
12463 {
12464 	void (*fe_datamove)(union ctl_io *io);
12465 
12466 	mtx_assert(&((struct ctl_softc *)CTL_SOFTC(io))->ctl_lock, MA_NOTOWNED);
12467 
12468 	CTL_DEBUG_PRINT(("ctl_datamove\n"));
12469 
12470 	/* No data transferred yet.  Frontend must update this when done. */
12471 	io->scsiio.kern_data_resid = io->scsiio.kern_data_len;
12472 
12473 #ifdef CTL_TIME_IO
12474 	getbinuptime(&io->io_hdr.dma_start_bt);
12475 #endif /* CTL_TIME_IO */
12476 
12477 #ifdef CTL_IO_DELAY
12478 	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12479 		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12480 	} else {
12481 		struct ctl_lun *lun;
12482 
12483 		lun = CTL_LUN(io);
12484 		if ((lun != NULL)
12485 		 && (lun->delay_info.datamove_delay > 0)) {
12486 			callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
12487 			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12488 			callout_reset(&io->io_hdr.delay_callout,
12489 				      lun->delay_info.datamove_delay * hz,
12490 				      ctl_datamove_timer_wakeup, io);
12491 			if (lun->delay_info.datamove_type ==
12492 			    CTL_DELAY_TYPE_ONESHOT)
12493 				lun->delay_info.datamove_delay = 0;
12494 			return;
12495 		}
12496 	}
12497 #endif
12498 
12499 	/*
12500 	 * This command has been aborted.  Set the port status, so we fail
12501 	 * the data move.
12502 	 */
12503 	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12504 		printf("ctl_datamove: tag 0x%04x on (%u:%u:%u) aborted\n",
12505 		       io->scsiio.tag_num, io->io_hdr.nexus.initid,
12506 		       io->io_hdr.nexus.targ_port,
12507 		       io->io_hdr.nexus.targ_lun);
12508 		io->io_hdr.port_status = 31337;
12509 		ctl_datamove_done_process(io);
12510 		io->scsiio.be_move_done(io, true);
12511 		return;
12512 	}
12513 
12514 	/* Don't confuse frontend with zero length data move. */
12515 	if (io->scsiio.kern_data_len == 0) {
12516 		ctl_datamove_done_process(io);
12517 		io->scsiio.be_move_done(io, true);
12518 		return;
12519 	}
12520 
12521 	fe_datamove = CTL_PORT(io)->fe_datamove;
12522 	fe_datamove(io);
12523 }
12524 
12525 static void
12526 ctl_send_datamove_done(union ctl_io *io, int have_lock)
12527 {
12528 	union ctl_ha_msg msg;
12529 #ifdef CTL_TIME_IO
12530 	struct bintime cur_bt;
12531 #endif
12532 
12533 	memset(&msg, 0, sizeof(msg));
12534 	msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12535 	msg.hdr.original_sc = io;
12536 	msg.hdr.serializing_sc = io->io_hdr.remote_io;
12537 	msg.hdr.nexus = io->io_hdr.nexus;
12538 	msg.hdr.status = io->io_hdr.status;
12539 	msg.scsi.kern_data_resid = io->scsiio.kern_data_resid;
12540 	msg.scsi.tag_num = io->scsiio.tag_num;
12541 	msg.scsi.tag_type = io->scsiio.tag_type;
12542 	msg.scsi.scsi_status = io->scsiio.scsi_status;
12543 	memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12544 	       io->scsiio.sense_len);
12545 	msg.scsi.sense_len = io->scsiio.sense_len;
12546 	msg.scsi.port_status = io->io_hdr.port_status;
12547 	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12548 	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12549 		ctl_failover_io(io, /*have_lock*/ have_lock);
12550 		return;
12551 	}
12552 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12553 	    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
12554 	    msg.scsi.sense_len, M_WAITOK);
12555 
12556 #ifdef CTL_TIME_IO
12557 	getbinuptime(&cur_bt);
12558 	bintime_sub(&cur_bt, &io->io_hdr.dma_start_bt);
12559 	bintime_add(&io->io_hdr.dma_bt, &cur_bt);
12560 #endif
12561 	io->io_hdr.num_dmas++;
12562 }
12563 
12564 /*
12565  * The DMA to the remote side is done, now we need to tell the other side
12566  * we're done so it can continue with its data movement.
12567  */
12568 static void
12569 ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12570 {
12571 	union ctl_io *io;
12572 	uint32_t i;
12573 
12574 	io = rq->context;
12575 
12576 	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12577 		printf("%s: ISC DMA write failed with error %d", __func__,
12578 		       rq->ret);
12579 		ctl_set_internal_failure(&io->scsiio,
12580 					 /*sks_valid*/ 1,
12581 					 /*retry_count*/ rq->ret);
12582 	}
12583 
12584 	ctl_dt_req_free(rq);
12585 
12586 	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12587 		free(CTL_LSGLT(io)[i].addr, M_CTL);
12588 	free(CTL_RSGL(io), M_CTL);
12589 	CTL_RSGL(io) = NULL;
12590 	CTL_LSGL(io) = NULL;
12591 
12592 	/*
12593 	 * The data is in local and remote memory, so now we need to send
12594 	 * status (good or back) back to the other side.
12595 	 */
12596 	ctl_send_datamove_done(io, /*have_lock*/ 0);
12597 }
12598 
12599 /*
12600  * We've moved the data from the host/controller into local memory.  Now we
12601  * need to push it over to the remote controller's memory.
12602  */
12603 static int
12604 ctl_datamove_remote_dm_write_cb(union ctl_io *io, bool samethr)
12605 {
12606 	int retval;
12607 
12608 	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
12609 					  ctl_datamove_remote_write_cb);
12610 	return (retval);
12611 }
12612 
12613 static void
12614 ctl_datamove_remote_write(union ctl_io *io)
12615 {
12616 	int retval;
12617 	void (*fe_datamove)(union ctl_io *io);
12618 
12619 	/*
12620 	 * - Get the data from the host/HBA into local memory.
12621 	 * - DMA memory from the local controller to the remote controller.
12622 	 * - Send status back to the remote controller.
12623 	 */
12624 
12625 	retval = ctl_datamove_remote_sgl_setup(io);
12626 	if (retval != 0)
12627 		return;
12628 
12629 	/* Switch the pointer over so the FETD knows what to do */
12630 	io->scsiio.kern_data_ptr = (uint8_t *)CTL_LSGL(io);
12631 
12632 	/*
12633 	 * Use a custom move done callback, since we need to send completion
12634 	 * back to the other controller, not to the backend on this side.
12635 	 */
12636 	io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
12637 
12638 	fe_datamove = CTL_PORT(io)->fe_datamove;
12639 	fe_datamove(io);
12640 }
12641 
12642 static int
12643 ctl_datamove_remote_dm_read_cb(union ctl_io *io, bool samethr)
12644 {
12645 	uint32_t i;
12646 
12647 	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12648 		free(CTL_LSGLT(io)[i].addr, M_CTL);
12649 	free(CTL_RSGL(io), M_CTL);
12650 	CTL_RSGL(io) = NULL;
12651 	CTL_LSGL(io) = NULL;
12652 
12653 	/*
12654 	 * The read is done, now we need to send status (good or bad) back
12655 	 * to the other side.
12656 	 */
12657 	ctl_send_datamove_done(io, /*have_lock*/ 0);
12658 
12659 	return (0);
12660 }
12661 
12662 static void
12663 ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
12664 {
12665 	union ctl_io *io;
12666 	void (*fe_datamove)(union ctl_io *io);
12667 
12668 	io = rq->context;
12669 
12670 	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12671 		printf("%s: ISC DMA read failed with error %d\n", __func__,
12672 		       rq->ret);
12673 		ctl_set_internal_failure(&io->scsiio,
12674 					 /*sks_valid*/ 1,
12675 					 /*retry_count*/ rq->ret);
12676 	}
12677 
12678 	ctl_dt_req_free(rq);
12679 
12680 	/* Switch the pointer over so the FETD knows what to do */
12681 	io->scsiio.kern_data_ptr = (uint8_t *)CTL_LSGL(io);
12682 
12683 	/*
12684 	 * Use a custom move done callback, since we need to send completion
12685 	 * back to the other controller, not to the backend on this side.
12686 	 */
12687 	io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
12688 
12689 	/* XXX KDM add checks like the ones in ctl_datamove? */
12690 
12691 	fe_datamove = CTL_PORT(io)->fe_datamove;
12692 	fe_datamove(io);
12693 }
12694 
12695 static int
12696 ctl_datamove_remote_sgl_setup(union ctl_io *io)
12697 {
12698 	struct ctl_sg_entry *local_sglist;
12699 	uint32_t len_to_go;
12700 	int retval;
12701 	int i;
12702 
12703 	retval = 0;
12704 	local_sglist = CTL_LSGL(io);
12705 	len_to_go = io->scsiio.kern_data_len;
12706 
12707 	/*
12708 	 * The difficult thing here is that the size of the various
12709 	 * S/G segments may be different than the size from the
12710 	 * remote controller.  That'll make it harder when DMAing
12711 	 * the data back to the other side.
12712 	 */
12713 	for (i = 0; len_to_go > 0; i++) {
12714 		local_sglist[i].len = MIN(len_to_go, CTL_HA_DATAMOVE_SEGMENT);
12715 		local_sglist[i].addr =
12716 		    malloc(local_sglist[i].len, M_CTL, M_WAITOK);
12717 
12718 		len_to_go -= local_sglist[i].len;
12719 	}
12720 	/*
12721 	 * Reset the number of S/G entries accordingly.  The original
12722 	 * number of S/G entries is available in rem_sg_entries.
12723 	 */
12724 	io->scsiio.kern_sg_entries = i;
12725 
12726 	return (retval);
12727 }
12728 
12729 static int
12730 ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
12731 			 ctl_ha_dt_cb callback)
12732 {
12733 	struct ctl_ha_dt_req *rq;
12734 	struct ctl_sg_entry *remote_sglist, *local_sglist;
12735 	uint32_t local_used, remote_used, total_used;
12736 	int i, j, isc_ret;
12737 
12738 	rq = ctl_dt_req_alloc();
12739 
12740 	/*
12741 	 * If we failed to allocate the request, and if the DMA didn't fail
12742 	 * anyway, set busy status.  This is just a resource allocation
12743 	 * failure.
12744 	 */
12745 	if ((rq == NULL)
12746 	 && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12747 	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS))
12748 		ctl_set_busy(&io->scsiio);
12749 
12750 	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12751 	    (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) {
12752 		if (rq != NULL)
12753 			ctl_dt_req_free(rq);
12754 
12755 		/*
12756 		 * The data move failed.  We need to return status back
12757 		 * to the other controller.  No point in trying to DMA
12758 		 * data to the remote controller.
12759 		 */
12760 
12761 		ctl_send_datamove_done(io, /*have_lock*/ 0);
12762 
12763 		return (1);
12764 	}
12765 
12766 	local_sglist = CTL_LSGL(io);
12767 	remote_sglist = CTL_RSGL(io);
12768 	local_used = 0;
12769 	remote_used = 0;
12770 	total_used = 0;
12771 
12772 	/*
12773 	 * Pull/push the data over the wire from/to the other controller.
12774 	 * This takes into account the possibility that the local and
12775 	 * remote sglists may not be identical in terms of the size of
12776 	 * the elements and the number of elements.
12777 	 *
12778 	 * One fundamental assumption here is that the length allocated for
12779 	 * both the local and remote sglists is identical.  Otherwise, we've
12780 	 * essentially got a coding error of some sort.
12781 	 */
12782 	isc_ret = CTL_HA_STATUS_SUCCESS;
12783 	for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
12784 		uint32_t cur_len;
12785 		uint8_t *tmp_ptr;
12786 
12787 		rq->command = command;
12788 		rq->context = io;
12789 
12790 		/*
12791 		 * Both pointers should be aligned.  But it is possible
12792 		 * that the allocation length is not.  They should both
12793 		 * also have enough slack left over at the end, though,
12794 		 * to round up to the next 8 byte boundary.
12795 		 */
12796 		cur_len = MIN(local_sglist[i].len - local_used,
12797 			      remote_sglist[j].len - remote_used);
12798 		rq->size = cur_len;
12799 
12800 		tmp_ptr = (uint8_t *)local_sglist[i].addr;
12801 		tmp_ptr += local_used;
12802 
12803 #if 0
12804 		/* Use physical addresses when talking to ISC hardware */
12805 		if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
12806 			/* XXX KDM use busdma */
12807 			rq->local = vtophys(tmp_ptr);
12808 		} else
12809 			rq->local = tmp_ptr;
12810 #else
12811 		KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
12812 		    ("HA does not support BUS_ADDR"));
12813 		rq->local = tmp_ptr;
12814 #endif
12815 
12816 		tmp_ptr = (uint8_t *)remote_sglist[j].addr;
12817 		tmp_ptr += remote_used;
12818 		rq->remote = tmp_ptr;
12819 
12820 		rq->callback = NULL;
12821 
12822 		local_used += cur_len;
12823 		if (local_used >= local_sglist[i].len) {
12824 			i++;
12825 			local_used = 0;
12826 		}
12827 
12828 		remote_used += cur_len;
12829 		if (remote_used >= remote_sglist[j].len) {
12830 			j++;
12831 			remote_used = 0;
12832 		}
12833 		total_used += cur_len;
12834 
12835 		if (total_used >= io->scsiio.kern_data_len)
12836 			rq->callback = callback;
12837 
12838 		isc_ret = ctl_dt_single(rq);
12839 		if (isc_ret > CTL_HA_STATUS_SUCCESS)
12840 			break;
12841 	}
12842 	if (isc_ret != CTL_HA_STATUS_WAIT) {
12843 		rq->ret = isc_ret;
12844 		callback(rq);
12845 	}
12846 
12847 	return (0);
12848 }
12849 
12850 static void
12851 ctl_datamove_remote_read(union ctl_io *io)
12852 {
12853 	int retval;
12854 	uint32_t i;
12855 
12856 	/*
12857 	 * This will send an error to the other controller in the case of a
12858 	 * failure.
12859 	 */
12860 	retval = ctl_datamove_remote_sgl_setup(io);
12861 	if (retval != 0)
12862 		return;
12863 
12864 	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
12865 					  ctl_datamove_remote_read_cb);
12866 	if (retval != 0) {
12867 		/*
12868 		 * Make sure we free memory if there was an error..  The
12869 		 * ctl_datamove_remote_xfer() function will send the
12870 		 * datamove done message, or call the callback with an
12871 		 * error if there is a problem.
12872 		 */
12873 		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12874 			free(CTL_LSGLT(io)[i].addr, M_CTL);
12875 		free(CTL_RSGL(io), M_CTL);
12876 		CTL_RSGL(io) = NULL;
12877 		CTL_LSGL(io) = NULL;
12878 	}
12879 }
12880 
12881 /*
12882  * Process a datamove request from the other controller.  This is used for
12883  * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
12884  * first.  Once that is complete, the data gets DMAed into the remote
12885  * controller's memory.  For reads, we DMA from the remote controller's
12886  * memory into our memory first, and then move it out to the FETD.
12887  */
12888 static void
12889 ctl_datamove_remote(union ctl_io *io)
12890 {
12891 
12892 	mtx_assert(&((struct ctl_softc *)CTL_SOFTC(io))->ctl_lock, MA_NOTOWNED);
12893 
12894 	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12895 		ctl_failover_io(io, /*have_lock*/ 0);
12896 		return;
12897 	}
12898 
12899 	/*
12900 	 * Note that we look for an aborted I/O here, but don't do some of
12901 	 * the other checks that ctl_datamove() normally does.
12902 	 * We don't need to run the datamove delay code, since that should
12903 	 * have been done if need be on the other controller.
12904 	 */
12905 	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12906 		printf("%s: tag 0x%04x on (%u:%u:%u) aborted\n", __func__,
12907 		       io->scsiio.tag_num, io->io_hdr.nexus.initid,
12908 		       io->io_hdr.nexus.targ_port,
12909 		       io->io_hdr.nexus.targ_lun);
12910 		io->io_hdr.port_status = 31338;
12911 		ctl_send_datamove_done(io, /*have_lock*/ 0);
12912 		return;
12913 	}
12914 
12915 	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT)
12916 		ctl_datamove_remote_write(io);
12917 	else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
12918 		ctl_datamove_remote_read(io);
12919 	else {
12920 		io->io_hdr.port_status = 31339;
12921 		ctl_send_datamove_done(io, /*have_lock*/ 0);
12922 	}
12923 }
12924 
12925 static void
12926 ctl_process_done(union ctl_io *io)
12927 {
12928 	struct ctl_softc *softc = CTL_SOFTC(io);
12929 	struct ctl_port *port = CTL_PORT(io);
12930 	struct ctl_lun *lun = CTL_LUN(io);
12931 	void (*fe_done)(union ctl_io *io);
12932 	union ctl_ha_msg msg;
12933 
12934 	CTL_DEBUG_PRINT(("ctl_process_done\n"));
12935 	fe_done = port->fe_done;
12936 
12937 #ifdef CTL_TIME_IO
12938 	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12939 		char str[256];
12940 		char path_str[64];
12941 		struct sbuf sb;
12942 
12943 		ctl_scsi_path_string(io, path_str, sizeof(path_str));
12944 		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12945 
12946 		sbuf_cat(&sb, path_str);
12947 		switch (io->io_hdr.io_type) {
12948 		case CTL_IO_SCSI:
12949 			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12950 			sbuf_printf(&sb, "\n");
12951 			sbuf_cat(&sb, path_str);
12952 			sbuf_printf(&sb, "Tag: 0x%04x/%d, Prio: %d\n",
12953 				    io->scsiio.tag_num, io->scsiio.tag_type,
12954 				    io->scsiio.priority);
12955 			break;
12956 		case CTL_IO_TASK:
12957 			sbuf_printf(&sb, "Task Action: %d Tag: 0x%04x/%d\n",
12958 				    io->taskio.task_action,
12959 				    io->taskio.tag_num, io->taskio.tag_type);
12960 			break;
12961 		default:
12962 			panic("%s: Invalid CTL I/O type %d\n",
12963 			    __func__, io->io_hdr.io_type);
12964 		}
12965 		sbuf_cat(&sb, path_str);
12966 		sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
12967 			    (intmax_t)time_uptime - io->io_hdr.start_time);
12968 		sbuf_finish(&sb);
12969 		printf("%s", sbuf_data(&sb));
12970 	}
12971 #endif /* CTL_TIME_IO */
12972 
12973 	switch (io->io_hdr.io_type) {
12974 	case CTL_IO_SCSI:
12975 		break;
12976 	case CTL_IO_TASK:
12977 		if (ctl_debug & CTL_DEBUG_INFO)
12978 			ctl_io_error_print(io, NULL);
12979 		fe_done(io);
12980 		return;
12981 	default:
12982 		panic("%s: Invalid CTL I/O type %d\n",
12983 		    __func__, io->io_hdr.io_type);
12984 	}
12985 
12986 	if (lun == NULL) {
12987 		CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
12988 				 io->io_hdr.nexus.targ_mapped_lun));
12989 		goto bailout;
12990 	}
12991 
12992 	mtx_lock(&lun->lun_lock);
12993 
12994 	/*
12995 	 * Check to see if we have any informational exception and status
12996 	 * of this command can be modified to report it in form of either
12997 	 * RECOVERED ERROR or NO SENSE, depending on MRIE mode page field.
12998 	 */
12999 	if (lun->ie_reported == 0 && lun->ie_asc != 0 &&
13000 	    io->io_hdr.status == CTL_SUCCESS &&
13001 	    (io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0) {
13002 		uint8_t mrie = lun->MODE_IE.mrie;
13003 		uint8_t per = ((lun->MODE_RWER.byte3 & SMS_RWER_PER) ||
13004 		    (lun->MODE_VER.byte3 & SMS_VER_PER));
13005 		if (((mrie == SIEP_MRIE_REC_COND && per) ||
13006 		     mrie == SIEP_MRIE_REC_UNCOND ||
13007 		     mrie == SIEP_MRIE_NO_SENSE) &&
13008 		    (ctl_get_cmd_entry(&io->scsiio, NULL)->flags &
13009 		     CTL_CMD_FLAG_NO_SENSE) == 0) {
13010 			ctl_set_sense(&io->scsiio,
13011 			      /*current_error*/ 1,
13012 			      /*sense_key*/ (mrie == SIEP_MRIE_NO_SENSE) ?
13013 			        SSD_KEY_NO_SENSE : SSD_KEY_RECOVERED_ERROR,
13014 			      /*asc*/ lun->ie_asc,
13015 			      /*ascq*/ lun->ie_ascq,
13016 			      SSD_ELEM_NONE);
13017 			lun->ie_reported = 1;
13018 		}
13019 	} else if (lun->ie_reported < 0)
13020 		lun->ie_reported = 0;
13021 
13022 	/*
13023 	 * Check to see if we have any errors to inject here.  We only
13024 	 * inject errors for commands that don't already have errors set.
13025 	 */
13026 	if (!STAILQ_EMPTY(&lun->error_list) &&
13027 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS) &&
13028 	    ((io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0))
13029 		ctl_inject_error(lun, io);
13030 
13031 	/*
13032 	 * XXX KDM how do we treat commands that aren't completed
13033 	 * successfully?
13034 	 *
13035 	 * XXX KDM should we also track I/O latency?
13036 	 */
13037 	if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13038 	    io->io_hdr.io_type == CTL_IO_SCSI) {
13039 		int type;
13040 #ifdef CTL_TIME_IO
13041 		struct bintime bt;
13042 
13043 		getbinuptime(&bt);
13044 		bintime_sub(&bt, &io->io_hdr.start_bt);
13045 #endif
13046 		if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13047 		    CTL_FLAG_DATA_IN)
13048 			type = CTL_STATS_READ;
13049 		else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13050 		    CTL_FLAG_DATA_OUT)
13051 			type = CTL_STATS_WRITE;
13052 		else
13053 			type = CTL_STATS_NO_IO;
13054 
13055 		lun->stats.bytes[type] += io->scsiio.kern_total_len;
13056 		lun->stats.operations[type] ++;
13057 		lun->stats.dmas[type] += io->io_hdr.num_dmas;
13058 #ifdef CTL_TIME_IO
13059 		bintime_add(&lun->stats.dma_time[type], &io->io_hdr.dma_bt);
13060 		bintime_add(&lun->stats.time[type], &bt);
13061 #endif
13062 
13063 		mtx_lock(&port->port_lock);
13064 		port->stats.bytes[type] += io->scsiio.kern_total_len;
13065 		port->stats.operations[type] ++;
13066 		port->stats.dmas[type] += io->io_hdr.num_dmas;
13067 #ifdef CTL_TIME_IO
13068 		bintime_add(&port->stats.dma_time[type], &io->io_hdr.dma_bt);
13069 		bintime_add(&port->stats.time[type], &bt);
13070 #endif
13071 		mtx_unlock(&port->port_lock);
13072 	}
13073 
13074 	/*
13075 	 * Run through the blocked queue of this I/O and see if anything
13076 	 * can be unblocked, now that this I/O is done and will be removed.
13077 	 * We need to do it before removal to have OOA position to start.
13078 	 */
13079 	ctl_try_unblock_others(lun, io, TRUE);
13080 
13081 	/*
13082 	 * Remove this from the OOA queue.
13083 	 */
13084 	LIST_REMOVE(&io->io_hdr, ooa_links);
13085 #ifdef CTL_TIME_IO
13086 	if (LIST_EMPTY(&lun->ooa_queue))
13087 		lun->last_busy = getsbinuptime();
13088 #endif
13089 
13090 	/*
13091 	 * If the LUN has been invalidated, free it if there is nothing
13092 	 * left on its OOA queue.
13093 	 */
13094 	if ((lun->flags & CTL_LUN_INVALID)
13095 	 && LIST_EMPTY(&lun->ooa_queue)) {
13096 		mtx_unlock(&lun->lun_lock);
13097 		ctl_free_lun(lun);
13098 	} else
13099 		mtx_unlock(&lun->lun_lock);
13100 
13101 bailout:
13102 
13103 	/*
13104 	 * If this command has been aborted, make sure we set the status
13105 	 * properly.  The FETD is responsible for freeing the I/O and doing
13106 	 * whatever it needs to do to clean up its state.
13107 	 */
13108 	if (io->io_hdr.flags & CTL_FLAG_ABORT)
13109 		ctl_set_task_aborted(&io->scsiio);
13110 
13111 	/*
13112 	 * If enabled, print command error status.
13113 	 */
13114 	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS &&
13115 	    (ctl_debug & CTL_DEBUG_INFO) != 0)
13116 		ctl_io_error_print(io, NULL);
13117 
13118 	/*
13119 	 * Tell the FETD or the other shelf controller we're done with this
13120 	 * command.  Note that only SCSI commands get to this point.  Task
13121 	 * management commands are completed above.
13122 	 */
13123 	if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
13124 	    (io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)) {
13125 		memset(&msg, 0, sizeof(msg));
13126 		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13127 		msg.hdr.serializing_sc = io->io_hdr.remote_io;
13128 		msg.hdr.nexus = io->io_hdr.nexus;
13129 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13130 		    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data),
13131 		    M_WAITOK);
13132 	}
13133 
13134 	fe_done(io);
13135 }
13136 
13137 /*
13138  * Front end should call this if it doesn't do autosense.  When the request
13139  * sense comes back in from the initiator, we'll dequeue this and send it.
13140  */
13141 int
13142 ctl_queue_sense(union ctl_io *io)
13143 {
13144 	struct ctl_softc *softc = CTL_SOFTC(io);
13145 	struct ctl_port *port = CTL_PORT(io);
13146 	struct ctl_lun *lun;
13147 	struct scsi_sense_data *ps;
13148 	uint32_t initidx, p, targ_lun;
13149 
13150 	CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13151 
13152 	targ_lun = ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13153 
13154 	/*
13155 	 * LUN lookup will likely move to the ctl_work_thread() once we
13156 	 * have our new queueing infrastructure (that doesn't put things on
13157 	 * a per-LUN queue initially).  That is so that we can handle
13158 	 * things like an INQUIRY to a LUN that we don't have enabled.  We
13159 	 * can't deal with that right now.
13160 	 * If we don't have a LUN for this, just toss the sense information.
13161 	 */
13162 	mtx_lock(&softc->ctl_lock);
13163 	if (targ_lun >= ctl_max_luns ||
13164 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
13165 		mtx_unlock(&softc->ctl_lock);
13166 		goto bailout;
13167 	}
13168 	mtx_lock(&lun->lun_lock);
13169 	mtx_unlock(&softc->ctl_lock);
13170 
13171 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
13172 	p = initidx / CTL_MAX_INIT_PER_PORT;
13173 	if (lun->pending_sense[p] == NULL) {
13174 		lun->pending_sense[p] = malloc(sizeof(*ps) * CTL_MAX_INIT_PER_PORT,
13175 		    M_CTL, M_NOWAIT | M_ZERO);
13176 	}
13177 	if ((ps = lun->pending_sense[p]) != NULL) {
13178 		ps += initidx % CTL_MAX_INIT_PER_PORT;
13179 		memset(ps, 0, sizeof(*ps));
13180 		memcpy(ps, &io->scsiio.sense_data, io->scsiio.sense_len);
13181 	}
13182 	mtx_unlock(&lun->lun_lock);
13183 
13184 bailout:
13185 	ctl_free_io(io);
13186 	return (CTL_RETVAL_COMPLETE);
13187 }
13188 
13189 /*
13190  * Primary command inlet from frontend ports.  All SCSI and task I/O
13191  * requests must go through this function.
13192  */
13193 int
13194 ctl_queue(union ctl_io *io)
13195 {
13196 	struct ctl_port *port = CTL_PORT(io);
13197 
13198 	CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13199 
13200 #ifdef CTL_TIME_IO
13201 	io->io_hdr.start_time = time_uptime;
13202 	getbinuptime(&io->io_hdr.start_bt);
13203 #endif /* CTL_TIME_IO */
13204 
13205 	/* Map FE-specific LUN ID into global one. */
13206 	io->io_hdr.nexus.targ_mapped_lun =
13207 	    ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13208 
13209 	switch (io->io_hdr.io_type) {
13210 	case CTL_IO_SCSI:
13211 	case CTL_IO_TASK:
13212 		if (ctl_debug & CTL_DEBUG_CDB)
13213 			ctl_io_print(io);
13214 		ctl_enqueue_incoming(io);
13215 		break;
13216 	default:
13217 		printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13218 		return (EINVAL);
13219 	}
13220 
13221 	return (CTL_RETVAL_COMPLETE);
13222 }
13223 
13224 int
13225 ctl_run(union ctl_io *io)
13226 {
13227 	struct ctl_port *port = CTL_PORT(io);
13228 
13229 	CTL_DEBUG_PRINT(("ctl_run cdb[0]=%02X\n", io->scsiio.cdb[0]));
13230 
13231 #ifdef CTL_TIME_IO
13232 	io->io_hdr.start_time = time_uptime;
13233 	getbinuptime(&io->io_hdr.start_bt);
13234 #endif /* CTL_TIME_IO */
13235 
13236 	/* Map FE-specific LUN ID into global one. */
13237 	io->io_hdr.nexus.targ_mapped_lun =
13238 	    ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13239 
13240 	switch (io->io_hdr.io_type) {
13241 	case CTL_IO_SCSI:
13242 		if (ctl_debug & CTL_DEBUG_CDB)
13243 			ctl_io_print(io);
13244 		ctl_scsiio_precheck(&io->scsiio);
13245 		break;
13246 	case CTL_IO_TASK:
13247 		if (ctl_debug & CTL_DEBUG_CDB)
13248 			ctl_io_print(io);
13249 		ctl_run_task(io);
13250 		break;
13251 	default:
13252 		printf("ctl_run: unknown I/O type %d\n", io->io_hdr.io_type);
13253 		return (EINVAL);
13254 	}
13255 
13256 	return (CTL_RETVAL_COMPLETE);
13257 }
13258 
13259 #ifdef CTL_IO_DELAY
13260 static void
13261 ctl_done_timer_wakeup(void *arg)
13262 {
13263 	union ctl_io *io;
13264 
13265 	io = (union ctl_io *)arg;
13266 	ctl_done(io);
13267 }
13268 #endif /* CTL_IO_DELAY */
13269 
13270 void
13271 ctl_serseq_done(union ctl_io *io)
13272 {
13273 	struct ctl_lun *lun = CTL_LUN(io);
13274 
13275 	if (lun->be_lun->serseq == CTL_LUN_SERSEQ_OFF)
13276 		return;
13277 
13278 	/* This is racy, but should not be a problem. */
13279 	if (!TAILQ_EMPTY(&io->io_hdr.blocked_queue)) {
13280 		mtx_lock(&lun->lun_lock);
13281 		io->io_hdr.flags |= CTL_FLAG_SERSEQ_DONE;
13282 		ctl_try_unblock_others(lun, io, FALSE);
13283 		mtx_unlock(&lun->lun_lock);
13284 	} else
13285 		io->io_hdr.flags |= CTL_FLAG_SERSEQ_DONE;
13286 }
13287 
13288 void
13289 ctl_done(union ctl_io *io)
13290 {
13291 
13292 	/*
13293 	 * Enable this to catch duplicate completion issues.
13294 	 */
13295 #if 0
13296 	if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13297 		printf("%s: type %d msg %d cdb %x iptl: "
13298 		       "%u:%u:%u tag 0x%04x "
13299 		       "flag %#x status %x\n",
13300 			__func__,
13301 			io->io_hdr.io_type,
13302 			io->io_hdr.msg_type,
13303 			io->scsiio.cdb[0],
13304 			io->io_hdr.nexus.initid,
13305 			io->io_hdr.nexus.targ_port,
13306 			io->io_hdr.nexus.targ_lun,
13307 			(io->io_hdr.io_type ==
13308 			CTL_IO_TASK) ?
13309 			io->taskio.tag_num :
13310 			io->scsiio.tag_num,
13311 		        io->io_hdr.flags,
13312 			io->io_hdr.status);
13313 	} else
13314 		io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13315 #endif
13316 
13317 	/*
13318 	 * This is an internal copy of an I/O, and should not go through
13319 	 * the normal done processing logic.
13320 	 */
13321 	if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13322 		return;
13323 
13324 #ifdef CTL_IO_DELAY
13325 	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13326 		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13327 	} else {
13328 		struct ctl_lun *lun = CTL_LUN(io);
13329 
13330 		if ((lun != NULL)
13331 		 && (lun->delay_info.done_delay > 0)) {
13332 			callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
13333 			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
13334 			callout_reset(&io->io_hdr.delay_callout,
13335 				      lun->delay_info.done_delay * hz,
13336 				      ctl_done_timer_wakeup, io);
13337 			if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
13338 				lun->delay_info.done_delay = 0;
13339 			return;
13340 		}
13341 	}
13342 #endif /* CTL_IO_DELAY */
13343 
13344 	ctl_enqueue_done(io);
13345 }
13346 
13347 static void
13348 ctl_work_thread(void *arg)
13349 {
13350 	struct ctl_thread *thr = (struct ctl_thread *)arg;
13351 	struct ctl_softc *softc = thr->ctl_softc;
13352 	union ctl_io *io;
13353 	int retval;
13354 
13355 	CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
13356 	thread_lock(curthread);
13357 	sched_prio(curthread, PUSER - 1);
13358 	thread_unlock(curthread);
13359 
13360 	while (!softc->shutdown) {
13361 		/*
13362 		 * We handle the queues in this order:
13363 		 * - ISC
13364 		 * - done queue (to free up resources, unblock other commands)
13365 		 * - incoming queue
13366 		 * - RtR queue
13367 		 *
13368 		 * If those queues are empty, we break out of the loop and
13369 		 * go to sleep.
13370 		 */
13371 		mtx_lock(&thr->queue_lock);
13372 		io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
13373 		if (io != NULL) {
13374 			STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
13375 			mtx_unlock(&thr->queue_lock);
13376 			ctl_handle_isc(io);
13377 			continue;
13378 		}
13379 		io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
13380 		if (io != NULL) {
13381 			STAILQ_REMOVE_HEAD(&thr->done_queue, links);
13382 			/* clear any blocked commands, call fe_done */
13383 			mtx_unlock(&thr->queue_lock);
13384 			ctl_process_done(io);
13385 			continue;
13386 		}
13387 		io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
13388 		if (io != NULL) {
13389 			STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
13390 			mtx_unlock(&thr->queue_lock);
13391 			if (io->io_hdr.io_type == CTL_IO_TASK)
13392 				ctl_run_task(io);
13393 			else
13394 				ctl_scsiio_precheck(&io->scsiio);
13395 			continue;
13396 		}
13397 		io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
13398 		if (io != NULL) {
13399 			STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
13400 			mtx_unlock(&thr->queue_lock);
13401 			retval = ctl_scsiio(&io->scsiio);
13402 			if (retval != CTL_RETVAL_COMPLETE)
13403 				CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
13404 			continue;
13405 		}
13406 
13407 		/* Sleep until we have something to do. */
13408 		mtx_sleep(thr, &thr->queue_lock, PDROP, "-", 0);
13409 	}
13410 	thr->thread = NULL;
13411 	kthread_exit();
13412 }
13413 
13414 static void
13415 ctl_thresh_thread(void *arg)
13416 {
13417 	struct ctl_softc *softc = (struct ctl_softc *)arg;
13418 	struct ctl_lun *lun;
13419 	struct ctl_logical_block_provisioning_page *page;
13420 	const char *attr;
13421 	union ctl_ha_msg msg;
13422 	uint64_t thres, val;
13423 	int i, e, set;
13424 
13425 	CTL_DEBUG_PRINT(("ctl_thresh_thread starting\n"));
13426 	thread_lock(curthread);
13427 	sched_prio(curthread, PUSER - 1);
13428 	thread_unlock(curthread);
13429 
13430 	while (!softc->shutdown) {
13431 		mtx_lock(&softc->ctl_lock);
13432 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
13433 			if ((lun->flags & CTL_LUN_DISABLED) ||
13434 			    (lun->flags & CTL_LUN_NO_MEDIA) ||
13435 			    lun->backend->lun_attr == NULL)
13436 				continue;
13437 			if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
13438 			    softc->ha_mode == CTL_HA_MODE_XFER)
13439 				continue;
13440 			if ((lun->MODE_RWER.byte8 & SMS_RWER_LBPERE) == 0)
13441 				continue;
13442 			e = 0;
13443 			page = &lun->MODE_LBP;
13444 			for (i = 0; i < CTL_NUM_LBP_THRESH; i++) {
13445 				if ((page->descr[i].flags & SLBPPD_ENABLED) == 0)
13446 					continue;
13447 				thres = scsi_4btoul(page->descr[i].count);
13448 				thres <<= CTL_LBP_EXPONENT;
13449 				switch (page->descr[i].resource) {
13450 				case 0x01:
13451 					attr = "blocksavail";
13452 					break;
13453 				case 0x02:
13454 					attr = "blocksused";
13455 					break;
13456 				case 0xf1:
13457 					attr = "poolblocksavail";
13458 					break;
13459 				case 0xf2:
13460 					attr = "poolblocksused";
13461 					break;
13462 				default:
13463 					continue;
13464 				}
13465 				mtx_unlock(&softc->ctl_lock); // XXX
13466 				val = lun->backend->lun_attr(lun->be_lun, attr);
13467 				mtx_lock(&softc->ctl_lock);
13468 				if (val == UINT64_MAX)
13469 					continue;
13470 				if ((page->descr[i].flags & SLBPPD_ARMING_MASK)
13471 				    == SLBPPD_ARMING_INC)
13472 					e = (val >= thres);
13473 				else
13474 					e = (val <= thres);
13475 				if (e)
13476 					break;
13477 			}
13478 			mtx_lock(&lun->lun_lock);
13479 			if (e) {
13480 				scsi_u64to8b((uint8_t *)&page->descr[i] -
13481 				    (uint8_t *)page, lun->ua_tpt_info);
13482 				if (lun->lasttpt == 0 ||
13483 				    time_uptime - lun->lasttpt >= CTL_LBP_UA_PERIOD) {
13484 					lun->lasttpt = time_uptime;
13485 					ctl_est_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13486 					set = 1;
13487 				} else
13488 					set = 0;
13489 			} else {
13490 				lun->lasttpt = 0;
13491 				ctl_clr_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13492 				set = -1;
13493 			}
13494 			mtx_unlock(&lun->lun_lock);
13495 			if (set != 0 &&
13496 			    lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
13497 				/* Send msg to other side. */
13498 				bzero(&msg.ua, sizeof(msg.ua));
13499 				msg.hdr.msg_type = CTL_MSG_UA;
13500 				msg.hdr.nexus.initid = -1;
13501 				msg.hdr.nexus.targ_port = -1;
13502 				msg.hdr.nexus.targ_lun = lun->lun;
13503 				msg.hdr.nexus.targ_mapped_lun = lun->lun;
13504 				msg.ua.ua_all = 1;
13505 				msg.ua.ua_set = (set > 0);
13506 				msg.ua.ua_type = CTL_UA_THIN_PROV_THRES;
13507 				memcpy(msg.ua.ua_info, lun->ua_tpt_info, 8);
13508 				mtx_unlock(&softc->ctl_lock); // XXX
13509 				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13510 				    sizeof(msg.ua), M_WAITOK);
13511 				mtx_lock(&softc->ctl_lock);
13512 			}
13513 		}
13514 		mtx_sleep(&softc->thresh_thread, &softc->ctl_lock,
13515 		    PDROP, "-", CTL_LBP_PERIOD * hz);
13516 	}
13517 	softc->thresh_thread = NULL;
13518 	kthread_exit();
13519 }
13520 
13521 static void
13522 ctl_enqueue_incoming(union ctl_io *io)
13523 {
13524 	struct ctl_softc *softc = CTL_SOFTC(io);
13525 	struct ctl_thread *thr;
13526 	u_int idx;
13527 
13528 	idx = (io->io_hdr.nexus.targ_port * 127 +
13529 	       io->io_hdr.nexus.initid) % worker_threads;
13530 	thr = &softc->threads[idx];
13531 	mtx_lock(&thr->queue_lock);
13532 	STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
13533 	mtx_unlock(&thr->queue_lock);
13534 	wakeup(thr);
13535 }
13536 
13537 static void
13538 ctl_enqueue_rtr(union ctl_io *io)
13539 {
13540 	struct ctl_softc *softc = CTL_SOFTC(io);
13541 	struct ctl_thread *thr;
13542 
13543 	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13544 	mtx_lock(&thr->queue_lock);
13545 	STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
13546 	mtx_unlock(&thr->queue_lock);
13547 	wakeup(thr);
13548 }
13549 
13550 static void
13551 ctl_enqueue_done(union ctl_io *io)
13552 {
13553 	struct ctl_softc *softc = CTL_SOFTC(io);
13554 	struct ctl_thread *thr;
13555 
13556 	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13557 	mtx_lock(&thr->queue_lock);
13558 	STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
13559 	mtx_unlock(&thr->queue_lock);
13560 	wakeup(thr);
13561 }
13562 
13563 static void
13564 ctl_enqueue_isc(union ctl_io *io)
13565 {
13566 	struct ctl_softc *softc = CTL_SOFTC(io);
13567 	struct ctl_thread *thr;
13568 
13569 	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13570 	mtx_lock(&thr->queue_lock);
13571 	STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
13572 	mtx_unlock(&thr->queue_lock);
13573 	wakeup(thr);
13574 }
13575 
13576 /*
13577  *  vim: ts=8
13578  */
13579