xref: /freebsd/sys/cam/ctl/ctl.c (revision 732a02b4e77866604a120a275c082bb6221bd2ff)
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_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
473 			 struct ctl_be_lun *be_lun);
474 static int ctl_free_lun(struct ctl_lun *lun);
475 static void ctl_create_lun(struct ctl_be_lun *be_lun);
476 
477 static int ctl_do_mode_select(union ctl_io *io);
478 static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
479 			   uint64_t res_key, uint64_t sa_res_key,
480 			   uint8_t type, uint32_t residx,
481 			   struct ctl_scsiio *ctsio,
482 			   struct scsi_per_res_out *cdb,
483 			   struct scsi_per_res_out_parms* param);
484 static void ctl_pro_preempt_other(struct ctl_lun *lun,
485 				  union ctl_ha_msg *msg);
486 static void ctl_hndl_per_res_out_on_other_sc(union ctl_io *io);
487 static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
488 static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
489 static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
490 static int ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len);
491 static int ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len);
492 static int ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio,
493 					 int alloc_len);
494 static int ctl_inquiry_evpd_sfs(struct ctl_scsiio *ctsio, int alloc_len);
495 static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
496 					 int alloc_len);
497 static int ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len);
498 static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
499 static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
500 static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
501 static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len);
502 static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2,
503     bool seq);
504 static ctl_action ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2);
505 static ctl_action ctl_check_for_blockage(struct ctl_lun *lun,
506     union ctl_io *pending_io, 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 int ctl_scsiio_precheck(struct ctl_softc *ctl_softc,
518 			       struct ctl_scsiio *ctsio);
519 static int ctl_scsiio(struct ctl_scsiio *ctsio);
520 
521 static int ctl_target_reset(union ctl_io *io);
522 static void ctl_do_lun_reset(struct ctl_lun *lun, uint32_t initidx,
523 			 ctl_ua_type ua_type);
524 static int ctl_lun_reset(union ctl_io *io);
525 static int ctl_abort_task(union ctl_io *io);
526 static int ctl_abort_task_set(union ctl_io *io);
527 static int ctl_query_task(union ctl_io *io, int task_set);
528 static void ctl_i_t_nexus_loss(struct ctl_softc *softc, uint32_t initidx,
529 			      ctl_ua_type ua_type);
530 static int ctl_i_t_nexus_reset(union ctl_io *io);
531 static int ctl_query_async_event(union ctl_io *io);
532 static void ctl_run_task(union ctl_io *io);
533 #ifdef CTL_IO_DELAY
534 static void ctl_datamove_timer_wakeup(void *arg);
535 static void ctl_done_timer_wakeup(void *arg);
536 #endif /* CTL_IO_DELAY */
537 
538 static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
539 static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
540 static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
541 static void ctl_datamove_remote_write(union ctl_io *io);
542 static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
543 static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
544 static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
545 static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
546 				    ctl_ha_dt_cb callback);
547 static void ctl_datamove_remote_read(union ctl_io *io);
548 static void ctl_datamove_remote(union ctl_io *io);
549 static void ctl_process_done(union ctl_io *io);
550 static void ctl_lun_thread(void *arg);
551 static void ctl_thresh_thread(void *arg);
552 static void ctl_work_thread(void *arg);
553 static void ctl_enqueue_incoming(union ctl_io *io);
554 static void ctl_enqueue_rtr(union ctl_io *io);
555 static void ctl_enqueue_done(union ctl_io *io);
556 static void ctl_enqueue_isc(union ctl_io *io);
557 static const struct ctl_cmd_entry *
558     ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa);
559 static const struct ctl_cmd_entry *
560     ctl_validate_command(struct ctl_scsiio *ctsio);
561 static int ctl_cmd_applicable(uint8_t lun_type,
562     const struct ctl_cmd_entry *entry);
563 static int ctl_ha_init(void);
564 static int ctl_ha_shutdown(void);
565 
566 static uint64_t ctl_get_prkey(struct ctl_lun *lun, uint32_t residx);
567 static void ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx);
568 static void ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx);
569 static void ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key);
570 
571 /*
572  * Load the serialization table.  This isn't very pretty, but is probably
573  * the easiest way to do it.
574  */
575 #include "ctl_ser_table.c"
576 
577 /*
578  * We only need to define open, close and ioctl routines for this driver.
579  */
580 static struct cdevsw ctl_cdevsw = {
581 	.d_version =	D_VERSION,
582 	.d_flags =	0,
583 	.d_open =	ctl_open,
584 	.d_close =	ctl_close,
585 	.d_ioctl =	ctl_ioctl,
586 	.d_name =	"ctl",
587 };
588 
589 
590 MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
591 
592 static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
593 
594 static moduledata_t ctl_moduledata = {
595 	"ctl",
596 	ctl_module_event_handler,
597 	NULL
598 };
599 
600 DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
601 MODULE_VERSION(ctl, 1);
602 
603 static struct ctl_frontend ha_frontend =
604 {
605 	.name = "ha",
606 	.init = ctl_ha_init,
607 	.shutdown = ctl_ha_shutdown,
608 };
609 
610 static int
611 ctl_ha_init(void)
612 {
613 	struct ctl_softc *softc = control_softc;
614 
615 	if (ctl_pool_create(softc, "othersc", CTL_POOL_ENTRIES_OTHER_SC,
616 	                    &softc->othersc_pool) != 0)
617 		return (ENOMEM);
618 	if (ctl_ha_msg_init(softc) != CTL_HA_STATUS_SUCCESS) {
619 		ctl_pool_free(softc->othersc_pool);
620 		return (EIO);
621 	}
622 	if (ctl_ha_msg_register(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
623 	    != CTL_HA_STATUS_SUCCESS) {
624 		ctl_ha_msg_destroy(softc);
625 		ctl_pool_free(softc->othersc_pool);
626 		return (EIO);
627 	}
628 	return (0);
629 };
630 
631 static int
632 ctl_ha_shutdown(void)
633 {
634 	struct ctl_softc *softc = control_softc;
635 	struct ctl_port *port;
636 
637 	ctl_ha_msg_shutdown(softc);
638 	if (ctl_ha_msg_deregister(CTL_HA_CHAN_CTL) != CTL_HA_STATUS_SUCCESS)
639 		return (EIO);
640 	if (ctl_ha_msg_destroy(softc) != CTL_HA_STATUS_SUCCESS)
641 		return (EIO);
642 	ctl_pool_free(softc->othersc_pool);
643 	while ((port = STAILQ_FIRST(&ha_frontend.port_list)) != NULL) {
644 		ctl_port_deregister(port);
645 		free(port->port_name, M_CTL);
646 		free(port, M_CTL);
647 	}
648 	return (0);
649 };
650 
651 static void
652 ctl_ha_datamove(union ctl_io *io)
653 {
654 	struct ctl_lun *lun = CTL_LUN(io);
655 	struct ctl_sg_entry *sgl;
656 	union ctl_ha_msg msg;
657 	uint32_t sg_entries_sent;
658 	int do_sg_copy, i, j;
659 
660 	memset(&msg.dt, 0, sizeof(msg.dt));
661 	msg.hdr.msg_type = CTL_MSG_DATAMOVE;
662 	msg.hdr.original_sc = io->io_hdr.remote_io;
663 	msg.hdr.serializing_sc = io;
664 	msg.hdr.nexus = io->io_hdr.nexus;
665 	msg.hdr.status = io->io_hdr.status;
666 	msg.dt.flags = io->io_hdr.flags;
667 
668 	/*
669 	 * We convert everything into a S/G list here.  We can't
670 	 * pass by reference, only by value between controllers.
671 	 * So we can't pass a pointer to the S/G list, only as many
672 	 * S/G entries as we can fit in here.  If it's possible for
673 	 * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
674 	 * then we need to break this up into multiple transfers.
675 	 */
676 	if (io->scsiio.kern_sg_entries == 0) {
677 		msg.dt.kern_sg_entries = 1;
678 #if 0
679 		if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
680 			msg.dt.sg_list[0].addr = io->scsiio.kern_data_ptr;
681 		} else {
682 			/* XXX KDM use busdma here! */
683 			msg.dt.sg_list[0].addr =
684 			    (void *)vtophys(io->scsiio.kern_data_ptr);
685 		}
686 #else
687 		KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
688 		    ("HA does not support BUS_ADDR"));
689 		msg.dt.sg_list[0].addr = io->scsiio.kern_data_ptr;
690 #endif
691 		msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
692 		do_sg_copy = 0;
693 	} else {
694 		msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
695 		do_sg_copy = 1;
696 	}
697 
698 	msg.dt.kern_data_len = io->scsiio.kern_data_len;
699 	msg.dt.kern_total_len = io->scsiio.kern_total_len;
700 	msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
701 	msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
702 	msg.dt.sg_sequence = 0;
703 
704 	/*
705 	 * Loop until we've sent all of the S/G entries.  On the
706 	 * other end, we'll recompose these S/G entries into one
707 	 * contiguous list before processing.
708 	 */
709 	for (sg_entries_sent = 0; sg_entries_sent < msg.dt.kern_sg_entries;
710 	    msg.dt.sg_sequence++) {
711 		msg.dt.cur_sg_entries = MIN((sizeof(msg.dt.sg_list) /
712 		    sizeof(msg.dt.sg_list[0])),
713 		    msg.dt.kern_sg_entries - sg_entries_sent);
714 		if (do_sg_copy != 0) {
715 			sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
716 			for (i = sg_entries_sent, j = 0;
717 			     i < msg.dt.cur_sg_entries; i++, j++) {
718 #if 0
719 				if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
720 					msg.dt.sg_list[j].addr = sgl[i].addr;
721 				} else {
722 					/* XXX KDM use busdma here! */
723 					msg.dt.sg_list[j].addr =
724 					    (void *)vtophys(sgl[i].addr);
725 				}
726 #else
727 				KASSERT((io->io_hdr.flags &
728 				    CTL_FLAG_BUS_ADDR) == 0,
729 				    ("HA does not support BUS_ADDR"));
730 				msg.dt.sg_list[j].addr = sgl[i].addr;
731 #endif
732 				msg.dt.sg_list[j].len = sgl[i].len;
733 			}
734 		}
735 
736 		sg_entries_sent += msg.dt.cur_sg_entries;
737 		msg.dt.sg_last = (sg_entries_sent >= msg.dt.kern_sg_entries);
738 		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
739 		    sizeof(msg.dt) - sizeof(msg.dt.sg_list) +
740 		    sizeof(struct ctl_sg_entry) * msg.dt.cur_sg_entries,
741 		    M_WAITOK) > CTL_HA_STATUS_SUCCESS) {
742 			io->io_hdr.port_status = 31341;
743 			io->scsiio.be_move_done(io);
744 			return;
745 		}
746 		msg.dt.sent_sg_entries = sg_entries_sent;
747 	}
748 
749 	/*
750 	 * Officially handover the request from us to peer.
751 	 * If failover has just happened, then we must return error.
752 	 * If failover happen just after, then it is not our problem.
753 	 */
754 	if (lun)
755 		mtx_lock(&lun->lun_lock);
756 	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
757 		if (lun)
758 			mtx_unlock(&lun->lun_lock);
759 		io->io_hdr.port_status = 31342;
760 		io->scsiio.be_move_done(io);
761 		return;
762 	}
763 	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
764 	io->io_hdr.flags |= CTL_FLAG_DMA_INPROG;
765 	if (lun)
766 		mtx_unlock(&lun->lun_lock);
767 }
768 
769 static void
770 ctl_ha_done(union ctl_io *io)
771 {
772 	union ctl_ha_msg msg;
773 
774 	if (io->io_hdr.io_type == CTL_IO_SCSI) {
775 		memset(&msg, 0, sizeof(msg));
776 		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
777 		msg.hdr.original_sc = io->io_hdr.remote_io;
778 		msg.hdr.nexus = io->io_hdr.nexus;
779 		msg.hdr.status = io->io_hdr.status;
780 		msg.scsi.scsi_status = io->scsiio.scsi_status;
781 		msg.scsi.tag_num = io->scsiio.tag_num;
782 		msg.scsi.tag_type = io->scsiio.tag_type;
783 		msg.scsi.sense_len = io->scsiio.sense_len;
784 		memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
785 		    io->scsiio.sense_len);
786 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
787 		    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
788 		    msg.scsi.sense_len, M_WAITOK);
789 	}
790 	ctl_free_io(io);
791 }
792 
793 static void
794 ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
795 			    union ctl_ha_msg *msg_info)
796 {
797 	struct ctl_scsiio *ctsio;
798 
799 	if (msg_info->hdr.original_sc == NULL) {
800 		printf("%s: original_sc == NULL!\n", __func__);
801 		/* XXX KDM now what? */
802 		return;
803 	}
804 
805 	ctsio = &msg_info->hdr.original_sc->scsiio;
806 	ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
807 	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
808 	ctsio->io_hdr.status = msg_info->hdr.status;
809 	ctsio->scsi_status = msg_info->scsi.scsi_status;
810 	ctsio->sense_len = msg_info->scsi.sense_len;
811 	memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
812 	       msg_info->scsi.sense_len);
813 	ctl_enqueue_isc((union ctl_io *)ctsio);
814 }
815 
816 static void
817 ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
818 				union ctl_ha_msg *msg_info)
819 {
820 	struct ctl_scsiio *ctsio;
821 
822 	if (msg_info->hdr.serializing_sc == NULL) {
823 		printf("%s: serializing_sc == NULL!\n", __func__);
824 		/* XXX KDM now what? */
825 		return;
826 	}
827 
828 	ctsio = &msg_info->hdr.serializing_sc->scsiio;
829 	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
830 	ctl_enqueue_isc((union ctl_io *)ctsio);
831 }
832 
833 void
834 ctl_isc_announce_lun(struct ctl_lun *lun)
835 {
836 	struct ctl_softc *softc = lun->ctl_softc;
837 	union ctl_ha_msg *msg;
838 	struct ctl_ha_msg_lun_pr_key pr_key;
839 	int i, k;
840 
841 	if (softc->ha_link != CTL_HA_LINK_ONLINE)
842 		return;
843 	mtx_lock(&lun->lun_lock);
844 	i = sizeof(msg->lun);
845 	if (lun->lun_devid)
846 		i += lun->lun_devid->len;
847 	i += sizeof(pr_key) * lun->pr_key_count;
848 alloc:
849 	mtx_unlock(&lun->lun_lock);
850 	msg = malloc(i, M_CTL, M_WAITOK);
851 	mtx_lock(&lun->lun_lock);
852 	k = sizeof(msg->lun);
853 	if (lun->lun_devid)
854 		k += lun->lun_devid->len;
855 	k += sizeof(pr_key) * lun->pr_key_count;
856 	if (i < k) {
857 		free(msg, M_CTL);
858 		i = k;
859 		goto alloc;
860 	}
861 	bzero(&msg->lun, sizeof(msg->lun));
862 	msg->hdr.msg_type = CTL_MSG_LUN_SYNC;
863 	msg->hdr.nexus.targ_lun = lun->lun;
864 	msg->hdr.nexus.targ_mapped_lun = lun->lun;
865 	msg->lun.flags = lun->flags;
866 	msg->lun.pr_generation = lun->pr_generation;
867 	msg->lun.pr_res_idx = lun->pr_res_idx;
868 	msg->lun.pr_res_type = lun->pr_res_type;
869 	msg->lun.pr_key_count = lun->pr_key_count;
870 	i = 0;
871 	if (lun->lun_devid) {
872 		msg->lun.lun_devid_len = lun->lun_devid->len;
873 		memcpy(&msg->lun.data[i], lun->lun_devid->data,
874 		    msg->lun.lun_devid_len);
875 		i += msg->lun.lun_devid_len;
876 	}
877 	for (k = 0; k < CTL_MAX_INITIATORS; k++) {
878 		if ((pr_key.pr_key = ctl_get_prkey(lun, k)) == 0)
879 			continue;
880 		pr_key.pr_iid = k;
881 		memcpy(&msg->lun.data[i], &pr_key, sizeof(pr_key));
882 		i += sizeof(pr_key);
883 	}
884 	mtx_unlock(&lun->lun_lock);
885 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->port, sizeof(msg->port) + i,
886 	    M_WAITOK);
887 	free(msg, M_CTL);
888 
889 	if (lun->flags & CTL_LUN_PRIMARY_SC) {
890 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
891 			ctl_isc_announce_mode(lun, -1,
892 			    lun->mode_pages.index[i].page_code & SMPH_PC_MASK,
893 			    lun->mode_pages.index[i].subpage);
894 		}
895 	}
896 }
897 
898 void
899 ctl_isc_announce_port(struct ctl_port *port)
900 {
901 	struct ctl_softc *softc = port->ctl_softc;
902 	union ctl_ha_msg *msg;
903 	int i;
904 
905 	if (port->targ_port < softc->port_min ||
906 	    port->targ_port >= softc->port_max ||
907 	    softc->ha_link != CTL_HA_LINK_ONLINE)
908 		return;
909 	i = sizeof(msg->port) + strlen(port->port_name) + 1;
910 	if (port->lun_map)
911 		i += port->lun_map_size * sizeof(uint32_t);
912 	if (port->port_devid)
913 		i += port->port_devid->len;
914 	if (port->target_devid)
915 		i += port->target_devid->len;
916 	if (port->init_devid)
917 		i += port->init_devid->len;
918 	msg = malloc(i, M_CTL, M_WAITOK);
919 	bzero(&msg->port, sizeof(msg->port));
920 	msg->hdr.msg_type = CTL_MSG_PORT_SYNC;
921 	msg->hdr.nexus.targ_port = port->targ_port;
922 	msg->port.port_type = port->port_type;
923 	msg->port.physical_port = port->physical_port;
924 	msg->port.virtual_port = port->virtual_port;
925 	msg->port.status = port->status;
926 	i = 0;
927 	msg->port.name_len = sprintf(&msg->port.data[i],
928 	    "%d:%s", softc->ha_id, port->port_name) + 1;
929 	i += msg->port.name_len;
930 	if (port->lun_map) {
931 		msg->port.lun_map_len = port->lun_map_size * sizeof(uint32_t);
932 		memcpy(&msg->port.data[i], port->lun_map,
933 		    msg->port.lun_map_len);
934 		i += msg->port.lun_map_len;
935 	}
936 	if (port->port_devid) {
937 		msg->port.port_devid_len = port->port_devid->len;
938 		memcpy(&msg->port.data[i], port->port_devid->data,
939 		    msg->port.port_devid_len);
940 		i += msg->port.port_devid_len;
941 	}
942 	if (port->target_devid) {
943 		msg->port.target_devid_len = port->target_devid->len;
944 		memcpy(&msg->port.data[i], port->target_devid->data,
945 		    msg->port.target_devid_len);
946 		i += msg->port.target_devid_len;
947 	}
948 	if (port->init_devid) {
949 		msg->port.init_devid_len = port->init_devid->len;
950 		memcpy(&msg->port.data[i], port->init_devid->data,
951 		    msg->port.init_devid_len);
952 		i += msg->port.init_devid_len;
953 	}
954 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->port, sizeof(msg->port) + i,
955 	    M_WAITOK);
956 	free(msg, M_CTL);
957 }
958 
959 void
960 ctl_isc_announce_iid(struct ctl_port *port, int iid)
961 {
962 	struct ctl_softc *softc = port->ctl_softc;
963 	union ctl_ha_msg *msg;
964 	int i, l;
965 
966 	if (port->targ_port < softc->port_min ||
967 	    port->targ_port >= softc->port_max ||
968 	    softc->ha_link != CTL_HA_LINK_ONLINE)
969 		return;
970 	mtx_lock(&softc->ctl_lock);
971 	i = sizeof(msg->iid);
972 	l = 0;
973 	if (port->wwpn_iid[iid].name)
974 		l = strlen(port->wwpn_iid[iid].name) + 1;
975 	i += l;
976 	msg = malloc(i, M_CTL, M_NOWAIT);
977 	if (msg == NULL) {
978 		mtx_unlock(&softc->ctl_lock);
979 		return;
980 	}
981 	bzero(&msg->iid, sizeof(msg->iid));
982 	msg->hdr.msg_type = CTL_MSG_IID_SYNC;
983 	msg->hdr.nexus.targ_port = port->targ_port;
984 	msg->hdr.nexus.initid = iid;
985 	msg->iid.in_use = port->wwpn_iid[iid].in_use;
986 	msg->iid.name_len = l;
987 	msg->iid.wwpn = port->wwpn_iid[iid].wwpn;
988 	if (port->wwpn_iid[iid].name)
989 		strlcpy(msg->iid.data, port->wwpn_iid[iid].name, l);
990 	mtx_unlock(&softc->ctl_lock);
991 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->iid, i, M_NOWAIT);
992 	free(msg, M_CTL);
993 }
994 
995 void
996 ctl_isc_announce_mode(struct ctl_lun *lun, uint32_t initidx,
997     uint8_t page, uint8_t subpage)
998 {
999 	struct ctl_softc *softc = lun->ctl_softc;
1000 	union ctl_ha_msg msg;
1001 	u_int i;
1002 
1003 	if (softc->ha_link != CTL_HA_LINK_ONLINE)
1004 		return;
1005 	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
1006 		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) ==
1007 		    page && lun->mode_pages.index[i].subpage == subpage)
1008 			break;
1009 	}
1010 	if (i == CTL_NUM_MODE_PAGES)
1011 		return;
1012 
1013 	/* Don't try to replicate pages not present on this device. */
1014 	if (lun->mode_pages.index[i].page_data == NULL)
1015 		return;
1016 
1017 	bzero(&msg.mode, sizeof(msg.mode));
1018 	msg.hdr.msg_type = CTL_MSG_MODE_SYNC;
1019 	msg.hdr.nexus.targ_port = initidx / CTL_MAX_INIT_PER_PORT;
1020 	msg.hdr.nexus.initid = initidx % CTL_MAX_INIT_PER_PORT;
1021 	msg.hdr.nexus.targ_lun = lun->lun;
1022 	msg.hdr.nexus.targ_mapped_lun = lun->lun;
1023 	msg.mode.page_code = page;
1024 	msg.mode.subpage = subpage;
1025 	msg.mode.page_len = lun->mode_pages.index[i].page_len;
1026 	memcpy(msg.mode.data, lun->mode_pages.index[i].page_data,
1027 	    msg.mode.page_len);
1028 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg.mode, sizeof(msg.mode),
1029 	    M_WAITOK);
1030 }
1031 
1032 static void
1033 ctl_isc_ha_link_up(struct ctl_softc *softc)
1034 {
1035 	struct ctl_port *port;
1036 	struct ctl_lun *lun;
1037 	union ctl_ha_msg msg;
1038 	int i;
1039 
1040 	/* Announce this node parameters to peer for validation. */
1041 	msg.login.msg_type = CTL_MSG_LOGIN;
1042 	msg.login.version = CTL_HA_VERSION;
1043 	msg.login.ha_mode = softc->ha_mode;
1044 	msg.login.ha_id = softc->ha_id;
1045 	msg.login.max_luns = ctl_max_luns;
1046 	msg.login.max_ports = ctl_max_ports;
1047 	msg.login.max_init_per_port = CTL_MAX_INIT_PER_PORT;
1048 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg.login, sizeof(msg.login),
1049 	    M_WAITOK);
1050 
1051 	STAILQ_FOREACH(port, &softc->port_list, links) {
1052 		ctl_isc_announce_port(port);
1053 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1054 			if (port->wwpn_iid[i].in_use)
1055 				ctl_isc_announce_iid(port, i);
1056 		}
1057 	}
1058 	STAILQ_FOREACH(lun, &softc->lun_list, links)
1059 		ctl_isc_announce_lun(lun);
1060 }
1061 
1062 static void
1063 ctl_isc_ha_link_down(struct ctl_softc *softc)
1064 {
1065 	struct ctl_port *port;
1066 	struct ctl_lun *lun;
1067 	union ctl_io *io;
1068 	int i;
1069 
1070 	mtx_lock(&softc->ctl_lock);
1071 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
1072 		mtx_lock(&lun->lun_lock);
1073 		if (lun->flags & CTL_LUN_PEER_SC_PRIMARY) {
1074 			lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
1075 			ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
1076 		}
1077 		mtx_unlock(&lun->lun_lock);
1078 
1079 		mtx_unlock(&softc->ctl_lock);
1080 		io = ctl_alloc_io(softc->othersc_pool);
1081 		mtx_lock(&softc->ctl_lock);
1082 		ctl_zero_io(io);
1083 		io->io_hdr.msg_type = CTL_MSG_FAILOVER;
1084 		io->io_hdr.nexus.targ_mapped_lun = lun->lun;
1085 		ctl_enqueue_isc(io);
1086 	}
1087 
1088 	STAILQ_FOREACH(port, &softc->port_list, links) {
1089 		if (port->targ_port >= softc->port_min &&
1090 		    port->targ_port < softc->port_max)
1091 			continue;
1092 		port->status &= ~CTL_PORT_STATUS_ONLINE;
1093 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1094 			port->wwpn_iid[i].in_use = 0;
1095 			free(port->wwpn_iid[i].name, M_CTL);
1096 			port->wwpn_iid[i].name = NULL;
1097 		}
1098 	}
1099 	mtx_unlock(&softc->ctl_lock);
1100 }
1101 
1102 static void
1103 ctl_isc_ua(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1104 {
1105 	struct ctl_lun *lun;
1106 	uint32_t iid = ctl_get_initindex(&msg->hdr.nexus);
1107 
1108 	mtx_lock(&softc->ctl_lock);
1109 	if (msg->hdr.nexus.targ_mapped_lun >= ctl_max_luns ||
1110 	    (lun = softc->ctl_luns[msg->hdr.nexus.targ_mapped_lun]) == NULL) {
1111 		mtx_unlock(&softc->ctl_lock);
1112 		return;
1113 	}
1114 	mtx_lock(&lun->lun_lock);
1115 	mtx_unlock(&softc->ctl_lock);
1116 	if (msg->ua.ua_type == CTL_UA_THIN_PROV_THRES && msg->ua.ua_set)
1117 		memcpy(lun->ua_tpt_info, msg->ua.ua_info, 8);
1118 	if (msg->ua.ua_all) {
1119 		if (msg->ua.ua_set)
1120 			ctl_est_ua_all(lun, iid, msg->ua.ua_type);
1121 		else
1122 			ctl_clr_ua_all(lun, iid, msg->ua.ua_type);
1123 	} else {
1124 		if (msg->ua.ua_set)
1125 			ctl_est_ua(lun, iid, msg->ua.ua_type);
1126 		else
1127 			ctl_clr_ua(lun, iid, msg->ua.ua_type);
1128 	}
1129 	mtx_unlock(&lun->lun_lock);
1130 }
1131 
1132 static void
1133 ctl_isc_lun_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1134 {
1135 	struct ctl_lun *lun;
1136 	struct ctl_ha_msg_lun_pr_key pr_key;
1137 	int i, k;
1138 	ctl_lun_flags oflags;
1139 	uint32_t targ_lun;
1140 
1141 	targ_lun = msg->hdr.nexus.targ_mapped_lun;
1142 	mtx_lock(&softc->ctl_lock);
1143 	if (targ_lun >= ctl_max_luns ||
1144 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
1145 		mtx_unlock(&softc->ctl_lock);
1146 		return;
1147 	}
1148 	mtx_lock(&lun->lun_lock);
1149 	mtx_unlock(&softc->ctl_lock);
1150 	if (lun->flags & CTL_LUN_DISABLED) {
1151 		mtx_unlock(&lun->lun_lock);
1152 		return;
1153 	}
1154 	i = (lun->lun_devid != NULL) ? lun->lun_devid->len : 0;
1155 	if (msg->lun.lun_devid_len != i || (i > 0 &&
1156 	    memcmp(&msg->lun.data[0], lun->lun_devid->data, i) != 0)) {
1157 		mtx_unlock(&lun->lun_lock);
1158 		printf("%s: Received conflicting HA LUN %d\n",
1159 		    __func__, targ_lun);
1160 		return;
1161 	} else {
1162 		/* Record whether peer is primary. */
1163 		oflags = lun->flags;
1164 		if ((msg->lun.flags & CTL_LUN_PRIMARY_SC) &&
1165 		    (msg->lun.flags & CTL_LUN_DISABLED) == 0)
1166 			lun->flags |= CTL_LUN_PEER_SC_PRIMARY;
1167 		else
1168 			lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
1169 		if (oflags != lun->flags)
1170 			ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
1171 
1172 		/* If peer is primary and we are not -- use data */
1173 		if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
1174 		    (lun->flags & CTL_LUN_PEER_SC_PRIMARY)) {
1175 			lun->pr_generation = msg->lun.pr_generation;
1176 			lun->pr_res_idx = msg->lun.pr_res_idx;
1177 			lun->pr_res_type = msg->lun.pr_res_type;
1178 			lun->pr_key_count = msg->lun.pr_key_count;
1179 			for (k = 0; k < CTL_MAX_INITIATORS; k++)
1180 				ctl_clr_prkey(lun, k);
1181 			for (k = 0; k < msg->lun.pr_key_count; k++) {
1182 				memcpy(&pr_key, &msg->lun.data[i],
1183 				    sizeof(pr_key));
1184 				ctl_alloc_prkey(lun, pr_key.pr_iid);
1185 				ctl_set_prkey(lun, pr_key.pr_iid,
1186 				    pr_key.pr_key);
1187 				i += sizeof(pr_key);
1188 			}
1189 		}
1190 
1191 		mtx_unlock(&lun->lun_lock);
1192 		CTL_DEBUG_PRINT(("%s: Known LUN %d, peer is %s\n",
1193 		    __func__, targ_lun,
1194 		    (msg->lun.flags & CTL_LUN_PRIMARY_SC) ?
1195 		    "primary" : "secondary"));
1196 
1197 		/* If we are primary but peer doesn't know -- notify */
1198 		if ((lun->flags & CTL_LUN_PRIMARY_SC) &&
1199 		    (msg->lun.flags & CTL_LUN_PEER_SC_PRIMARY) == 0)
1200 			ctl_isc_announce_lun(lun);
1201 	}
1202 }
1203 
1204 static void
1205 ctl_isc_port_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1206 {
1207 	struct ctl_port *port;
1208 	struct ctl_lun *lun;
1209 	int i, new;
1210 
1211 	port = softc->ctl_ports[msg->hdr.nexus.targ_port];
1212 	if (port == NULL) {
1213 		CTL_DEBUG_PRINT(("%s: New port %d\n", __func__,
1214 		    msg->hdr.nexus.targ_port));
1215 		new = 1;
1216 		port = malloc(sizeof(*port), M_CTL, M_WAITOK | M_ZERO);
1217 		port->frontend = &ha_frontend;
1218 		port->targ_port = msg->hdr.nexus.targ_port;
1219 		port->fe_datamove = ctl_ha_datamove;
1220 		port->fe_done = ctl_ha_done;
1221 	} else if (port->frontend == &ha_frontend) {
1222 		CTL_DEBUG_PRINT(("%s: Updated port %d\n", __func__,
1223 		    msg->hdr.nexus.targ_port));
1224 		new = 0;
1225 	} else {
1226 		printf("%s: Received conflicting HA port %d\n",
1227 		    __func__, msg->hdr.nexus.targ_port);
1228 		return;
1229 	}
1230 	port->port_type = msg->port.port_type;
1231 	port->physical_port = msg->port.physical_port;
1232 	port->virtual_port = msg->port.virtual_port;
1233 	port->status = msg->port.status;
1234 	i = 0;
1235 	free(port->port_name, M_CTL);
1236 	port->port_name = strndup(&msg->port.data[i], msg->port.name_len,
1237 	    M_CTL);
1238 	i += msg->port.name_len;
1239 	if (msg->port.lun_map_len != 0) {
1240 		if (port->lun_map == NULL ||
1241 		    port->lun_map_size * sizeof(uint32_t) <
1242 		    msg->port.lun_map_len) {
1243 			port->lun_map_size = 0;
1244 			free(port->lun_map, M_CTL);
1245 			port->lun_map = malloc(msg->port.lun_map_len,
1246 			    M_CTL, M_WAITOK);
1247 		}
1248 		memcpy(port->lun_map, &msg->port.data[i], msg->port.lun_map_len);
1249 		port->lun_map_size = msg->port.lun_map_len / sizeof(uint32_t);
1250 		i += msg->port.lun_map_len;
1251 	} else {
1252 		port->lun_map_size = 0;
1253 		free(port->lun_map, M_CTL);
1254 		port->lun_map = NULL;
1255 	}
1256 	if (msg->port.port_devid_len != 0) {
1257 		if (port->port_devid == NULL ||
1258 		    port->port_devid->len < msg->port.port_devid_len) {
1259 			free(port->port_devid, M_CTL);
1260 			port->port_devid = malloc(sizeof(struct ctl_devid) +
1261 			    msg->port.port_devid_len, M_CTL, M_WAITOK);
1262 		}
1263 		memcpy(port->port_devid->data, &msg->port.data[i],
1264 		    msg->port.port_devid_len);
1265 		port->port_devid->len = msg->port.port_devid_len;
1266 		i += msg->port.port_devid_len;
1267 	} else {
1268 		free(port->port_devid, M_CTL);
1269 		port->port_devid = NULL;
1270 	}
1271 	if (msg->port.target_devid_len != 0) {
1272 		if (port->target_devid == NULL ||
1273 		    port->target_devid->len < msg->port.target_devid_len) {
1274 			free(port->target_devid, M_CTL);
1275 			port->target_devid = malloc(sizeof(struct ctl_devid) +
1276 			    msg->port.target_devid_len, M_CTL, M_WAITOK);
1277 		}
1278 		memcpy(port->target_devid->data, &msg->port.data[i],
1279 		    msg->port.target_devid_len);
1280 		port->target_devid->len = msg->port.target_devid_len;
1281 		i += msg->port.target_devid_len;
1282 	} else {
1283 		free(port->target_devid, M_CTL);
1284 		port->target_devid = NULL;
1285 	}
1286 	if (msg->port.init_devid_len != 0) {
1287 		if (port->init_devid == NULL ||
1288 		    port->init_devid->len < msg->port.init_devid_len) {
1289 			free(port->init_devid, M_CTL);
1290 			port->init_devid = malloc(sizeof(struct ctl_devid) +
1291 			    msg->port.init_devid_len, M_CTL, M_WAITOK);
1292 		}
1293 		memcpy(port->init_devid->data, &msg->port.data[i],
1294 		    msg->port.init_devid_len);
1295 		port->init_devid->len = msg->port.init_devid_len;
1296 		i += msg->port.init_devid_len;
1297 	} else {
1298 		free(port->init_devid, M_CTL);
1299 		port->init_devid = NULL;
1300 	}
1301 	if (new) {
1302 		if (ctl_port_register(port) != 0) {
1303 			printf("%s: ctl_port_register() failed with error\n",
1304 			    __func__);
1305 		}
1306 	}
1307 	mtx_lock(&softc->ctl_lock);
1308 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
1309 		if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
1310 			continue;
1311 		mtx_lock(&lun->lun_lock);
1312 		ctl_est_ua_all(lun, -1, CTL_UA_INQ_CHANGE);
1313 		mtx_unlock(&lun->lun_lock);
1314 	}
1315 	mtx_unlock(&softc->ctl_lock);
1316 }
1317 
1318 static void
1319 ctl_isc_iid_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1320 {
1321 	struct ctl_port *port;
1322 	int iid;
1323 
1324 	port = softc->ctl_ports[msg->hdr.nexus.targ_port];
1325 	if (port == NULL) {
1326 		printf("%s: Received IID for unknown port %d\n",
1327 		    __func__, msg->hdr.nexus.targ_port);
1328 		return;
1329 	}
1330 	iid = msg->hdr.nexus.initid;
1331 	if (port->wwpn_iid[iid].in_use != 0 &&
1332 	    msg->iid.in_use == 0)
1333 		ctl_i_t_nexus_loss(softc, iid, CTL_UA_POWERON);
1334 	port->wwpn_iid[iid].in_use = msg->iid.in_use;
1335 	port->wwpn_iid[iid].wwpn = msg->iid.wwpn;
1336 	free(port->wwpn_iid[iid].name, M_CTL);
1337 	if (msg->iid.name_len) {
1338 		port->wwpn_iid[iid].name = strndup(&msg->iid.data[0],
1339 		    msg->iid.name_len, M_CTL);
1340 	} else
1341 		port->wwpn_iid[iid].name = NULL;
1342 }
1343 
1344 static void
1345 ctl_isc_login(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1346 {
1347 
1348 	if (msg->login.version != CTL_HA_VERSION) {
1349 		printf("CTL HA peers have different versions %d != %d\n",
1350 		    msg->login.version, CTL_HA_VERSION);
1351 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1352 		return;
1353 	}
1354 	if (msg->login.ha_mode != softc->ha_mode) {
1355 		printf("CTL HA peers have different ha_mode %d != %d\n",
1356 		    msg->login.ha_mode, softc->ha_mode);
1357 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1358 		return;
1359 	}
1360 	if (msg->login.ha_id == softc->ha_id) {
1361 		printf("CTL HA peers have same ha_id %d\n", msg->login.ha_id);
1362 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1363 		return;
1364 	}
1365 	if (msg->login.max_luns != ctl_max_luns ||
1366 	    msg->login.max_ports != ctl_max_ports ||
1367 	    msg->login.max_init_per_port != CTL_MAX_INIT_PER_PORT) {
1368 		printf("CTL HA peers have different limits\n");
1369 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1370 		return;
1371 	}
1372 }
1373 
1374 static void
1375 ctl_isc_mode_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1376 {
1377 	struct ctl_lun *lun;
1378 	u_int i;
1379 	uint32_t initidx, targ_lun;
1380 
1381 	targ_lun = msg->hdr.nexus.targ_mapped_lun;
1382 	mtx_lock(&softc->ctl_lock);
1383 	if (targ_lun >= ctl_max_luns ||
1384 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
1385 		mtx_unlock(&softc->ctl_lock);
1386 		return;
1387 	}
1388 	mtx_lock(&lun->lun_lock);
1389 	mtx_unlock(&softc->ctl_lock);
1390 	if (lun->flags & CTL_LUN_DISABLED) {
1391 		mtx_unlock(&lun->lun_lock);
1392 		return;
1393 	}
1394 	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
1395 		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) ==
1396 		    msg->mode.page_code &&
1397 		    lun->mode_pages.index[i].subpage == msg->mode.subpage)
1398 			break;
1399 	}
1400 	if (i == CTL_NUM_MODE_PAGES) {
1401 		mtx_unlock(&lun->lun_lock);
1402 		return;
1403 	}
1404 	memcpy(lun->mode_pages.index[i].page_data, msg->mode.data,
1405 	    lun->mode_pages.index[i].page_len);
1406 	initidx = ctl_get_initindex(&msg->hdr.nexus);
1407 	if (initidx != -1)
1408 		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
1409 	mtx_unlock(&lun->lun_lock);
1410 }
1411 
1412 /*
1413  * ISC (Inter Shelf Communication) event handler.  Events from the HA
1414  * subsystem come in here.
1415  */
1416 static void
1417 ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
1418 {
1419 	struct ctl_softc *softc = control_softc;
1420 	union ctl_io *io;
1421 	struct ctl_prio *presio;
1422 	ctl_ha_status isc_status;
1423 
1424 	CTL_DEBUG_PRINT(("CTL: Isc Msg event %d\n", event));
1425 	if (event == CTL_HA_EVT_MSG_RECV) {
1426 		union ctl_ha_msg *msg, msgbuf;
1427 
1428 		if (param > sizeof(msgbuf))
1429 			msg = malloc(param, M_CTL, M_WAITOK);
1430 		else
1431 			msg = &msgbuf;
1432 		isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, msg, param,
1433 		    M_WAITOK);
1434 		if (isc_status != CTL_HA_STATUS_SUCCESS) {
1435 			printf("%s: Error receiving message: %d\n",
1436 			    __func__, isc_status);
1437 			if (msg != &msgbuf)
1438 				free(msg, M_CTL);
1439 			return;
1440 		}
1441 
1442 		CTL_DEBUG_PRINT(("CTL: msg_type %d\n", msg->hdr.msg_type));
1443 		switch (msg->hdr.msg_type) {
1444 		case CTL_MSG_SERIALIZE:
1445 			io = ctl_alloc_io(softc->othersc_pool);
1446 			ctl_zero_io(io);
1447 			// populate ctsio from msg
1448 			io->io_hdr.io_type = CTL_IO_SCSI;
1449 			io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
1450 			io->io_hdr.remote_io = msg->hdr.original_sc;
1451 			io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
1452 					    CTL_FLAG_IO_ACTIVE;
1453 			/*
1454 			 * If we're in serialization-only mode, we don't
1455 			 * want to go through full done processing.  Thus
1456 			 * the COPY flag.
1457 			 *
1458 			 * XXX KDM add another flag that is more specific.
1459 			 */
1460 			if (softc->ha_mode != CTL_HA_MODE_XFER)
1461 				io->io_hdr.flags |= CTL_FLAG_INT_COPY;
1462 			io->io_hdr.nexus = msg->hdr.nexus;
1463 			io->scsiio.tag_num = msg->scsi.tag_num;
1464 			io->scsiio.tag_type = msg->scsi.tag_type;
1465 #ifdef CTL_TIME_IO
1466 			io->io_hdr.start_time = time_uptime;
1467 			getbinuptime(&io->io_hdr.start_bt);
1468 #endif /* CTL_TIME_IO */
1469 			io->scsiio.cdb_len = msg->scsi.cdb_len;
1470 			memcpy(io->scsiio.cdb, msg->scsi.cdb,
1471 			       CTL_MAX_CDBLEN);
1472 			if (softc->ha_mode == CTL_HA_MODE_XFER) {
1473 				const struct ctl_cmd_entry *entry;
1474 
1475 				entry = ctl_get_cmd_entry(&io->scsiio, NULL);
1476 				io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
1477 				io->io_hdr.flags |=
1478 					entry->flags & CTL_FLAG_DATA_MASK;
1479 			}
1480 			ctl_enqueue_isc(io);
1481 			break;
1482 
1483 		/* Performed on the Originating SC, XFER mode only */
1484 		case CTL_MSG_DATAMOVE: {
1485 			struct ctl_sg_entry *sgl;
1486 			int i, j;
1487 
1488 			io = msg->hdr.original_sc;
1489 			if (io == NULL) {
1490 				printf("%s: original_sc == NULL!\n", __func__);
1491 				/* XXX KDM do something here */
1492 				break;
1493 			}
1494 			io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
1495 			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1496 			/*
1497 			 * Keep track of this, we need to send it back over
1498 			 * when the datamove is complete.
1499 			 */
1500 			io->io_hdr.remote_io = msg->hdr.serializing_sc;
1501 			if (msg->hdr.status == CTL_SUCCESS)
1502 				io->io_hdr.status = msg->hdr.status;
1503 
1504 			if (msg->dt.sg_sequence == 0) {
1505 #ifdef CTL_TIME_IO
1506 				getbinuptime(&io->io_hdr.dma_start_bt);
1507 #endif
1508 				i = msg->dt.kern_sg_entries +
1509 				    msg->dt.kern_data_len /
1510 				    CTL_HA_DATAMOVE_SEGMENT + 1;
1511 				sgl = malloc(sizeof(*sgl) * i, M_CTL,
1512 				    M_WAITOK | M_ZERO);
1513 				CTL_RSGL(io) = sgl;
1514 				CTL_LSGL(io) = &sgl[msg->dt.kern_sg_entries];
1515 
1516 				io->scsiio.kern_data_ptr = (uint8_t *)sgl;
1517 
1518 				io->scsiio.kern_sg_entries =
1519 					msg->dt.kern_sg_entries;
1520 				io->scsiio.rem_sg_entries =
1521 					msg->dt.kern_sg_entries;
1522 				io->scsiio.kern_data_len =
1523 					msg->dt.kern_data_len;
1524 				io->scsiio.kern_total_len =
1525 					msg->dt.kern_total_len;
1526 				io->scsiio.kern_data_resid =
1527 					msg->dt.kern_data_resid;
1528 				io->scsiio.kern_rel_offset =
1529 					msg->dt.kern_rel_offset;
1530 				io->io_hdr.flags &= ~CTL_FLAG_BUS_ADDR;
1531 				io->io_hdr.flags |= msg->dt.flags &
1532 				    CTL_FLAG_BUS_ADDR;
1533 			} else
1534 				sgl = (struct ctl_sg_entry *)
1535 					io->scsiio.kern_data_ptr;
1536 
1537 			for (i = msg->dt.sent_sg_entries, j = 0;
1538 			     i < (msg->dt.sent_sg_entries +
1539 			     msg->dt.cur_sg_entries); i++, j++) {
1540 				sgl[i].addr = msg->dt.sg_list[j].addr;
1541 				sgl[i].len = msg->dt.sg_list[j].len;
1542 			}
1543 
1544 			/*
1545 			 * If this is the last piece of the I/O, we've got
1546 			 * the full S/G list.  Queue processing in the thread.
1547 			 * Otherwise wait for the next piece.
1548 			 */
1549 			if (msg->dt.sg_last != 0)
1550 				ctl_enqueue_isc(io);
1551 			break;
1552 		}
1553 		/* Performed on the Serializing (primary) SC, XFER mode only */
1554 		case CTL_MSG_DATAMOVE_DONE: {
1555 			if (msg->hdr.serializing_sc == NULL) {
1556 				printf("%s: serializing_sc == NULL!\n",
1557 				       __func__);
1558 				/* XXX KDM now what? */
1559 				break;
1560 			}
1561 			/*
1562 			 * We grab the sense information here in case
1563 			 * there was a failure, so we can return status
1564 			 * back to the initiator.
1565 			 */
1566 			io = msg->hdr.serializing_sc;
1567 			io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
1568 			io->io_hdr.flags &= ~CTL_FLAG_DMA_INPROG;
1569 			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1570 			io->io_hdr.port_status = msg->scsi.port_status;
1571 			io->scsiio.kern_data_resid = msg->scsi.kern_data_resid;
1572 			if (msg->hdr.status != CTL_STATUS_NONE) {
1573 				io->io_hdr.status = msg->hdr.status;
1574 				io->scsiio.scsi_status = msg->scsi.scsi_status;
1575 				io->scsiio.sense_len = msg->scsi.sense_len;
1576 				memcpy(&io->scsiio.sense_data,
1577 				    &msg->scsi.sense_data,
1578 				    msg->scsi.sense_len);
1579 				if (msg->hdr.status == CTL_SUCCESS)
1580 					io->io_hdr.flags |= CTL_FLAG_STATUS_SENT;
1581 			}
1582 			ctl_enqueue_isc(io);
1583 			break;
1584 		}
1585 
1586 		/* Preformed on Originating SC, SER_ONLY mode */
1587 		case CTL_MSG_R2R:
1588 			io = msg->hdr.original_sc;
1589 			if (io == NULL) {
1590 				printf("%s: original_sc == NULL!\n",
1591 				    __func__);
1592 				break;
1593 			}
1594 			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1595 			io->io_hdr.msg_type = CTL_MSG_R2R;
1596 			io->io_hdr.remote_io = msg->hdr.serializing_sc;
1597 			ctl_enqueue_isc(io);
1598 			break;
1599 
1600 		/*
1601 		 * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
1602 		 * mode.
1603 		 * Performed on the Originating (i.e. secondary) SC in XFER
1604 		 * mode
1605 		 */
1606 		case CTL_MSG_FINISH_IO:
1607 			if (softc->ha_mode == CTL_HA_MODE_XFER)
1608 				ctl_isc_handler_finish_xfer(softc, msg);
1609 			else
1610 				ctl_isc_handler_finish_ser_only(softc, msg);
1611 			break;
1612 
1613 		/* Preformed on Originating SC */
1614 		case CTL_MSG_BAD_JUJU:
1615 			io = msg->hdr.original_sc;
1616 			if (io == NULL) {
1617 				printf("%s: Bad JUJU!, original_sc is NULL!\n",
1618 				       __func__);
1619 				break;
1620 			}
1621 			ctl_copy_sense_data(msg, io);
1622 			/*
1623 			 * IO should have already been cleaned up on other
1624 			 * SC so clear this flag so we won't send a message
1625 			 * back to finish the IO there.
1626 			 */
1627 			io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
1628 			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1629 
1630 			/* io = msg->hdr.serializing_sc; */
1631 			io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
1632 			ctl_enqueue_isc(io);
1633 			break;
1634 
1635 		/* Handle resets sent from the other side */
1636 		case CTL_MSG_MANAGE_TASKS: {
1637 			struct ctl_taskio *taskio;
1638 			taskio = (struct ctl_taskio *)ctl_alloc_io(
1639 			    softc->othersc_pool);
1640 			ctl_zero_io((union ctl_io *)taskio);
1641 			taskio->io_hdr.io_type = CTL_IO_TASK;
1642 			taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1643 			taskio->io_hdr.nexus = msg->hdr.nexus;
1644 			taskio->task_action = msg->task.task_action;
1645 			taskio->tag_num = msg->task.tag_num;
1646 			taskio->tag_type = msg->task.tag_type;
1647 #ifdef CTL_TIME_IO
1648 			taskio->io_hdr.start_time = time_uptime;
1649 			getbinuptime(&taskio->io_hdr.start_bt);
1650 #endif /* CTL_TIME_IO */
1651 			ctl_run_task((union ctl_io *)taskio);
1652 			break;
1653 		}
1654 		/* Persistent Reserve action which needs attention */
1655 		case CTL_MSG_PERS_ACTION:
1656 			presio = (struct ctl_prio *)ctl_alloc_io(
1657 			    softc->othersc_pool);
1658 			ctl_zero_io((union ctl_io *)presio);
1659 			presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
1660 			presio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1661 			presio->io_hdr.nexus = msg->hdr.nexus;
1662 			presio->pr_msg = msg->pr;
1663 			ctl_enqueue_isc((union ctl_io *)presio);
1664 			break;
1665 		case CTL_MSG_UA:
1666 			ctl_isc_ua(softc, msg, param);
1667 			break;
1668 		case CTL_MSG_PORT_SYNC:
1669 			ctl_isc_port_sync(softc, msg, param);
1670 			break;
1671 		case CTL_MSG_LUN_SYNC:
1672 			ctl_isc_lun_sync(softc, msg, param);
1673 			break;
1674 		case CTL_MSG_IID_SYNC:
1675 			ctl_isc_iid_sync(softc, msg, param);
1676 			break;
1677 		case CTL_MSG_LOGIN:
1678 			ctl_isc_login(softc, msg, param);
1679 			break;
1680 		case CTL_MSG_MODE_SYNC:
1681 			ctl_isc_mode_sync(softc, msg, param);
1682 			break;
1683 		default:
1684 			printf("Received HA message of unknown type %d\n",
1685 			    msg->hdr.msg_type);
1686 			ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1687 			break;
1688 		}
1689 		if (msg != &msgbuf)
1690 			free(msg, M_CTL);
1691 	} else if (event == CTL_HA_EVT_LINK_CHANGE) {
1692 		printf("CTL: HA link status changed from %d to %d\n",
1693 		    softc->ha_link, param);
1694 		if (param == softc->ha_link)
1695 			return;
1696 		if (softc->ha_link == CTL_HA_LINK_ONLINE) {
1697 			softc->ha_link = param;
1698 			ctl_isc_ha_link_down(softc);
1699 		} else {
1700 			softc->ha_link = param;
1701 			if (softc->ha_link == CTL_HA_LINK_ONLINE)
1702 				ctl_isc_ha_link_up(softc);
1703 		}
1704 		return;
1705 	} else {
1706 		printf("ctl_isc_event_handler: Unknown event %d\n", event);
1707 		return;
1708 	}
1709 }
1710 
1711 static void
1712 ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
1713 {
1714 
1715 	memcpy(&dest->scsiio.sense_data, &src->scsi.sense_data,
1716 	    src->scsi.sense_len);
1717 	dest->scsiio.scsi_status = src->scsi.scsi_status;
1718 	dest->scsiio.sense_len = src->scsi.sense_len;
1719 	dest->io_hdr.status = src->hdr.status;
1720 }
1721 
1722 static void
1723 ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest)
1724 {
1725 
1726 	memcpy(&dest->scsi.sense_data, &src->scsiio.sense_data,
1727 	    src->scsiio.sense_len);
1728 	dest->scsi.scsi_status = src->scsiio.scsi_status;
1729 	dest->scsi.sense_len = src->scsiio.sense_len;
1730 	dest->hdr.status = src->io_hdr.status;
1731 }
1732 
1733 void
1734 ctl_est_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1735 {
1736 	struct ctl_softc *softc = lun->ctl_softc;
1737 	ctl_ua_type *pu;
1738 
1739 	if (initidx < softc->init_min || initidx >= softc->init_max)
1740 		return;
1741 	mtx_assert(&lun->lun_lock, MA_OWNED);
1742 	pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1743 	if (pu == NULL)
1744 		return;
1745 	pu[initidx % CTL_MAX_INIT_PER_PORT] |= ua;
1746 }
1747 
1748 void
1749 ctl_est_ua_port(struct ctl_lun *lun, int port, uint32_t except, ctl_ua_type ua)
1750 {
1751 	int i;
1752 
1753 	mtx_assert(&lun->lun_lock, MA_OWNED);
1754 	if (lun->pending_ua[port] == NULL)
1755 		return;
1756 	for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1757 		if (port * CTL_MAX_INIT_PER_PORT + i == except)
1758 			continue;
1759 		lun->pending_ua[port][i] |= ua;
1760 	}
1761 }
1762 
1763 void
1764 ctl_est_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1765 {
1766 	struct ctl_softc *softc = lun->ctl_softc;
1767 	int i;
1768 
1769 	mtx_assert(&lun->lun_lock, MA_OWNED);
1770 	for (i = softc->port_min; i < softc->port_max; i++)
1771 		ctl_est_ua_port(lun, i, except, ua);
1772 }
1773 
1774 void
1775 ctl_clr_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1776 {
1777 	struct ctl_softc *softc = lun->ctl_softc;
1778 	ctl_ua_type *pu;
1779 
1780 	if (initidx < softc->init_min || initidx >= softc->init_max)
1781 		return;
1782 	mtx_assert(&lun->lun_lock, MA_OWNED);
1783 	pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1784 	if (pu == NULL)
1785 		return;
1786 	pu[initidx % CTL_MAX_INIT_PER_PORT] &= ~ua;
1787 }
1788 
1789 void
1790 ctl_clr_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1791 {
1792 	struct ctl_softc *softc = lun->ctl_softc;
1793 	int i, j;
1794 
1795 	mtx_assert(&lun->lun_lock, MA_OWNED);
1796 	for (i = softc->port_min; i < softc->port_max; i++) {
1797 		if (lun->pending_ua[i] == NULL)
1798 			continue;
1799 		for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
1800 			if (i * CTL_MAX_INIT_PER_PORT + j == except)
1801 				continue;
1802 			lun->pending_ua[i][j] &= ~ua;
1803 		}
1804 	}
1805 }
1806 
1807 void
1808 ctl_clr_ua_allluns(struct ctl_softc *ctl_softc, uint32_t initidx,
1809     ctl_ua_type ua_type)
1810 {
1811 	struct ctl_lun *lun;
1812 
1813 	mtx_assert(&ctl_softc->ctl_lock, MA_OWNED);
1814 	STAILQ_FOREACH(lun, &ctl_softc->lun_list, links) {
1815 		mtx_lock(&lun->lun_lock);
1816 		ctl_clr_ua(lun, initidx, ua_type);
1817 		mtx_unlock(&lun->lun_lock);
1818 	}
1819 }
1820 
1821 static int
1822 ctl_ha_role_sysctl(SYSCTL_HANDLER_ARGS)
1823 {
1824 	struct ctl_softc *softc = (struct ctl_softc *)arg1;
1825 	struct ctl_lun *lun;
1826 	struct ctl_lun_req ireq;
1827 	int error, value;
1828 
1829 	value = (softc->flags & CTL_FLAG_ACTIVE_SHELF) ? 0 : 1;
1830 	error = sysctl_handle_int(oidp, &value, 0, req);
1831 	if ((error != 0) || (req->newptr == NULL))
1832 		return (error);
1833 
1834 	mtx_lock(&softc->ctl_lock);
1835 	if (value == 0)
1836 		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1837 	else
1838 		softc->flags &= ~CTL_FLAG_ACTIVE_SHELF;
1839 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
1840 		mtx_unlock(&softc->ctl_lock);
1841 		bzero(&ireq, sizeof(ireq));
1842 		ireq.reqtype = CTL_LUNREQ_MODIFY;
1843 		ireq.reqdata.modify.lun_id = lun->lun;
1844 		lun->backend->ioctl(NULL, CTL_LUN_REQ, (caddr_t)&ireq, 0,
1845 		    curthread);
1846 		if (ireq.status != CTL_LUN_OK) {
1847 			printf("%s: CTL_LUNREQ_MODIFY returned %d '%s'\n",
1848 			    __func__, ireq.status, ireq.error_str);
1849 		}
1850 		mtx_lock(&softc->ctl_lock);
1851 	}
1852 	mtx_unlock(&softc->ctl_lock);
1853 	return (0);
1854 }
1855 
1856 static int
1857 ctl_init(void)
1858 {
1859 	struct make_dev_args args;
1860 	struct ctl_softc *softc;
1861 	int i, error;
1862 
1863 	softc = control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
1864 			       M_WAITOK | M_ZERO);
1865 
1866 	make_dev_args_init(&args);
1867 	args.mda_devsw = &ctl_cdevsw;
1868 	args.mda_uid = UID_ROOT;
1869 	args.mda_gid = GID_OPERATOR;
1870 	args.mda_mode = 0600;
1871 	args.mda_si_drv1 = softc;
1872 	args.mda_si_drv2 = NULL;
1873 	error = make_dev_s(&args, &softc->dev, "cam/ctl");
1874 	if (error != 0) {
1875 		free(softc, M_DEVBUF);
1876 		control_softc = NULL;
1877 		return (error);
1878 	}
1879 
1880 	sysctl_ctx_init(&softc->sysctl_ctx);
1881 	softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
1882 		SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
1883 		CTLFLAG_RD | CTLFLAG_MPSAFE, 0, "CAM Target Layer");
1884 
1885 	if (softc->sysctl_tree == NULL) {
1886 		printf("%s: unable to allocate sysctl tree\n", __func__);
1887 		destroy_dev(softc->dev);
1888 		free(softc, M_DEVBUF);
1889 		control_softc = NULL;
1890 		return (ENOMEM);
1891 	}
1892 
1893 	mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
1894 	softc->io_zone = uma_zcreate("CTL IO", sizeof(union ctl_io),
1895 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1896 	softc->flags = 0;
1897 
1898 	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1899 	    OID_AUTO, "ha_mode", CTLFLAG_RDTUN, (int *)&softc->ha_mode, 0,
1900 	    "HA mode (0 - act/stby, 1 - serialize only, 2 - xfer)");
1901 
1902 	if (ctl_max_luns <= 0 || powerof2(ctl_max_luns) == 0) {
1903 		printf("Bad value %d for kern.cam.ctl.max_luns, must be a power of two, using %d\n",
1904 		    ctl_max_luns, CTL_DEFAULT_MAX_LUNS);
1905 		ctl_max_luns = CTL_DEFAULT_MAX_LUNS;
1906 	}
1907 	softc->ctl_luns = malloc(sizeof(struct ctl_lun *) * ctl_max_luns,
1908 	    M_DEVBUF, M_WAITOK | M_ZERO);
1909 	softc->ctl_lun_mask = malloc(sizeof(uint32_t) *
1910 	    ((ctl_max_luns + 31) / 32), M_DEVBUF, M_WAITOK | M_ZERO);
1911 	if (ctl_max_ports <= 0 || powerof2(ctl_max_ports) == 0) {
1912 		printf("Bad value %d for kern.cam.ctl.max_ports, must be a power of two, using %d\n",
1913 		    ctl_max_ports, CTL_DEFAULT_MAX_PORTS);
1914 		ctl_max_ports = CTL_DEFAULT_MAX_PORTS;
1915 	}
1916 	softc->ctl_port_mask = malloc(sizeof(uint32_t) *
1917 	  ((ctl_max_ports + 31) / 32), M_DEVBUF, M_WAITOK | M_ZERO);
1918 	softc->ctl_ports = malloc(sizeof(struct ctl_port *) * ctl_max_ports,
1919 	     M_DEVBUF, M_WAITOK | M_ZERO);
1920 
1921 
1922 	/*
1923 	 * In Copan's HA scheme, the "master" and "slave" roles are
1924 	 * figured out through the slot the controller is in.  Although it
1925 	 * is an active/active system, someone has to be in charge.
1926 	 */
1927 	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1928 	    OID_AUTO, "ha_id", CTLFLAG_RDTUN, &softc->ha_id, 0,
1929 	    "HA head ID (0 - no HA)");
1930 	if (softc->ha_id == 0 || softc->ha_id > NUM_HA_SHELVES) {
1931 		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1932 		softc->is_single = 1;
1933 		softc->port_cnt = ctl_max_ports;
1934 		softc->port_min = 0;
1935 	} else {
1936 		softc->port_cnt = ctl_max_ports / NUM_HA_SHELVES;
1937 		softc->port_min = (softc->ha_id - 1) * softc->port_cnt;
1938 	}
1939 	softc->port_max = softc->port_min + softc->port_cnt;
1940 	softc->init_min = softc->port_min * CTL_MAX_INIT_PER_PORT;
1941 	softc->init_max = softc->port_max * CTL_MAX_INIT_PER_PORT;
1942 
1943 	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1944 	    OID_AUTO, "ha_link", CTLFLAG_RD, (int *)&softc->ha_link, 0,
1945 	    "HA link state (0 - offline, 1 - unknown, 2 - online)");
1946 
1947 	STAILQ_INIT(&softc->lun_list);
1948 	STAILQ_INIT(&softc->pending_lun_queue);
1949 	STAILQ_INIT(&softc->fe_list);
1950 	STAILQ_INIT(&softc->port_list);
1951 	STAILQ_INIT(&softc->be_list);
1952 	ctl_tpc_init(softc);
1953 
1954 	if (worker_threads <= 0)
1955 		worker_threads = max(1, mp_ncpus / 4);
1956 	if (worker_threads > CTL_MAX_THREADS)
1957 		worker_threads = CTL_MAX_THREADS;
1958 
1959 	for (i = 0; i < worker_threads; i++) {
1960 		struct ctl_thread *thr = &softc->threads[i];
1961 
1962 		mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1963 		thr->ctl_softc = softc;
1964 		STAILQ_INIT(&thr->incoming_queue);
1965 		STAILQ_INIT(&thr->rtr_queue);
1966 		STAILQ_INIT(&thr->done_queue);
1967 		STAILQ_INIT(&thr->isc_queue);
1968 
1969 		error = kproc_kthread_add(ctl_work_thread, thr,
1970 		    &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1971 		if (error != 0) {
1972 			printf("error creating CTL work thread!\n");
1973 			return (error);
1974 		}
1975 	}
1976 	error = kproc_kthread_add(ctl_lun_thread, softc,
1977 	    &softc->ctl_proc, &softc->lun_thread, 0, 0, "ctl", "lun");
1978 	if (error != 0) {
1979 		printf("error creating CTL lun thread!\n");
1980 		return (error);
1981 	}
1982 	error = kproc_kthread_add(ctl_thresh_thread, softc,
1983 	    &softc->ctl_proc, &softc->thresh_thread, 0, 0, "ctl", "thresh");
1984 	if (error != 0) {
1985 		printf("error creating CTL threshold thread!\n");
1986 		return (error);
1987 	}
1988 
1989 	SYSCTL_ADD_PROC(&softc->sysctl_ctx,SYSCTL_CHILDREN(softc->sysctl_tree),
1990 	    OID_AUTO, "ha_role",
1991 	    CTLTYPE_INT | CTLFLAG_RWTUN | CTLFLAG_NEEDGIANT,
1992 	    softc, 0, ctl_ha_role_sysctl, "I", "HA role for this head");
1993 
1994 	if (softc->is_single == 0) {
1995 		if (ctl_frontend_register(&ha_frontend) != 0)
1996 			softc->is_single = 1;
1997 	}
1998 	return (0);
1999 }
2000 
2001 static int
2002 ctl_shutdown(void)
2003 {
2004 	struct ctl_softc *softc = control_softc;
2005 	int i;
2006 
2007 	if (softc->is_single == 0)
2008 		ctl_frontend_deregister(&ha_frontend);
2009 
2010 	destroy_dev(softc->dev);
2011 
2012 	/* Shutdown CTL threads. */
2013 	softc->shutdown = 1;
2014 	for (i = 0; i < worker_threads; i++) {
2015 		struct ctl_thread *thr = &softc->threads[i];
2016 		while (thr->thread != NULL) {
2017 			wakeup(thr);
2018 			if (thr->thread != NULL)
2019 				pause("CTL thr shutdown", 1);
2020 		}
2021 		mtx_destroy(&thr->queue_lock);
2022 	}
2023 	while (softc->lun_thread != NULL) {
2024 		wakeup(&softc->pending_lun_queue);
2025 		if (softc->lun_thread != NULL)
2026 			pause("CTL thr shutdown", 1);
2027 	}
2028 	while (softc->thresh_thread != NULL) {
2029 		wakeup(softc->thresh_thread);
2030 		if (softc->thresh_thread != NULL)
2031 			pause("CTL thr shutdown", 1);
2032 	}
2033 
2034 	ctl_tpc_shutdown(softc);
2035 	uma_zdestroy(softc->io_zone);
2036 	mtx_destroy(&softc->ctl_lock);
2037 
2038 	free(softc->ctl_luns, M_DEVBUF);
2039 	free(softc->ctl_lun_mask, M_DEVBUF);
2040 	free(softc->ctl_port_mask, M_DEVBUF);
2041 	free(softc->ctl_ports, M_DEVBUF);
2042 
2043 	sysctl_ctx_free(&softc->sysctl_ctx);
2044 
2045 	free(softc, M_DEVBUF);
2046 	control_softc = NULL;
2047 	return (0);
2048 }
2049 
2050 static int
2051 ctl_module_event_handler(module_t mod, int what, void *arg)
2052 {
2053 
2054 	switch (what) {
2055 	case MOD_LOAD:
2056 		return (ctl_init());
2057 	case MOD_UNLOAD:
2058 		return (ctl_shutdown());
2059 	default:
2060 		return (EOPNOTSUPP);
2061 	}
2062 }
2063 
2064 /*
2065  * XXX KDM should we do some access checks here?  Bump a reference count to
2066  * prevent a CTL module from being unloaded while someone has it open?
2067  */
2068 static int
2069 ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
2070 {
2071 	return (0);
2072 }
2073 
2074 static int
2075 ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
2076 {
2077 	return (0);
2078 }
2079 
2080 /*
2081  * Remove an initiator by port number and initiator ID.
2082  * Returns 0 for success, -1 for failure.
2083  */
2084 int
2085 ctl_remove_initiator(struct ctl_port *port, int iid)
2086 {
2087 	struct ctl_softc *softc = port->ctl_softc;
2088 	int last;
2089 
2090 	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
2091 
2092 	if (iid > CTL_MAX_INIT_PER_PORT) {
2093 		printf("%s: initiator ID %u > maximun %u!\n",
2094 		       __func__, iid, CTL_MAX_INIT_PER_PORT);
2095 		return (-1);
2096 	}
2097 
2098 	mtx_lock(&softc->ctl_lock);
2099 	last = (--port->wwpn_iid[iid].in_use == 0);
2100 	port->wwpn_iid[iid].last_use = time_uptime;
2101 	mtx_unlock(&softc->ctl_lock);
2102 	if (last)
2103 		ctl_i_t_nexus_loss(softc, iid, CTL_UA_POWERON);
2104 	ctl_isc_announce_iid(port, iid);
2105 
2106 	return (0);
2107 }
2108 
2109 /*
2110  * Add an initiator to the initiator map.
2111  * Returns iid for success, < 0 for failure.
2112  */
2113 int
2114 ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
2115 {
2116 	struct ctl_softc *softc = port->ctl_softc;
2117 	time_t best_time;
2118 	int i, best;
2119 
2120 	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
2121 
2122 	if (iid >= CTL_MAX_INIT_PER_PORT) {
2123 		printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
2124 		       __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
2125 		free(name, M_CTL);
2126 		return (-1);
2127 	}
2128 
2129 	mtx_lock(&softc->ctl_lock);
2130 
2131 	if (iid < 0 && (wwpn != 0 || name != NULL)) {
2132 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2133 			if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
2134 				iid = i;
2135 				break;
2136 			}
2137 			if (name != NULL && port->wwpn_iid[i].name != NULL &&
2138 			    strcmp(name, port->wwpn_iid[i].name) == 0) {
2139 				iid = i;
2140 				break;
2141 			}
2142 		}
2143 	}
2144 
2145 	if (iid < 0) {
2146 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2147 			if (port->wwpn_iid[i].in_use == 0 &&
2148 			    port->wwpn_iid[i].wwpn == 0 &&
2149 			    port->wwpn_iid[i].name == NULL) {
2150 				iid = i;
2151 				break;
2152 			}
2153 		}
2154 	}
2155 
2156 	if (iid < 0) {
2157 		best = -1;
2158 		best_time = INT32_MAX;
2159 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2160 			if (port->wwpn_iid[i].in_use == 0) {
2161 				if (port->wwpn_iid[i].last_use < best_time) {
2162 					best = i;
2163 					best_time = port->wwpn_iid[i].last_use;
2164 				}
2165 			}
2166 		}
2167 		iid = best;
2168 	}
2169 
2170 	if (iid < 0) {
2171 		mtx_unlock(&softc->ctl_lock);
2172 		free(name, M_CTL);
2173 		return (-2);
2174 	}
2175 
2176 	if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
2177 		/*
2178 		 * This is not an error yet.
2179 		 */
2180 		if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
2181 #if 0
2182 			printf("%s: port %d iid %u WWPN %#jx arrived"
2183 			    " again\n", __func__, port->targ_port,
2184 			    iid, (uintmax_t)wwpn);
2185 #endif
2186 			goto take;
2187 		}
2188 		if (name != NULL && port->wwpn_iid[iid].name != NULL &&
2189 		    strcmp(name, port->wwpn_iid[iid].name) == 0) {
2190 #if 0
2191 			printf("%s: port %d iid %u name '%s' arrived"
2192 			    " again\n", __func__, port->targ_port,
2193 			    iid, name);
2194 #endif
2195 			goto take;
2196 		}
2197 
2198 		/*
2199 		 * This is an error, but what do we do about it?  The
2200 		 * driver is telling us we have a new WWPN for this
2201 		 * initiator ID, so we pretty much need to use it.
2202 		 */
2203 		printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
2204 		    " but WWPN %#jx '%s' is still at that address\n",
2205 		    __func__, port->targ_port, iid, wwpn, name,
2206 		    (uintmax_t)port->wwpn_iid[iid].wwpn,
2207 		    port->wwpn_iid[iid].name);
2208 	}
2209 take:
2210 	free(port->wwpn_iid[iid].name, M_CTL);
2211 	port->wwpn_iid[iid].name = name;
2212 	port->wwpn_iid[iid].wwpn = wwpn;
2213 	port->wwpn_iid[iid].in_use++;
2214 	mtx_unlock(&softc->ctl_lock);
2215 	ctl_isc_announce_iid(port, iid);
2216 
2217 	return (iid);
2218 }
2219 
2220 static int
2221 ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
2222 {
2223 	int len;
2224 
2225 	switch (port->port_type) {
2226 	case CTL_PORT_FC:
2227 	{
2228 		struct scsi_transportid_fcp *id =
2229 		    (struct scsi_transportid_fcp *)buf;
2230 		if (port->wwpn_iid[iid].wwpn == 0)
2231 			return (0);
2232 		memset(id, 0, sizeof(*id));
2233 		id->format_protocol = SCSI_PROTO_FC;
2234 		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
2235 		return (sizeof(*id));
2236 	}
2237 	case CTL_PORT_ISCSI:
2238 	{
2239 		struct scsi_transportid_iscsi_port *id =
2240 		    (struct scsi_transportid_iscsi_port *)buf;
2241 		if (port->wwpn_iid[iid].name == NULL)
2242 			return (0);
2243 		memset(id, 0, 256);
2244 		id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
2245 		    SCSI_PROTO_ISCSI;
2246 		len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
2247 		len = roundup2(min(len, 252), 4);
2248 		scsi_ulto2b(len, id->additional_length);
2249 		return (sizeof(*id) + len);
2250 	}
2251 	case CTL_PORT_SAS:
2252 	{
2253 		struct scsi_transportid_sas *id =
2254 		    (struct scsi_transportid_sas *)buf;
2255 		if (port->wwpn_iid[iid].wwpn == 0)
2256 			return (0);
2257 		memset(id, 0, sizeof(*id));
2258 		id->format_protocol = SCSI_PROTO_SAS;
2259 		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
2260 		return (sizeof(*id));
2261 	}
2262 	default:
2263 	{
2264 		struct scsi_transportid_spi *id =
2265 		    (struct scsi_transportid_spi *)buf;
2266 		memset(id, 0, sizeof(*id));
2267 		id->format_protocol = SCSI_PROTO_SPI;
2268 		scsi_ulto2b(iid, id->scsi_addr);
2269 		scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
2270 		return (sizeof(*id));
2271 	}
2272 	}
2273 }
2274 
2275 /*
2276  * Serialize a command that went down the "wrong" side, and so was sent to
2277  * this controller for execution.  The logic is a little different than the
2278  * standard case in ctl_scsiio_precheck().  Errors in this case need to get
2279  * sent back to the other side, but in the success case, we execute the
2280  * command on this side (XFER mode) or tell the other side to execute it
2281  * (SER_ONLY mode).
2282  */
2283 static void
2284 ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
2285 {
2286 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
2287 	struct ctl_port *port = CTL_PORT(ctsio);
2288 	union ctl_ha_msg msg_info;
2289 	struct ctl_lun *lun;
2290 	const struct ctl_cmd_entry *entry;
2291 	union ctl_io *bio;
2292 	uint32_t targ_lun;
2293 
2294 	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
2295 
2296 	/* Make sure that we know about this port. */
2297 	if (port == NULL || (port->status & CTL_PORT_STATUS_ONLINE) == 0) {
2298 		ctl_set_internal_failure(ctsio, /*sks_valid*/ 0,
2299 					 /*retry_count*/ 1);
2300 		goto badjuju;
2301 	}
2302 
2303 	/* Make sure that we know about this LUN. */
2304 	mtx_lock(&softc->ctl_lock);
2305 	if (targ_lun >= ctl_max_luns ||
2306 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
2307 		mtx_unlock(&softc->ctl_lock);
2308 
2309 		/*
2310 		 * The other node would not send this request to us unless
2311 		 * received announce that we are primary node for this LUN.
2312 		 * If this LUN does not exist now, it is probably result of
2313 		 * a race, so respond to initiator in the most opaque way.
2314 		 */
2315 		ctl_set_busy(ctsio);
2316 		goto badjuju;
2317 	}
2318 	mtx_lock(&lun->lun_lock);
2319 	mtx_unlock(&softc->ctl_lock);
2320 
2321 	/*
2322 	 * If the LUN is invalid, pretend that it doesn't exist.
2323 	 * It will go away as soon as all pending I/Os completed.
2324 	 */
2325 	if (lun->flags & CTL_LUN_DISABLED) {
2326 		mtx_unlock(&lun->lun_lock);
2327 		ctl_set_busy(ctsio);
2328 		goto badjuju;
2329 	}
2330 
2331 	entry = ctl_get_cmd_entry(ctsio, NULL);
2332 	if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
2333 		mtx_unlock(&lun->lun_lock);
2334 		goto badjuju;
2335 	}
2336 
2337 	CTL_LUN(ctsio) = lun;
2338 	CTL_BACKEND_LUN(ctsio) = lun->be_lun;
2339 
2340 	/*
2341 	 * Every I/O goes into the OOA queue for a
2342 	 * particular LUN, and stays there until completion.
2343 	 */
2344 #ifdef CTL_TIME_IO
2345 	if (TAILQ_EMPTY(&lun->ooa_queue))
2346 		lun->idle_time += getsbinuptime() - lun->last_busy;
2347 #endif
2348 	TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2349 
2350 	bio = (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq, ooa_links);
2351 	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio, &bio)) {
2352 	case CTL_ACTION_BLOCK:
2353 		ctsio->io_hdr.blocker = bio;
2354 		TAILQ_INSERT_TAIL(&bio->io_hdr.blocked_queue, &ctsio->io_hdr,
2355 				  blocked_links);
2356 		mtx_unlock(&lun->lun_lock);
2357 		break;
2358 	case CTL_ACTION_PASS:
2359 	case CTL_ACTION_SKIP:
2360 		if (softc->ha_mode == CTL_HA_MODE_XFER) {
2361 			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
2362 			ctl_enqueue_rtr((union ctl_io *)ctsio);
2363 			mtx_unlock(&lun->lun_lock);
2364 		} else {
2365 			ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
2366 			mtx_unlock(&lun->lun_lock);
2367 
2368 			/* send msg back to other side */
2369 			msg_info.hdr.original_sc = ctsio->io_hdr.remote_io;
2370 			msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
2371 			msg_info.hdr.msg_type = CTL_MSG_R2R;
2372 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2373 			    sizeof(msg_info.hdr), M_WAITOK);
2374 		}
2375 		break;
2376 	case CTL_ACTION_OVERLAP:
2377 		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2378 		mtx_unlock(&lun->lun_lock);
2379 		ctl_set_overlapped_cmd(ctsio);
2380 		goto badjuju;
2381 	case CTL_ACTION_OVERLAP_TAG:
2382 		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2383 		mtx_unlock(&lun->lun_lock);
2384 		ctl_set_overlapped_tag(ctsio, ctsio->tag_num);
2385 		goto badjuju;
2386 	case CTL_ACTION_ERROR:
2387 	default:
2388 		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2389 		mtx_unlock(&lun->lun_lock);
2390 
2391 		ctl_set_internal_failure(ctsio, /*sks_valid*/ 0,
2392 					 /*retry_count*/ 0);
2393 badjuju:
2394 		ctl_copy_sense_data_back((union ctl_io *)ctsio, &msg_info);
2395 		msg_info.hdr.original_sc = ctsio->io_hdr.remote_io;
2396 		msg_info.hdr.serializing_sc = NULL;
2397 		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
2398 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2399 		    sizeof(msg_info.scsi), M_WAITOK);
2400 		ctl_free_io((union ctl_io *)ctsio);
2401 		break;
2402 	}
2403 }
2404 
2405 /*
2406  * Returns 0 for success, errno for failure.
2407  */
2408 static void
2409 ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2410 		   struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2411 {
2412 	union ctl_io *io;
2413 
2414 	mtx_lock(&lun->lun_lock);
2415 	for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
2416 	     (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2417 	     ooa_links)) {
2418 		struct ctl_ooa_entry *entry;
2419 
2420 		/*
2421 		 * If we've got more than we can fit, just count the
2422 		 * remaining entries.
2423 		 */
2424 		if (*cur_fill_num >= ooa_hdr->alloc_num)
2425 			continue;
2426 
2427 		entry = &kern_entries[*cur_fill_num];
2428 
2429 		entry->tag_num = io->scsiio.tag_num;
2430 		entry->lun_num = lun->lun;
2431 #ifdef CTL_TIME_IO
2432 		entry->start_bt = io->io_hdr.start_bt;
2433 #endif
2434 		bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2435 		entry->cdb_len = io->scsiio.cdb_len;
2436 		if (io->io_hdr.blocker != NULL)
2437 			entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2438 
2439 		if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2440 			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2441 
2442 		if (io->io_hdr.flags & CTL_FLAG_ABORT)
2443 			entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2444 
2445 		if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2446 			entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2447 
2448 		if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2449 			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2450 	}
2451 	mtx_unlock(&lun->lun_lock);
2452 }
2453 
2454 /*
2455  * Escape characters that are illegal or not recommended in XML.
2456  */
2457 int
2458 ctl_sbuf_printf_esc(struct sbuf *sb, char *str, int size)
2459 {
2460 	char *end = str + size;
2461 	int retval;
2462 
2463 	retval = 0;
2464 
2465 	for (; *str && str < end; str++) {
2466 		switch (*str) {
2467 		case '&':
2468 			retval = sbuf_printf(sb, "&amp;");
2469 			break;
2470 		case '>':
2471 			retval = sbuf_printf(sb, "&gt;");
2472 			break;
2473 		case '<':
2474 			retval = sbuf_printf(sb, "&lt;");
2475 			break;
2476 		default:
2477 			retval = sbuf_putc(sb, *str);
2478 			break;
2479 		}
2480 
2481 		if (retval != 0)
2482 			break;
2483 
2484 	}
2485 
2486 	return (retval);
2487 }
2488 
2489 static void
2490 ctl_id_sbuf(struct ctl_devid *id, struct sbuf *sb)
2491 {
2492 	struct scsi_vpd_id_descriptor *desc;
2493 	int i;
2494 
2495 	if (id == NULL || id->len < 4)
2496 		return;
2497 	desc = (struct scsi_vpd_id_descriptor *)id->data;
2498 	switch (desc->id_type & SVPD_ID_TYPE_MASK) {
2499 	case SVPD_ID_TYPE_T10:
2500 		sbuf_printf(sb, "t10.");
2501 		break;
2502 	case SVPD_ID_TYPE_EUI64:
2503 		sbuf_printf(sb, "eui.");
2504 		break;
2505 	case SVPD_ID_TYPE_NAA:
2506 		sbuf_printf(sb, "naa.");
2507 		break;
2508 	case SVPD_ID_TYPE_SCSI_NAME:
2509 		break;
2510 	}
2511 	switch (desc->proto_codeset & SVPD_ID_CODESET_MASK) {
2512 	case SVPD_ID_CODESET_BINARY:
2513 		for (i = 0; i < desc->length; i++)
2514 			sbuf_printf(sb, "%02x", desc->identifier[i]);
2515 		break;
2516 	case SVPD_ID_CODESET_ASCII:
2517 		sbuf_printf(sb, "%.*s", (int)desc->length,
2518 		    (char *)desc->identifier);
2519 		break;
2520 	case SVPD_ID_CODESET_UTF8:
2521 		sbuf_printf(sb, "%s", (char *)desc->identifier);
2522 		break;
2523 	}
2524 }
2525 
2526 static int
2527 ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2528 	  struct thread *td)
2529 {
2530 	struct ctl_softc *softc = dev->si_drv1;
2531 	struct ctl_port *port;
2532 	struct ctl_lun *lun;
2533 	int retval;
2534 
2535 	retval = 0;
2536 
2537 	switch (cmd) {
2538 	case CTL_IO:
2539 		retval = ctl_ioctl_io(dev, cmd, addr, flag, td);
2540 		break;
2541 	case CTL_ENABLE_PORT:
2542 	case CTL_DISABLE_PORT:
2543 	case CTL_SET_PORT_WWNS: {
2544 		struct ctl_port *port;
2545 		struct ctl_port_entry *entry;
2546 
2547 		entry = (struct ctl_port_entry *)addr;
2548 
2549 		mtx_lock(&softc->ctl_lock);
2550 		STAILQ_FOREACH(port, &softc->port_list, links) {
2551 			int action, done;
2552 
2553 			if (port->targ_port < softc->port_min ||
2554 			    port->targ_port >= softc->port_max)
2555 				continue;
2556 
2557 			action = 0;
2558 			done = 0;
2559 			if ((entry->port_type == CTL_PORT_NONE)
2560 			 && (entry->targ_port == port->targ_port)) {
2561 				/*
2562 				 * If the user only wants to enable or
2563 				 * disable or set WWNs on a specific port,
2564 				 * do the operation and we're done.
2565 				 */
2566 				action = 1;
2567 				done = 1;
2568 			} else if (entry->port_type & port->port_type) {
2569 				/*
2570 				 * Compare the user's type mask with the
2571 				 * particular frontend type to see if we
2572 				 * have a match.
2573 				 */
2574 				action = 1;
2575 				done = 0;
2576 
2577 				/*
2578 				 * Make sure the user isn't trying to set
2579 				 * WWNs on multiple ports at the same time.
2580 				 */
2581 				if (cmd == CTL_SET_PORT_WWNS) {
2582 					printf("%s: Can't set WWNs on "
2583 					       "multiple ports\n", __func__);
2584 					retval = EINVAL;
2585 					break;
2586 				}
2587 			}
2588 			if (action == 0)
2589 				continue;
2590 
2591 			/*
2592 			 * XXX KDM we have to drop the lock here, because
2593 			 * the online/offline operations can potentially
2594 			 * block.  We need to reference count the frontends
2595 			 * so they can't go away,
2596 			 */
2597 			if (cmd == CTL_ENABLE_PORT) {
2598 				mtx_unlock(&softc->ctl_lock);
2599 				ctl_port_online(port);
2600 				mtx_lock(&softc->ctl_lock);
2601 			} else if (cmd == CTL_DISABLE_PORT) {
2602 				mtx_unlock(&softc->ctl_lock);
2603 				ctl_port_offline(port);
2604 				mtx_lock(&softc->ctl_lock);
2605 			} else if (cmd == CTL_SET_PORT_WWNS) {
2606 				ctl_port_set_wwns(port,
2607 				    (entry->flags & CTL_PORT_WWNN_VALID) ?
2608 				    1 : 0, entry->wwnn,
2609 				    (entry->flags & CTL_PORT_WWPN_VALID) ?
2610 				    1 : 0, entry->wwpn);
2611 			}
2612 			if (done != 0)
2613 				break;
2614 		}
2615 		mtx_unlock(&softc->ctl_lock);
2616 		break;
2617 	}
2618 	case CTL_GET_OOA: {
2619 		struct ctl_ooa *ooa_hdr;
2620 		struct ctl_ooa_entry *entries;
2621 		uint32_t cur_fill_num;
2622 
2623 		ooa_hdr = (struct ctl_ooa *)addr;
2624 
2625 		if ((ooa_hdr->alloc_len == 0)
2626 		 || (ooa_hdr->alloc_num == 0)) {
2627 			printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2628 			       "must be non-zero\n", __func__,
2629 			       ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2630 			retval = EINVAL;
2631 			break;
2632 		}
2633 
2634 		if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2635 		    sizeof(struct ctl_ooa_entry))) {
2636 			printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2637 			       "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2638 			       __func__, ooa_hdr->alloc_len,
2639 			       ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2640 			retval = EINVAL;
2641 			break;
2642 		}
2643 
2644 		entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2645 		if (entries == NULL) {
2646 			printf("%s: could not allocate %d bytes for OOA "
2647 			       "dump\n", __func__, ooa_hdr->alloc_len);
2648 			retval = ENOMEM;
2649 			break;
2650 		}
2651 
2652 		mtx_lock(&softc->ctl_lock);
2653 		if ((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0 &&
2654 		    (ooa_hdr->lun_num >= ctl_max_luns ||
2655 		     softc->ctl_luns[ooa_hdr->lun_num] == NULL)) {
2656 			mtx_unlock(&softc->ctl_lock);
2657 			free(entries, M_CTL);
2658 			printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2659 			       __func__, (uintmax_t)ooa_hdr->lun_num);
2660 			retval = EINVAL;
2661 			break;
2662 		}
2663 
2664 		cur_fill_num = 0;
2665 
2666 		if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2667 			STAILQ_FOREACH(lun, &softc->lun_list, links) {
2668 				ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2669 				    ooa_hdr, entries);
2670 			}
2671 		} else {
2672 			lun = softc->ctl_luns[ooa_hdr->lun_num];
2673 			ctl_ioctl_fill_ooa(lun, &cur_fill_num, ooa_hdr,
2674 			    entries);
2675 		}
2676 		mtx_unlock(&softc->ctl_lock);
2677 
2678 		ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2679 		ooa_hdr->fill_len = ooa_hdr->fill_num *
2680 			sizeof(struct ctl_ooa_entry);
2681 		retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2682 		if (retval != 0) {
2683 			printf("%s: error copying out %d bytes for OOA dump\n",
2684 			       __func__, ooa_hdr->fill_len);
2685 		}
2686 
2687 		getbinuptime(&ooa_hdr->cur_bt);
2688 
2689 		if (cur_fill_num > ooa_hdr->alloc_num) {
2690 			ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2691 			ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2692 		} else {
2693 			ooa_hdr->dropped_num = 0;
2694 			ooa_hdr->status = CTL_OOA_OK;
2695 		}
2696 
2697 		free(entries, M_CTL);
2698 		break;
2699 	}
2700 	case CTL_DELAY_IO: {
2701 		struct ctl_io_delay_info *delay_info;
2702 
2703 		delay_info = (struct ctl_io_delay_info *)addr;
2704 
2705 #ifdef CTL_IO_DELAY
2706 		mtx_lock(&softc->ctl_lock);
2707 		if (delay_info->lun_id >= ctl_max_luns ||
2708 		    (lun = softc->ctl_luns[delay_info->lun_id]) == NULL) {
2709 			mtx_unlock(&softc->ctl_lock);
2710 			delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2711 			break;
2712 		}
2713 		mtx_lock(&lun->lun_lock);
2714 		mtx_unlock(&softc->ctl_lock);
2715 		delay_info->status = CTL_DELAY_STATUS_OK;
2716 		switch (delay_info->delay_type) {
2717 		case CTL_DELAY_TYPE_CONT:
2718 		case CTL_DELAY_TYPE_ONESHOT:
2719 			break;
2720 		default:
2721 			delay_info->status = CTL_DELAY_STATUS_INVALID_TYPE;
2722 			break;
2723 		}
2724 		switch (delay_info->delay_loc) {
2725 		case CTL_DELAY_LOC_DATAMOVE:
2726 			lun->delay_info.datamove_type = delay_info->delay_type;
2727 			lun->delay_info.datamove_delay = delay_info->delay_secs;
2728 			break;
2729 		case CTL_DELAY_LOC_DONE:
2730 			lun->delay_info.done_type = delay_info->delay_type;
2731 			lun->delay_info.done_delay = delay_info->delay_secs;
2732 			break;
2733 		default:
2734 			delay_info->status = CTL_DELAY_STATUS_INVALID_LOC;
2735 			break;
2736 		}
2737 		mtx_unlock(&lun->lun_lock);
2738 #else
2739 		delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2740 #endif /* CTL_IO_DELAY */
2741 		break;
2742 	}
2743 	case CTL_ERROR_INJECT: {
2744 		struct ctl_error_desc *err_desc, *new_err_desc;
2745 
2746 		err_desc = (struct ctl_error_desc *)addr;
2747 
2748 		new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2749 				      M_WAITOK | M_ZERO);
2750 		bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2751 
2752 		mtx_lock(&softc->ctl_lock);
2753 		if (err_desc->lun_id >= ctl_max_luns ||
2754 		    (lun = softc->ctl_luns[err_desc->lun_id]) == NULL) {
2755 			mtx_unlock(&softc->ctl_lock);
2756 			free(new_err_desc, M_CTL);
2757 			printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
2758 			       __func__, (uintmax_t)err_desc->lun_id);
2759 			retval = EINVAL;
2760 			break;
2761 		}
2762 		mtx_lock(&lun->lun_lock);
2763 		mtx_unlock(&softc->ctl_lock);
2764 
2765 		/*
2766 		 * We could do some checking here to verify the validity
2767 		 * of the request, but given the complexity of error
2768 		 * injection requests, the checking logic would be fairly
2769 		 * complex.
2770 		 *
2771 		 * For now, if the request is invalid, it just won't get
2772 		 * executed and might get deleted.
2773 		 */
2774 		STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
2775 
2776 		/*
2777 		 * XXX KDM check to make sure the serial number is unique,
2778 		 * in case we somehow manage to wrap.  That shouldn't
2779 		 * happen for a very long time, but it's the right thing to
2780 		 * do.
2781 		 */
2782 		new_err_desc->serial = lun->error_serial;
2783 		err_desc->serial = lun->error_serial;
2784 		lun->error_serial++;
2785 
2786 		mtx_unlock(&lun->lun_lock);
2787 		break;
2788 	}
2789 	case CTL_ERROR_INJECT_DELETE: {
2790 		struct ctl_error_desc *delete_desc, *desc, *desc2;
2791 		int delete_done;
2792 
2793 		delete_desc = (struct ctl_error_desc *)addr;
2794 		delete_done = 0;
2795 
2796 		mtx_lock(&softc->ctl_lock);
2797 		if (delete_desc->lun_id >= ctl_max_luns ||
2798 		    (lun = softc->ctl_luns[delete_desc->lun_id]) == NULL) {
2799 			mtx_unlock(&softc->ctl_lock);
2800 			printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
2801 			       __func__, (uintmax_t)delete_desc->lun_id);
2802 			retval = EINVAL;
2803 			break;
2804 		}
2805 		mtx_lock(&lun->lun_lock);
2806 		mtx_unlock(&softc->ctl_lock);
2807 		STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
2808 			if (desc->serial != delete_desc->serial)
2809 				continue;
2810 
2811 			STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
2812 				      links);
2813 			free(desc, M_CTL);
2814 			delete_done = 1;
2815 		}
2816 		mtx_unlock(&lun->lun_lock);
2817 		if (delete_done == 0) {
2818 			printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
2819 			       "error serial %ju on LUN %u\n", __func__,
2820 			       delete_desc->serial, delete_desc->lun_id);
2821 			retval = EINVAL;
2822 			break;
2823 		}
2824 		break;
2825 	}
2826 	case CTL_DUMP_STRUCTS: {
2827 		int j, k;
2828 		struct ctl_port *port;
2829 		struct ctl_frontend *fe;
2830 
2831 		mtx_lock(&softc->ctl_lock);
2832 		printf("CTL Persistent Reservation information start:\n");
2833 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
2834 			mtx_lock(&lun->lun_lock);
2835 			if ((lun->flags & CTL_LUN_DISABLED) != 0) {
2836 				mtx_unlock(&lun->lun_lock);
2837 				continue;
2838 			}
2839 
2840 			for (j = 0; j < ctl_max_ports; j++) {
2841 				if (lun->pr_keys[j] == NULL)
2842 					continue;
2843 				for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
2844 					if (lun->pr_keys[j][k] == 0)
2845 						continue;
2846 					printf("  LUN %ju port %d iid %d key "
2847 					       "%#jx\n", lun->lun, j, k,
2848 					       (uintmax_t)lun->pr_keys[j][k]);
2849 				}
2850 			}
2851 			mtx_unlock(&lun->lun_lock);
2852 		}
2853 		printf("CTL Persistent Reservation information end\n");
2854 		printf("CTL Ports:\n");
2855 		STAILQ_FOREACH(port, &softc->port_list, links) {
2856 			printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
2857 			       "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
2858 			       port->frontend->name, port->port_type,
2859 			       port->physical_port, port->virtual_port,
2860 			       (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
2861 			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
2862 				if (port->wwpn_iid[j].in_use == 0 &&
2863 				    port->wwpn_iid[j].wwpn == 0 &&
2864 				    port->wwpn_iid[j].name == NULL)
2865 					continue;
2866 
2867 				printf("    iid %u use %d WWPN %#jx '%s'\n",
2868 				    j, port->wwpn_iid[j].in_use,
2869 				    (uintmax_t)port->wwpn_iid[j].wwpn,
2870 				    port->wwpn_iid[j].name);
2871 			}
2872 		}
2873 		printf("CTL Port information end\n");
2874 		mtx_unlock(&softc->ctl_lock);
2875 		/*
2876 		 * XXX KDM calling this without a lock.  We'd likely want
2877 		 * to drop the lock before calling the frontend's dump
2878 		 * routine anyway.
2879 		 */
2880 		printf("CTL Frontends:\n");
2881 		STAILQ_FOREACH(fe, &softc->fe_list, links) {
2882 			printf("  Frontend '%s'\n", fe->name);
2883 			if (fe->fe_dump != NULL)
2884 				fe->fe_dump();
2885 		}
2886 		printf("CTL Frontend information end\n");
2887 		break;
2888 	}
2889 	case CTL_LUN_REQ: {
2890 		struct ctl_lun_req *lun_req;
2891 		struct ctl_backend_driver *backend;
2892 		void *packed;
2893 		nvlist_t *tmp_args_nvl;
2894 		size_t packed_len;
2895 
2896 		lun_req = (struct ctl_lun_req *)addr;
2897 		tmp_args_nvl = lun_req->args_nvl;
2898 
2899 		backend = ctl_backend_find(lun_req->backend);
2900 		if (backend == NULL) {
2901 			lun_req->status = CTL_LUN_ERROR;
2902 			snprintf(lun_req->error_str,
2903 				 sizeof(lun_req->error_str),
2904 				 "Backend \"%s\" not found.",
2905 				 lun_req->backend);
2906 			break;
2907 		}
2908 
2909 		if (lun_req->args != NULL) {
2910 			packed = malloc(lun_req->args_len, M_CTL, M_WAITOK);
2911 			if (copyin(lun_req->args, packed, lun_req->args_len) != 0) {
2912 				free(packed, M_CTL);
2913 				lun_req->status = CTL_LUN_ERROR;
2914 				snprintf(lun_req->error_str, sizeof(lun_req->error_str),
2915 				    "Cannot copyin args.");
2916 				break;
2917 			}
2918 			lun_req->args_nvl = nvlist_unpack(packed,
2919 			    lun_req->args_len, 0);
2920 			free(packed, M_CTL);
2921 
2922 			if (lun_req->args_nvl == NULL) {
2923 				lun_req->status = CTL_LUN_ERROR;
2924 				snprintf(lun_req->error_str, sizeof(lun_req->error_str),
2925 				    "Cannot unpack args nvlist.");
2926 				break;
2927 			}
2928 		} else
2929 			lun_req->args_nvl = nvlist_create(0);
2930 
2931 		retval = backend->ioctl(dev, cmd, addr, flag, td);
2932 		nvlist_destroy(lun_req->args_nvl);
2933 		lun_req->args_nvl = tmp_args_nvl;
2934 
2935 		if (lun_req->result_nvl != NULL) {
2936 			if (lun_req->result != NULL) {
2937 				packed = nvlist_pack(lun_req->result_nvl,
2938 				    &packed_len);
2939 				if (packed == NULL) {
2940 					lun_req->status = CTL_LUN_ERROR;
2941 					snprintf(lun_req->error_str,
2942 					    sizeof(lun_req->error_str),
2943 					    "Cannot pack result nvlist.");
2944 					break;
2945 				}
2946 
2947 				if (packed_len > lun_req->result_len) {
2948 					lun_req->status = CTL_LUN_ERROR;
2949 					snprintf(lun_req->error_str,
2950 					    sizeof(lun_req->error_str),
2951 					    "Result nvlist too large.");
2952 					free(packed, M_NVLIST);
2953 					break;
2954 				}
2955 
2956 				if (copyout(packed, lun_req->result, packed_len)) {
2957 					lun_req->status = CTL_LUN_ERROR;
2958 					snprintf(lun_req->error_str,
2959 					    sizeof(lun_req->error_str),
2960 					    "Cannot copyout() the result.");
2961 					free(packed, M_NVLIST);
2962 					break;
2963 				}
2964 
2965 				lun_req->result_len = packed_len;
2966 				free(packed, M_NVLIST);
2967 			}
2968 
2969 			nvlist_destroy(lun_req->result_nvl);
2970 		}
2971 		break;
2972 	}
2973 	case CTL_LUN_LIST: {
2974 		struct sbuf *sb;
2975 		struct ctl_lun_list *list;
2976 		const char *name, *value;
2977 		void *cookie;
2978 		int type;
2979 
2980 		list = (struct ctl_lun_list *)addr;
2981 
2982 		/*
2983 		 * Allocate a fixed length sbuf here, based on the length
2984 		 * of the user's buffer.  We could allocate an auto-extending
2985 		 * buffer, and then tell the user how much larger our
2986 		 * amount of data is than his buffer, but that presents
2987 		 * some problems:
2988 		 *
2989 		 * 1.  The sbuf(9) routines use a blocking malloc, and so
2990 		 *     we can't hold a lock while calling them with an
2991 		 *     auto-extending buffer.
2992  		 *
2993 		 * 2.  There is not currently a LUN reference counting
2994 		 *     mechanism, outside of outstanding transactions on
2995 		 *     the LUN's OOA queue.  So a LUN could go away on us
2996 		 *     while we're getting the LUN number, backend-specific
2997 		 *     information, etc.  Thus, given the way things
2998 		 *     currently work, we need to hold the CTL lock while
2999 		 *     grabbing LUN information.
3000 		 *
3001 		 * So, from the user's standpoint, the best thing to do is
3002 		 * allocate what he thinks is a reasonable buffer length,
3003 		 * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
3004 		 * double the buffer length and try again.  (And repeat
3005 		 * that until he succeeds.)
3006 		 */
3007 		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3008 		if (sb == NULL) {
3009 			list->status = CTL_LUN_LIST_ERROR;
3010 			snprintf(list->error_str, sizeof(list->error_str),
3011 				 "Unable to allocate %d bytes for LUN list",
3012 				 list->alloc_len);
3013 			break;
3014 		}
3015 
3016 		sbuf_printf(sb, "<ctllunlist>\n");
3017 
3018 		mtx_lock(&softc->ctl_lock);
3019 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
3020 			mtx_lock(&lun->lun_lock);
3021 			retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3022 					     (uintmax_t)lun->lun);
3023 
3024 			/*
3025 			 * Bail out as soon as we see that we've overfilled
3026 			 * the buffer.
3027 			 */
3028 			if (retval != 0)
3029 				break;
3030 
3031 			retval = sbuf_printf(sb, "\t<backend_type>%s"
3032 					     "</backend_type>\n",
3033 					     (lun->backend == NULL) ?  "none" :
3034 					     lun->backend->name);
3035 
3036 			if (retval != 0)
3037 				break;
3038 
3039 			retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3040 					     lun->be_lun->lun_type);
3041 
3042 			if (retval != 0)
3043 				break;
3044 
3045 			if (lun->backend == NULL) {
3046 				retval = sbuf_printf(sb, "</lun>\n");
3047 				if (retval != 0)
3048 					break;
3049 				continue;
3050 			}
3051 
3052 			retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3053 					     (lun->be_lun->maxlba > 0) ?
3054 					     lun->be_lun->maxlba + 1 : 0);
3055 
3056 			if (retval != 0)
3057 				break;
3058 
3059 			retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3060 					     lun->be_lun->blocksize);
3061 
3062 			if (retval != 0)
3063 				break;
3064 
3065 			retval = sbuf_printf(sb, "\t<serial_number>");
3066 
3067 			if (retval != 0)
3068 				break;
3069 
3070 			retval = ctl_sbuf_printf_esc(sb,
3071 			    lun->be_lun->serial_num,
3072 			    sizeof(lun->be_lun->serial_num));
3073 
3074 			if (retval != 0)
3075 				break;
3076 
3077 			retval = sbuf_printf(sb, "</serial_number>\n");
3078 
3079 			if (retval != 0)
3080 				break;
3081 
3082 			retval = sbuf_printf(sb, "\t<device_id>");
3083 
3084 			if (retval != 0)
3085 				break;
3086 
3087 			retval = ctl_sbuf_printf_esc(sb,
3088 			    lun->be_lun->device_id,
3089 			    sizeof(lun->be_lun->device_id));
3090 
3091 			if (retval != 0)
3092 				break;
3093 
3094 			retval = sbuf_printf(sb, "</device_id>\n");
3095 
3096 			if (retval != 0)
3097 				break;
3098 
3099 			if (lun->backend->lun_info != NULL) {
3100 				retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
3101 				if (retval != 0)
3102 					break;
3103 			}
3104 
3105 			cookie = NULL;
3106 			while ((name = nvlist_next(lun->be_lun->options, &type,
3107 			    &cookie)) != NULL) {
3108 				sbuf_printf(sb, "\t<%s>", name);
3109 
3110 				if (type == NV_TYPE_STRING) {
3111 					value = dnvlist_get_string(
3112 					    lun->be_lun->options, name, NULL);
3113 					if (value != NULL)
3114 						sbuf_printf(sb, "%s", value);
3115 				}
3116 
3117 				sbuf_printf(sb, "</%s>\n", name);
3118 			}
3119 
3120 			retval = sbuf_printf(sb, "</lun>\n");
3121 
3122 			if (retval != 0)
3123 				break;
3124 			mtx_unlock(&lun->lun_lock);
3125 		}
3126 		if (lun != NULL)
3127 			mtx_unlock(&lun->lun_lock);
3128 		mtx_unlock(&softc->ctl_lock);
3129 
3130 		if ((retval != 0)
3131 		 || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3132 			retval = 0;
3133 			sbuf_delete(sb);
3134 			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3135 			snprintf(list->error_str, sizeof(list->error_str),
3136 				 "Out of space, %d bytes is too small",
3137 				 list->alloc_len);
3138 			break;
3139 		}
3140 
3141 		sbuf_finish(sb);
3142 
3143 		retval = copyout(sbuf_data(sb), list->lun_xml,
3144 				 sbuf_len(sb) + 1);
3145 
3146 		list->fill_len = sbuf_len(sb) + 1;
3147 		list->status = CTL_LUN_LIST_OK;
3148 		sbuf_delete(sb);
3149 		break;
3150 	}
3151 	case CTL_ISCSI: {
3152 		struct ctl_iscsi *ci;
3153 		struct ctl_frontend *fe;
3154 
3155 		ci = (struct ctl_iscsi *)addr;
3156 
3157 		fe = ctl_frontend_find("iscsi");
3158 		if (fe == NULL) {
3159 			ci->status = CTL_ISCSI_ERROR;
3160 			snprintf(ci->error_str, sizeof(ci->error_str),
3161 			    "Frontend \"iscsi\" not found.");
3162 			break;
3163 		}
3164 
3165 		retval = fe->ioctl(dev, cmd, addr, flag, td);
3166 		break;
3167 	}
3168 	case CTL_PORT_REQ: {
3169 		struct ctl_req *req;
3170 		struct ctl_frontend *fe;
3171 		void *packed;
3172 		nvlist_t *tmp_args_nvl;
3173 		size_t packed_len;
3174 
3175 		req = (struct ctl_req *)addr;
3176 		tmp_args_nvl = req->args_nvl;
3177 
3178 		fe = ctl_frontend_find(req->driver);
3179 		if (fe == NULL) {
3180 			req->status = CTL_LUN_ERROR;
3181 			snprintf(req->error_str, sizeof(req->error_str),
3182 			    "Frontend \"%s\" not found.", req->driver);
3183 			break;
3184 		}
3185 
3186 		if (req->args != NULL) {
3187 			packed = malloc(req->args_len, M_CTL, M_WAITOK);
3188 			if (copyin(req->args, packed, req->args_len) != 0) {
3189 				free(packed, M_CTL);
3190 				req->status = CTL_LUN_ERROR;
3191 				snprintf(req->error_str, sizeof(req->error_str),
3192 				    "Cannot copyin args.");
3193 				break;
3194 			}
3195 			req->args_nvl = nvlist_unpack(packed,
3196 			    req->args_len, 0);
3197 			free(packed, M_CTL);
3198 
3199 			if (req->args_nvl == NULL) {
3200 				req->status = CTL_LUN_ERROR;
3201 				snprintf(req->error_str, sizeof(req->error_str),
3202 				    "Cannot unpack args nvlist.");
3203 				break;
3204 			}
3205 		} else
3206 			req->args_nvl = nvlist_create(0);
3207 
3208 		if (fe->ioctl)
3209 			retval = fe->ioctl(dev, cmd, addr, flag, td);
3210 		else
3211 			retval = ENODEV;
3212 
3213 		nvlist_destroy(req->args_nvl);
3214 		req->args_nvl = tmp_args_nvl;
3215 
3216 		if (req->result_nvl != NULL) {
3217 			if (req->result != NULL) {
3218 				packed = nvlist_pack(req->result_nvl,
3219 				    &packed_len);
3220 				if (packed == NULL) {
3221 					req->status = CTL_LUN_ERROR;
3222 					snprintf(req->error_str,
3223 					    sizeof(req->error_str),
3224 					    "Cannot pack result nvlist.");
3225 					break;
3226 				}
3227 
3228 				if (packed_len > req->result_len) {
3229 					req->status = CTL_LUN_ERROR;
3230 					snprintf(req->error_str,
3231 					    sizeof(req->error_str),
3232 					    "Result nvlist too large.");
3233 					free(packed, M_NVLIST);
3234 					break;
3235 				}
3236 
3237 				if (copyout(packed, req->result, packed_len)) {
3238 					req->status = CTL_LUN_ERROR;
3239 					snprintf(req->error_str,
3240 					    sizeof(req->error_str),
3241 					    "Cannot copyout() the result.");
3242 					free(packed, M_NVLIST);
3243 					break;
3244 				}
3245 
3246 				req->result_len = packed_len;
3247 				free(packed, M_NVLIST);
3248 			}
3249 
3250 			nvlist_destroy(req->result_nvl);
3251 		}
3252 		break;
3253 	}
3254 	case CTL_PORT_LIST: {
3255 		struct sbuf *sb;
3256 		struct ctl_port *port;
3257 		struct ctl_lun_list *list;
3258 		const char *name, *value;
3259 		void *cookie;
3260 		int j, type;
3261 		uint32_t plun;
3262 
3263 		list = (struct ctl_lun_list *)addr;
3264 
3265 		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3266 		if (sb == NULL) {
3267 			list->status = CTL_LUN_LIST_ERROR;
3268 			snprintf(list->error_str, sizeof(list->error_str),
3269 				 "Unable to allocate %d bytes for LUN list",
3270 				 list->alloc_len);
3271 			break;
3272 		}
3273 
3274 		sbuf_printf(sb, "<ctlportlist>\n");
3275 
3276 		mtx_lock(&softc->ctl_lock);
3277 		STAILQ_FOREACH(port, &softc->port_list, links) {
3278 			retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3279 					     (uintmax_t)port->targ_port);
3280 
3281 			/*
3282 			 * Bail out as soon as we see that we've overfilled
3283 			 * the buffer.
3284 			 */
3285 			if (retval != 0)
3286 				break;
3287 
3288 			retval = sbuf_printf(sb, "\t<frontend_type>%s"
3289 			    "</frontend_type>\n", port->frontend->name);
3290 			if (retval != 0)
3291 				break;
3292 
3293 			retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3294 					     port->port_type);
3295 			if (retval != 0)
3296 				break;
3297 
3298 			retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3299 			    (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3300 			if (retval != 0)
3301 				break;
3302 
3303 			retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3304 			    port->port_name);
3305 			if (retval != 0)
3306 				break;
3307 
3308 			retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3309 			    port->physical_port);
3310 			if (retval != 0)
3311 				break;
3312 
3313 			retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3314 			    port->virtual_port);
3315 			if (retval != 0)
3316 				break;
3317 
3318 			if (port->target_devid != NULL) {
3319 				sbuf_printf(sb, "\t<target>");
3320 				ctl_id_sbuf(port->target_devid, sb);
3321 				sbuf_printf(sb, "</target>\n");
3322 			}
3323 
3324 			if (port->port_devid != NULL) {
3325 				sbuf_printf(sb, "\t<port>");
3326 				ctl_id_sbuf(port->port_devid, sb);
3327 				sbuf_printf(sb, "</port>\n");
3328 			}
3329 
3330 			if (port->port_info != NULL) {
3331 				retval = port->port_info(port->onoff_arg, sb);
3332 				if (retval != 0)
3333 					break;
3334 			}
3335 
3336 			cookie = NULL;
3337 			while ((name = nvlist_next(port->options, &type,
3338 			    &cookie)) != NULL) {
3339 				sbuf_printf(sb, "\t<%s>", name);
3340 
3341 				if (type == NV_TYPE_STRING) {
3342 					value = dnvlist_get_string(port->options,
3343 					    name, NULL);
3344 					if (value != NULL)
3345 						sbuf_printf(sb, "%s", value);
3346 				}
3347 
3348 				sbuf_printf(sb, "</%s>\n", name);
3349 			}
3350 
3351 			if (port->lun_map != NULL) {
3352 				sbuf_printf(sb, "\t<lun_map>on</lun_map>\n");
3353 				for (j = 0; j < port->lun_map_size; j++) {
3354 					plun = ctl_lun_map_from_port(port, j);
3355 					if (plun == UINT32_MAX)
3356 						continue;
3357 					sbuf_printf(sb,
3358 					    "\t<lun id=\"%u\">%u</lun>\n",
3359 					    j, plun);
3360 				}
3361 			}
3362 
3363 			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3364 				if (port->wwpn_iid[j].in_use == 0 ||
3365 				    (port->wwpn_iid[j].wwpn == 0 &&
3366 				     port->wwpn_iid[j].name == NULL))
3367 					continue;
3368 
3369 				if (port->wwpn_iid[j].name != NULL)
3370 					retval = sbuf_printf(sb,
3371 					    "\t<initiator id=\"%u\">%s</initiator>\n",
3372 					    j, port->wwpn_iid[j].name);
3373 				else
3374 					retval = sbuf_printf(sb,
3375 					    "\t<initiator id=\"%u\">naa.%08jx</initiator>\n",
3376 					    j, port->wwpn_iid[j].wwpn);
3377 				if (retval != 0)
3378 					break;
3379 			}
3380 			if (retval != 0)
3381 				break;
3382 
3383 			retval = sbuf_printf(sb, "</targ_port>\n");
3384 			if (retval != 0)
3385 				break;
3386 		}
3387 		mtx_unlock(&softc->ctl_lock);
3388 
3389 		if ((retval != 0)
3390 		 || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3391 			retval = 0;
3392 			sbuf_delete(sb);
3393 			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3394 			snprintf(list->error_str, sizeof(list->error_str),
3395 				 "Out of space, %d bytes is too small",
3396 				 list->alloc_len);
3397 			break;
3398 		}
3399 
3400 		sbuf_finish(sb);
3401 
3402 		retval = copyout(sbuf_data(sb), list->lun_xml,
3403 				 sbuf_len(sb) + 1);
3404 
3405 		list->fill_len = sbuf_len(sb) + 1;
3406 		list->status = CTL_LUN_LIST_OK;
3407 		sbuf_delete(sb);
3408 		break;
3409 	}
3410 	case CTL_LUN_MAP: {
3411 		struct ctl_lun_map *lm  = (struct ctl_lun_map *)addr;
3412 		struct ctl_port *port;
3413 
3414 		mtx_lock(&softc->ctl_lock);
3415 		if (lm->port < softc->port_min ||
3416 		    lm->port >= softc->port_max ||
3417 		    (port = softc->ctl_ports[lm->port]) == NULL) {
3418 			mtx_unlock(&softc->ctl_lock);
3419 			return (ENXIO);
3420 		}
3421 		if (port->status & CTL_PORT_STATUS_ONLINE) {
3422 			STAILQ_FOREACH(lun, &softc->lun_list, links) {
3423 				if (ctl_lun_map_to_port(port, lun->lun) ==
3424 				    UINT32_MAX)
3425 					continue;
3426 				mtx_lock(&lun->lun_lock);
3427 				ctl_est_ua_port(lun, lm->port, -1,
3428 				    CTL_UA_LUN_CHANGE);
3429 				mtx_unlock(&lun->lun_lock);
3430 			}
3431 		}
3432 		mtx_unlock(&softc->ctl_lock); // XXX: port_enable sleeps
3433 		if (lm->plun != UINT32_MAX) {
3434 			if (lm->lun == UINT32_MAX)
3435 				retval = ctl_lun_map_unset(port, lm->plun);
3436 			else if (lm->lun < ctl_max_luns &&
3437 			    softc->ctl_luns[lm->lun] != NULL)
3438 				retval = ctl_lun_map_set(port, lm->plun, lm->lun);
3439 			else
3440 				return (ENXIO);
3441 		} else {
3442 			if (lm->lun == UINT32_MAX)
3443 				retval = ctl_lun_map_deinit(port);
3444 			else
3445 				retval = ctl_lun_map_init(port);
3446 		}
3447 		if (port->status & CTL_PORT_STATUS_ONLINE)
3448 			ctl_isc_announce_port(port);
3449 		break;
3450 	}
3451 	case CTL_GET_LUN_STATS: {
3452 		struct ctl_get_io_stats *stats = (struct ctl_get_io_stats *)addr;
3453 		int i;
3454 
3455 		/*
3456 		 * XXX KDM no locking here.  If the LUN list changes,
3457 		 * things can blow up.
3458 		 */
3459 		i = 0;
3460 		stats->status = CTL_SS_OK;
3461 		stats->fill_len = 0;
3462 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
3463 			if (lun->lun < stats->first_item)
3464 				continue;
3465 			if (stats->fill_len + sizeof(lun->stats) >
3466 			    stats->alloc_len) {
3467 				stats->status = CTL_SS_NEED_MORE_SPACE;
3468 				break;
3469 			}
3470 			retval = copyout(&lun->stats, &stats->stats[i++],
3471 					 sizeof(lun->stats));
3472 			if (retval != 0)
3473 				break;
3474 			stats->fill_len += sizeof(lun->stats);
3475 		}
3476 		stats->num_items = softc->num_luns;
3477 		stats->flags = CTL_STATS_FLAG_NONE;
3478 #ifdef CTL_TIME_IO
3479 		stats->flags |= CTL_STATS_FLAG_TIME_VALID;
3480 #endif
3481 		getnanouptime(&stats->timestamp);
3482 		break;
3483 	}
3484 	case CTL_GET_PORT_STATS: {
3485 		struct ctl_get_io_stats *stats = (struct ctl_get_io_stats *)addr;
3486 		int i;
3487 
3488 		/*
3489 		 * XXX KDM no locking here.  If the LUN list changes,
3490 		 * things can blow up.
3491 		 */
3492 		i = 0;
3493 		stats->status = CTL_SS_OK;
3494 		stats->fill_len = 0;
3495 		STAILQ_FOREACH(port, &softc->port_list, links) {
3496 			if (port->targ_port < stats->first_item)
3497 				continue;
3498 			if (stats->fill_len + sizeof(port->stats) >
3499 			    stats->alloc_len) {
3500 				stats->status = CTL_SS_NEED_MORE_SPACE;
3501 				break;
3502 			}
3503 			retval = copyout(&port->stats, &stats->stats[i++],
3504 					 sizeof(port->stats));
3505 			if (retval != 0)
3506 				break;
3507 			stats->fill_len += sizeof(port->stats);
3508 		}
3509 		stats->num_items = softc->num_ports;
3510 		stats->flags = CTL_STATS_FLAG_NONE;
3511 #ifdef CTL_TIME_IO
3512 		stats->flags |= CTL_STATS_FLAG_TIME_VALID;
3513 #endif
3514 		getnanouptime(&stats->timestamp);
3515 		break;
3516 	}
3517 	default: {
3518 		/* XXX KDM should we fix this? */
3519 #if 0
3520 		struct ctl_backend_driver *backend;
3521 		unsigned int type;
3522 		int found;
3523 
3524 		found = 0;
3525 
3526 		/*
3527 		 * We encode the backend type as the ioctl type for backend
3528 		 * ioctls.  So parse it out here, and then search for a
3529 		 * backend of this type.
3530 		 */
3531 		type = _IOC_TYPE(cmd);
3532 
3533 		STAILQ_FOREACH(backend, &softc->be_list, links) {
3534 			if (backend->type == type) {
3535 				found = 1;
3536 				break;
3537 			}
3538 		}
3539 		if (found == 0) {
3540 			printf("ctl: unknown ioctl command %#lx or backend "
3541 			       "%d\n", cmd, type);
3542 			retval = EINVAL;
3543 			break;
3544 		}
3545 		retval = backend->ioctl(dev, cmd, addr, flag, td);
3546 #endif
3547 		retval = ENOTTY;
3548 		break;
3549 	}
3550 	}
3551 	return (retval);
3552 }
3553 
3554 uint32_t
3555 ctl_get_initindex(struct ctl_nexus *nexus)
3556 {
3557 	return (nexus->initid + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3558 }
3559 
3560 int
3561 ctl_lun_map_init(struct ctl_port *port)
3562 {
3563 	struct ctl_softc *softc = port->ctl_softc;
3564 	struct ctl_lun *lun;
3565 	int size = ctl_lun_map_size;
3566 	uint32_t i;
3567 
3568 	if (port->lun_map == NULL || port->lun_map_size < size) {
3569 		port->lun_map_size = 0;
3570 		free(port->lun_map, M_CTL);
3571 		port->lun_map = malloc(size * sizeof(uint32_t),
3572 		    M_CTL, M_NOWAIT);
3573 	}
3574 	if (port->lun_map == NULL)
3575 		return (ENOMEM);
3576 	for (i = 0; i < size; i++)
3577 		port->lun_map[i] = UINT32_MAX;
3578 	port->lun_map_size = size;
3579 	if (port->status & CTL_PORT_STATUS_ONLINE) {
3580 		if (port->lun_disable != NULL) {
3581 			STAILQ_FOREACH(lun, &softc->lun_list, links)
3582 				port->lun_disable(port->targ_lun_arg, lun->lun);
3583 		}
3584 		ctl_isc_announce_port(port);
3585 	}
3586 	return (0);
3587 }
3588 
3589 int
3590 ctl_lun_map_deinit(struct ctl_port *port)
3591 {
3592 	struct ctl_softc *softc = port->ctl_softc;
3593 	struct ctl_lun *lun;
3594 
3595 	if (port->lun_map == NULL)
3596 		return (0);
3597 	port->lun_map_size = 0;
3598 	free(port->lun_map, M_CTL);
3599 	port->lun_map = NULL;
3600 	if (port->status & CTL_PORT_STATUS_ONLINE) {
3601 		if (port->lun_enable != NULL) {
3602 			STAILQ_FOREACH(lun, &softc->lun_list, links)
3603 				port->lun_enable(port->targ_lun_arg, lun->lun);
3604 		}
3605 		ctl_isc_announce_port(port);
3606 	}
3607 	return (0);
3608 }
3609 
3610 int
3611 ctl_lun_map_set(struct ctl_port *port, uint32_t plun, uint32_t glun)
3612 {
3613 	int status;
3614 	uint32_t old;
3615 
3616 	if (port->lun_map == NULL) {
3617 		status = ctl_lun_map_init(port);
3618 		if (status != 0)
3619 			return (status);
3620 	}
3621 	if (plun >= port->lun_map_size)
3622 		return (EINVAL);
3623 	old = port->lun_map[plun];
3624 	port->lun_map[plun] = glun;
3625 	if ((port->status & CTL_PORT_STATUS_ONLINE) && old == UINT32_MAX) {
3626 		if (port->lun_enable != NULL)
3627 			port->lun_enable(port->targ_lun_arg, plun);
3628 		ctl_isc_announce_port(port);
3629 	}
3630 	return (0);
3631 }
3632 
3633 int
3634 ctl_lun_map_unset(struct ctl_port *port, uint32_t plun)
3635 {
3636 	uint32_t old;
3637 
3638 	if (port->lun_map == NULL || plun >= port->lun_map_size)
3639 		return (0);
3640 	old = port->lun_map[plun];
3641 	port->lun_map[plun] = UINT32_MAX;
3642 	if ((port->status & CTL_PORT_STATUS_ONLINE) && old != UINT32_MAX) {
3643 		if (port->lun_disable != NULL)
3644 			port->lun_disable(port->targ_lun_arg, plun);
3645 		ctl_isc_announce_port(port);
3646 	}
3647 	return (0);
3648 }
3649 
3650 uint32_t
3651 ctl_lun_map_from_port(struct ctl_port *port, uint32_t lun_id)
3652 {
3653 
3654 	if (port == NULL)
3655 		return (UINT32_MAX);
3656 	if (port->lun_map == NULL)
3657 		return (lun_id);
3658 	if (lun_id > port->lun_map_size)
3659 		return (UINT32_MAX);
3660 	return (port->lun_map[lun_id]);
3661 }
3662 
3663 uint32_t
3664 ctl_lun_map_to_port(struct ctl_port *port, uint32_t lun_id)
3665 {
3666 	uint32_t i;
3667 
3668 	if (port == NULL)
3669 		return (UINT32_MAX);
3670 	if (port->lun_map == NULL)
3671 		return (lun_id);
3672 	for (i = 0; i < port->lun_map_size; i++) {
3673 		if (port->lun_map[i] == lun_id)
3674 			return (i);
3675 	}
3676 	return (UINT32_MAX);
3677 }
3678 
3679 uint32_t
3680 ctl_decode_lun(uint64_t encoded)
3681 {
3682 	uint8_t lun[8];
3683 	uint32_t result = 0xffffffff;
3684 
3685 	be64enc(lun, encoded);
3686 	switch (lun[0] & RPL_LUNDATA_ATYP_MASK) {
3687 	case RPL_LUNDATA_ATYP_PERIPH:
3688 		if ((lun[0] & 0x3f) == 0 && lun[2] == 0 && lun[3] == 0 &&
3689 		    lun[4] == 0 && lun[5] == 0 && lun[6] == 0 && lun[7] == 0)
3690 			result = lun[1];
3691 		break;
3692 	case RPL_LUNDATA_ATYP_FLAT:
3693 		if (lun[2] == 0 && lun[3] == 0 && lun[4] == 0 && lun[5] == 0 &&
3694 		    lun[6] == 0 && lun[7] == 0)
3695 			result = ((lun[0] & 0x3f) << 8) + lun[1];
3696 		break;
3697 	case RPL_LUNDATA_ATYP_EXTLUN:
3698 		switch (lun[0] & RPL_LUNDATA_EXT_EAM_MASK) {
3699 		case 0x02:
3700 			switch (lun[0] & RPL_LUNDATA_EXT_LEN_MASK) {
3701 			case 0x00:
3702 				result = lun[1];
3703 				break;
3704 			case 0x10:
3705 				result = (lun[1] << 16) + (lun[2] << 8) +
3706 				    lun[3];
3707 				break;
3708 			case 0x20:
3709 				if (lun[1] == 0 && lun[6] == 0 && lun[7] == 0)
3710 					result = (lun[2] << 24) +
3711 					    (lun[3] << 16) + (lun[4] << 8) +
3712 					    lun[5];
3713 				break;
3714 			}
3715 			break;
3716 		case RPL_LUNDATA_EXT_EAM_NOT_SPEC:
3717 			result = 0xffffffff;
3718 			break;
3719 		}
3720 		break;
3721 	}
3722 	return (result);
3723 }
3724 
3725 uint64_t
3726 ctl_encode_lun(uint32_t decoded)
3727 {
3728 	uint64_t l = decoded;
3729 
3730 	if (l <= 0xff)
3731 		return (((uint64_t)RPL_LUNDATA_ATYP_PERIPH << 56) | (l << 48));
3732 	if (l <= 0x3fff)
3733 		return (((uint64_t)RPL_LUNDATA_ATYP_FLAT << 56) | (l << 48));
3734 	if (l <= 0xffffff)
3735 		return (((uint64_t)(RPL_LUNDATA_ATYP_EXTLUN | 0x12) << 56) |
3736 		    (l << 32));
3737 	return ((((uint64_t)RPL_LUNDATA_ATYP_EXTLUN | 0x22) << 56) | (l << 16));
3738 }
3739 
3740 int
3741 ctl_ffz(uint32_t *mask, uint32_t first, uint32_t last)
3742 {
3743 	int i;
3744 
3745 	for (i = first; i < last; i++) {
3746 		if ((mask[i / 32] & (1 << (i % 32))) == 0)
3747 			return (i);
3748 	}
3749 	return (-1);
3750 }
3751 
3752 int
3753 ctl_set_mask(uint32_t *mask, uint32_t bit)
3754 {
3755 	uint32_t chunk, piece;
3756 
3757 	chunk = bit >> 5;
3758 	piece = bit % (sizeof(uint32_t) * 8);
3759 
3760 	if ((mask[chunk] & (1 << piece)) != 0)
3761 		return (-1);
3762 	else
3763 		mask[chunk] |= (1 << piece);
3764 
3765 	return (0);
3766 }
3767 
3768 int
3769 ctl_clear_mask(uint32_t *mask, uint32_t bit)
3770 {
3771 	uint32_t chunk, piece;
3772 
3773 	chunk = bit >> 5;
3774 	piece = bit % (sizeof(uint32_t) * 8);
3775 
3776 	if ((mask[chunk] & (1 << piece)) == 0)
3777 		return (-1);
3778 	else
3779 		mask[chunk] &= ~(1 << piece);
3780 
3781 	return (0);
3782 }
3783 
3784 int
3785 ctl_is_set(uint32_t *mask, uint32_t bit)
3786 {
3787 	uint32_t chunk, piece;
3788 
3789 	chunk = bit >> 5;
3790 	piece = bit % (sizeof(uint32_t) * 8);
3791 
3792 	if ((mask[chunk] & (1 << piece)) == 0)
3793 		return (0);
3794 	else
3795 		return (1);
3796 }
3797 
3798 static uint64_t
3799 ctl_get_prkey(struct ctl_lun *lun, uint32_t residx)
3800 {
3801 	uint64_t *t;
3802 
3803 	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3804 	if (t == NULL)
3805 		return (0);
3806 	return (t[residx % CTL_MAX_INIT_PER_PORT]);
3807 }
3808 
3809 static void
3810 ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx)
3811 {
3812 	uint64_t *t;
3813 
3814 	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3815 	if (t == NULL)
3816 		return;
3817 	t[residx % CTL_MAX_INIT_PER_PORT] = 0;
3818 }
3819 
3820 static void
3821 ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx)
3822 {
3823 	uint64_t *p;
3824 	u_int i;
3825 
3826 	i = residx/CTL_MAX_INIT_PER_PORT;
3827 	if (lun->pr_keys[i] != NULL)
3828 		return;
3829 	mtx_unlock(&lun->lun_lock);
3830 	p = malloc(sizeof(uint64_t) * CTL_MAX_INIT_PER_PORT, M_CTL,
3831 	    M_WAITOK | M_ZERO);
3832 	mtx_lock(&lun->lun_lock);
3833 	if (lun->pr_keys[i] == NULL)
3834 		lun->pr_keys[i] = p;
3835 	else
3836 		free(p, M_CTL);
3837 }
3838 
3839 static void
3840 ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key)
3841 {
3842 	uint64_t *t;
3843 
3844 	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3845 	KASSERT(t != NULL, ("prkey %d is not allocated", residx));
3846 	t[residx % CTL_MAX_INIT_PER_PORT] = key;
3847 }
3848 
3849 /*
3850  * ctl_softc, pool_name, total_ctl_io are passed in.
3851  * npool is passed out.
3852  */
3853 int
3854 ctl_pool_create(struct ctl_softc *ctl_softc, const char *pool_name,
3855 		uint32_t total_ctl_io, void **npool)
3856 {
3857 	struct ctl_io_pool *pool;
3858 
3859 	pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3860 					    M_NOWAIT | M_ZERO);
3861 	if (pool == NULL)
3862 		return (ENOMEM);
3863 
3864 	snprintf(pool->name, sizeof(pool->name), "CTL IO %s", pool_name);
3865 	pool->ctl_softc = ctl_softc;
3866 #ifdef IO_POOLS
3867 	pool->zone = uma_zsecond_create(pool->name, NULL,
3868 	    NULL, NULL, NULL, ctl_softc->io_zone);
3869 	/* uma_prealloc(pool->zone, total_ctl_io); */
3870 #else
3871 	pool->zone = ctl_softc->io_zone;
3872 #endif
3873 
3874 	*npool = pool;
3875 	return (0);
3876 }
3877 
3878 void
3879 ctl_pool_free(struct ctl_io_pool *pool)
3880 {
3881 
3882 	if (pool == NULL)
3883 		return;
3884 
3885 #ifdef IO_POOLS
3886 	uma_zdestroy(pool->zone);
3887 #endif
3888 	free(pool, M_CTL);
3889 }
3890 
3891 union ctl_io *
3892 ctl_alloc_io(void *pool_ref)
3893 {
3894 	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3895 	union ctl_io *io;
3896 
3897 	io = uma_zalloc(pool->zone, M_WAITOK);
3898 	if (io != NULL) {
3899 		io->io_hdr.pool = pool_ref;
3900 		CTL_SOFTC(io) = pool->ctl_softc;
3901 		TAILQ_INIT(&io->io_hdr.blocked_queue);
3902 	}
3903 	return (io);
3904 }
3905 
3906 union ctl_io *
3907 ctl_alloc_io_nowait(void *pool_ref)
3908 {
3909 	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3910 	union ctl_io *io;
3911 
3912 	io = uma_zalloc(pool->zone, M_NOWAIT);
3913 	if (io != NULL) {
3914 		io->io_hdr.pool = pool_ref;
3915 		CTL_SOFTC(io) = pool->ctl_softc;
3916 		TAILQ_INIT(&io->io_hdr.blocked_queue);
3917 	}
3918 	return (io);
3919 }
3920 
3921 void
3922 ctl_free_io(union ctl_io *io)
3923 {
3924 	struct ctl_io_pool *pool;
3925 
3926 	if (io == NULL)
3927 		return;
3928 
3929 	pool = (struct ctl_io_pool *)io->io_hdr.pool;
3930 	uma_zfree(pool->zone, io);
3931 }
3932 
3933 void
3934 ctl_zero_io(union ctl_io *io)
3935 {
3936 	struct ctl_io_pool *pool;
3937 
3938 	if (io == NULL)
3939 		return;
3940 
3941 	/*
3942 	 * May need to preserve linked list pointers at some point too.
3943 	 */
3944 	pool = io->io_hdr.pool;
3945 	memset(io, 0, sizeof(*io));
3946 	io->io_hdr.pool = pool;
3947 	CTL_SOFTC(io) = pool->ctl_softc;
3948 	TAILQ_INIT(&io->io_hdr.blocked_queue);
3949 }
3950 
3951 int
3952 ctl_expand_number(const char *buf, uint64_t *num)
3953 {
3954 	char *endptr;
3955 	uint64_t number;
3956 	unsigned shift;
3957 
3958 	number = strtoq(buf, &endptr, 0);
3959 
3960 	switch (tolower((unsigned char)*endptr)) {
3961 	case 'e':
3962 		shift = 60;
3963 		break;
3964 	case 'p':
3965 		shift = 50;
3966 		break;
3967 	case 't':
3968 		shift = 40;
3969 		break;
3970 	case 'g':
3971 		shift = 30;
3972 		break;
3973 	case 'm':
3974 		shift = 20;
3975 		break;
3976 	case 'k':
3977 		shift = 10;
3978 		break;
3979 	case 'b':
3980 	case '\0': /* No unit. */
3981 		*num = number;
3982 		return (0);
3983 	default:
3984 		/* Unrecognized unit. */
3985 		return (-1);
3986 	}
3987 
3988 	if ((number << shift) >> shift != number) {
3989 		/* Overflow */
3990 		return (-1);
3991 	}
3992 	*num = number << shift;
3993 	return (0);
3994 }
3995 
3996 
3997 /*
3998  * This routine could be used in the future to load default and/or saved
3999  * mode page parameters for a particuar lun.
4000  */
4001 static int
4002 ctl_init_page_index(struct ctl_lun *lun)
4003 {
4004 	int i, page_code;
4005 	struct ctl_page_index *page_index;
4006 	const char *value;
4007 	uint64_t ival;
4008 
4009 	memcpy(&lun->mode_pages.index, page_index_template,
4010 	       sizeof(page_index_template));
4011 
4012 	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
4013 
4014 		page_index = &lun->mode_pages.index[i];
4015 		if (lun->be_lun->lun_type == T_DIRECT &&
4016 		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
4017 			continue;
4018 		if (lun->be_lun->lun_type == T_PROCESSOR &&
4019 		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
4020 			continue;
4021 		if (lun->be_lun->lun_type == T_CDROM &&
4022 		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
4023 			continue;
4024 
4025 		page_code = page_index->page_code & SMPH_PC_MASK;
4026 		switch (page_code) {
4027 		case SMS_RW_ERROR_RECOVERY_PAGE: {
4028 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4029 			    ("subpage %#x for page %#x is incorrect!",
4030 			    page_index->subpage, page_code));
4031 			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT],
4032 			       &rw_er_page_default,
4033 			       sizeof(rw_er_page_default));
4034 			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CHANGEABLE],
4035 			       &rw_er_page_changeable,
4036 			       sizeof(rw_er_page_changeable));
4037 			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_DEFAULT],
4038 			       &rw_er_page_default,
4039 			       sizeof(rw_er_page_default));
4040 			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_SAVED],
4041 			       &rw_er_page_default,
4042 			       sizeof(rw_er_page_default));
4043 			page_index->page_data =
4044 				(uint8_t *)lun->mode_pages.rw_er_page;
4045 			break;
4046 		}
4047 		case SMS_FORMAT_DEVICE_PAGE: {
4048 			struct scsi_format_page *format_page;
4049 
4050 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4051 			    ("subpage %#x for page %#x is incorrect!",
4052 			    page_index->subpage, page_code));
4053 
4054 			/*
4055 			 * Sectors per track are set above.  Bytes per
4056 			 * sector need to be set here on a per-LUN basis.
4057 			 */
4058 			memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
4059 			       &format_page_default,
4060 			       sizeof(format_page_default));
4061 			memcpy(&lun->mode_pages.format_page[
4062 			       CTL_PAGE_CHANGEABLE], &format_page_changeable,
4063 			       sizeof(format_page_changeable));
4064 			memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
4065 			       &format_page_default,
4066 			       sizeof(format_page_default));
4067 			memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
4068 			       &format_page_default,
4069 			       sizeof(format_page_default));
4070 
4071 			format_page = &lun->mode_pages.format_page[
4072 				CTL_PAGE_CURRENT];
4073 			scsi_ulto2b(lun->be_lun->blocksize,
4074 				    format_page->bytes_per_sector);
4075 
4076 			format_page = &lun->mode_pages.format_page[
4077 				CTL_PAGE_DEFAULT];
4078 			scsi_ulto2b(lun->be_lun->blocksize,
4079 				    format_page->bytes_per_sector);
4080 
4081 			format_page = &lun->mode_pages.format_page[
4082 				CTL_PAGE_SAVED];
4083 			scsi_ulto2b(lun->be_lun->blocksize,
4084 				    format_page->bytes_per_sector);
4085 
4086 			page_index->page_data =
4087 				(uint8_t *)lun->mode_pages.format_page;
4088 			break;
4089 		}
4090 		case SMS_RIGID_DISK_PAGE: {
4091 			struct scsi_rigid_disk_page *rigid_disk_page;
4092 			uint32_t sectors_per_cylinder;
4093 			uint64_t cylinders;
4094 #ifndef	__XSCALE__
4095 			int shift;
4096 #endif /* !__XSCALE__ */
4097 
4098 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4099 			    ("subpage %#x for page %#x is incorrect!",
4100 			    page_index->subpage, page_code));
4101 
4102 			/*
4103 			 * Rotation rate and sectors per track are set
4104 			 * above.  We calculate the cylinders here based on
4105 			 * capacity.  Due to the number of heads and
4106 			 * sectors per track we're using, smaller arrays
4107 			 * may turn out to have 0 cylinders.  Linux and
4108 			 * FreeBSD don't pay attention to these mode pages
4109 			 * to figure out capacity, but Solaris does.  It
4110 			 * seems to deal with 0 cylinders just fine, and
4111 			 * works out a fake geometry based on the capacity.
4112 			 */
4113 			memcpy(&lun->mode_pages.rigid_disk_page[
4114 			       CTL_PAGE_DEFAULT], &rigid_disk_page_default,
4115 			       sizeof(rigid_disk_page_default));
4116 			memcpy(&lun->mode_pages.rigid_disk_page[
4117 			       CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
4118 			       sizeof(rigid_disk_page_changeable));
4119 
4120 			sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
4121 				CTL_DEFAULT_HEADS;
4122 
4123 			/*
4124 			 * The divide method here will be more accurate,
4125 			 * probably, but results in floating point being
4126 			 * used in the kernel on i386 (__udivdi3()).  On the
4127 			 * XScale, though, __udivdi3() is implemented in
4128 			 * software.
4129 			 *
4130 			 * The shift method for cylinder calculation is
4131 			 * accurate if sectors_per_cylinder is a power of
4132 			 * 2.  Otherwise it might be slightly off -- you
4133 			 * might have a bit of a truncation problem.
4134 			 */
4135 #ifdef	__XSCALE__
4136 			cylinders = (lun->be_lun->maxlba + 1) /
4137 				sectors_per_cylinder;
4138 #else
4139 			for (shift = 31; shift > 0; shift--) {
4140 				if (sectors_per_cylinder & (1 << shift))
4141 					break;
4142 			}
4143 			cylinders = (lun->be_lun->maxlba + 1) >> shift;
4144 #endif
4145 
4146 			/*
4147 			 * We've basically got 3 bytes, or 24 bits for the
4148 			 * cylinder size in the mode page.  If we're over,
4149 			 * just round down to 2^24.
4150 			 */
4151 			if (cylinders > 0xffffff)
4152 				cylinders = 0xffffff;
4153 
4154 			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4155 				CTL_PAGE_DEFAULT];
4156 			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4157 
4158 			if ((value = dnvlist_get_string(lun->be_lun->options,
4159 			    "rpm", NULL)) != NULL) {
4160 				scsi_ulto2b(strtol(value, NULL, 0),
4161 				     rigid_disk_page->rotation_rate);
4162 			}
4163 
4164 			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_CURRENT],
4165 			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4166 			       sizeof(rigid_disk_page_default));
4167 			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_SAVED],
4168 			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4169 			       sizeof(rigid_disk_page_default));
4170 
4171 			page_index->page_data =
4172 				(uint8_t *)lun->mode_pages.rigid_disk_page;
4173 			break;
4174 		}
4175 		case SMS_VERIFY_ERROR_RECOVERY_PAGE: {
4176 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4177 			    ("subpage %#x for page %#x is incorrect!",
4178 			    page_index->subpage, page_code));
4179 			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_CURRENT],
4180 			       &verify_er_page_default,
4181 			       sizeof(verify_er_page_default));
4182 			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_CHANGEABLE],
4183 			       &verify_er_page_changeable,
4184 			       sizeof(verify_er_page_changeable));
4185 			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_DEFAULT],
4186 			       &verify_er_page_default,
4187 			       sizeof(verify_er_page_default));
4188 			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_SAVED],
4189 			       &verify_er_page_default,
4190 			       sizeof(verify_er_page_default));
4191 			page_index->page_data =
4192 				(uint8_t *)lun->mode_pages.verify_er_page;
4193 			break;
4194 		}
4195 		case SMS_CACHING_PAGE: {
4196 			struct scsi_caching_page *caching_page;
4197 
4198 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4199 			    ("subpage %#x for page %#x is incorrect!",
4200 			    page_index->subpage, page_code));
4201 			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4202 			       &caching_page_default,
4203 			       sizeof(caching_page_default));
4204 			memcpy(&lun->mode_pages.caching_page[
4205 			       CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4206 			       sizeof(caching_page_changeable));
4207 			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4208 			       &caching_page_default,
4209 			       sizeof(caching_page_default));
4210 			caching_page = &lun->mode_pages.caching_page[
4211 			    CTL_PAGE_SAVED];
4212 			value = dnvlist_get_string(lun->be_lun->options,
4213 			    "writecache", NULL);
4214 			if (value != NULL && strcmp(value, "off") == 0)
4215 				caching_page->flags1 &= ~SCP_WCE;
4216 			value = dnvlist_get_string(lun->be_lun->options,
4217 			    "readcache", NULL);
4218 			if (value != NULL && strcmp(value, "off") == 0)
4219 				caching_page->flags1 |= SCP_RCD;
4220 			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4221 			       &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4222 			       sizeof(caching_page_default));
4223 			page_index->page_data =
4224 				(uint8_t *)lun->mode_pages.caching_page;
4225 			break;
4226 		}
4227 		case SMS_CONTROL_MODE_PAGE: {
4228 			switch (page_index->subpage) {
4229 			case SMS_SUBPAGE_PAGE_0: {
4230 				struct scsi_control_page *control_page;
4231 
4232 				memcpy(&lun->mode_pages.control_page[
4233 				    CTL_PAGE_DEFAULT],
4234 				       &control_page_default,
4235 				       sizeof(control_page_default));
4236 				memcpy(&lun->mode_pages.control_page[
4237 				    CTL_PAGE_CHANGEABLE],
4238 				       &control_page_changeable,
4239 				       sizeof(control_page_changeable));
4240 				memcpy(&lun->mode_pages.control_page[
4241 				    CTL_PAGE_SAVED],
4242 				       &control_page_default,
4243 				       sizeof(control_page_default));
4244 				control_page = &lun->mode_pages.control_page[
4245 				    CTL_PAGE_SAVED];
4246 				value = dnvlist_get_string(lun->be_lun->options,
4247 				    "reordering", NULL);
4248 				if (value != NULL &&
4249 				    strcmp(value, "unrestricted") == 0) {
4250 					control_page->queue_flags &=
4251 					    ~SCP_QUEUE_ALG_MASK;
4252 					control_page->queue_flags |=
4253 					    SCP_QUEUE_ALG_UNRESTRICTED;
4254 				}
4255 				memcpy(&lun->mode_pages.control_page[
4256 				    CTL_PAGE_CURRENT],
4257 				       &lun->mode_pages.control_page[
4258 				    CTL_PAGE_SAVED],
4259 				       sizeof(control_page_default));
4260 				page_index->page_data =
4261 				    (uint8_t *)lun->mode_pages.control_page;
4262 				break;
4263 			}
4264 			case 0x01:
4265 				memcpy(&lun->mode_pages.control_ext_page[
4266 				    CTL_PAGE_DEFAULT],
4267 				       &control_ext_page_default,
4268 				       sizeof(control_ext_page_default));
4269 				memcpy(&lun->mode_pages.control_ext_page[
4270 				    CTL_PAGE_CHANGEABLE],
4271 				       &control_ext_page_changeable,
4272 				       sizeof(control_ext_page_changeable));
4273 				memcpy(&lun->mode_pages.control_ext_page[
4274 				    CTL_PAGE_SAVED],
4275 				       &control_ext_page_default,
4276 				       sizeof(control_ext_page_default));
4277 				memcpy(&lun->mode_pages.control_ext_page[
4278 				    CTL_PAGE_CURRENT],
4279 				       &lun->mode_pages.control_ext_page[
4280 				    CTL_PAGE_SAVED],
4281 				       sizeof(control_ext_page_default));
4282 				page_index->page_data =
4283 				    (uint8_t *)lun->mode_pages.control_ext_page;
4284 				break;
4285 			default:
4286 				panic("subpage %#x for page %#x is incorrect!",
4287 				      page_index->subpage, page_code);
4288 			}
4289 			break;
4290 		}
4291 		case SMS_INFO_EXCEPTIONS_PAGE: {
4292 			switch (page_index->subpage) {
4293 			case SMS_SUBPAGE_PAGE_0:
4294 				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_CURRENT],
4295 				       &ie_page_default,
4296 				       sizeof(ie_page_default));
4297 				memcpy(&lun->mode_pages.ie_page[
4298 				       CTL_PAGE_CHANGEABLE], &ie_page_changeable,
4299 				       sizeof(ie_page_changeable));
4300 				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_DEFAULT],
4301 				       &ie_page_default,
4302 				       sizeof(ie_page_default));
4303 				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_SAVED],
4304 				       &ie_page_default,
4305 				       sizeof(ie_page_default));
4306 				page_index->page_data =
4307 					(uint8_t *)lun->mode_pages.ie_page;
4308 				break;
4309 			case 0x02: {
4310 				struct ctl_logical_block_provisioning_page *page;
4311 
4312 				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_DEFAULT],
4313 				       &lbp_page_default,
4314 				       sizeof(lbp_page_default));
4315 				memcpy(&lun->mode_pages.lbp_page[
4316 				       CTL_PAGE_CHANGEABLE], &lbp_page_changeable,
4317 				       sizeof(lbp_page_changeable));
4318 				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4319 				       &lbp_page_default,
4320 				       sizeof(lbp_page_default));
4321 				page = &lun->mode_pages.lbp_page[CTL_PAGE_SAVED];
4322 				value = dnvlist_get_string(lun->be_lun->options,
4323 				    "avail-threshold", NULL);
4324 				if (value != NULL &&
4325 				    ctl_expand_number(value, &ival) == 0) {
4326 					page->descr[0].flags |= SLBPPD_ENABLED |
4327 					    SLBPPD_ARMING_DEC;
4328 					if (lun->be_lun->blocksize)
4329 						ival /= lun->be_lun->blocksize;
4330 					else
4331 						ival /= 512;
4332 					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4333 					    page->descr[0].count);
4334 				}
4335 				value = dnvlist_get_string(lun->be_lun->options,
4336 				    "used-threshold", NULL);
4337 				if (value != NULL &&
4338 				    ctl_expand_number(value, &ival) == 0) {
4339 					page->descr[1].flags |= SLBPPD_ENABLED |
4340 					    SLBPPD_ARMING_INC;
4341 					if (lun->be_lun->blocksize)
4342 						ival /= lun->be_lun->blocksize;
4343 					else
4344 						ival /= 512;
4345 					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4346 					    page->descr[1].count);
4347 				}
4348 				value = dnvlist_get_string(lun->be_lun->options,
4349 				    "pool-avail-threshold", NULL);
4350 				if (value != NULL &&
4351 				    ctl_expand_number(value, &ival) == 0) {
4352 					page->descr[2].flags |= SLBPPD_ENABLED |
4353 					    SLBPPD_ARMING_DEC;
4354 					if (lun->be_lun->blocksize)
4355 						ival /= lun->be_lun->blocksize;
4356 					else
4357 						ival /= 512;
4358 					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4359 					    page->descr[2].count);
4360 				}
4361 				value = dnvlist_get_string(lun->be_lun->options,
4362 				    "pool-used-threshold", NULL);
4363 				if (value != NULL &&
4364 				    ctl_expand_number(value, &ival) == 0) {
4365 					page->descr[3].flags |= SLBPPD_ENABLED |
4366 					    SLBPPD_ARMING_INC;
4367 					if (lun->be_lun->blocksize)
4368 						ival /= lun->be_lun->blocksize;
4369 					else
4370 						ival /= 512;
4371 					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4372 					    page->descr[3].count);
4373 				}
4374 				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_CURRENT],
4375 				       &lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4376 				       sizeof(lbp_page_default));
4377 				page_index->page_data =
4378 					(uint8_t *)lun->mode_pages.lbp_page;
4379 				break;
4380 			}
4381 			default:
4382 				panic("subpage %#x for page %#x is incorrect!",
4383 				      page_index->subpage, page_code);
4384 			}
4385 			break;
4386 		}
4387 		case SMS_CDDVD_CAPS_PAGE:{
4388 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4389 			    ("subpage %#x for page %#x is incorrect!",
4390 			    page_index->subpage, page_code));
4391 			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_DEFAULT],
4392 			       &cddvd_page_default,
4393 			       sizeof(cddvd_page_default));
4394 			memcpy(&lun->mode_pages.cddvd_page[
4395 			       CTL_PAGE_CHANGEABLE], &cddvd_page_changeable,
4396 			       sizeof(cddvd_page_changeable));
4397 			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_SAVED],
4398 			       &cddvd_page_default,
4399 			       sizeof(cddvd_page_default));
4400 			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_CURRENT],
4401 			       &lun->mode_pages.cddvd_page[CTL_PAGE_SAVED],
4402 			       sizeof(cddvd_page_default));
4403 			page_index->page_data =
4404 				(uint8_t *)lun->mode_pages.cddvd_page;
4405 			break;
4406 		}
4407 		default:
4408 			panic("invalid page code value %#x", page_code);
4409 		}
4410 	}
4411 
4412 	return (CTL_RETVAL_COMPLETE);
4413 }
4414 
4415 static int
4416 ctl_init_log_page_index(struct ctl_lun *lun)
4417 {
4418 	struct ctl_page_index *page_index;
4419 	int i, j, k, prev;
4420 
4421 	memcpy(&lun->log_pages.index, log_page_index_template,
4422 	       sizeof(log_page_index_template));
4423 
4424 	prev = -1;
4425 	for (i = 0, j = 0, k = 0; i < CTL_NUM_LOG_PAGES; i++) {
4426 
4427 		page_index = &lun->log_pages.index[i];
4428 		if (lun->be_lun->lun_type == T_DIRECT &&
4429 		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
4430 			continue;
4431 		if (lun->be_lun->lun_type == T_PROCESSOR &&
4432 		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
4433 			continue;
4434 		if (lun->be_lun->lun_type == T_CDROM &&
4435 		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
4436 			continue;
4437 
4438 		if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING &&
4439 		    lun->backend->lun_attr == NULL)
4440 			continue;
4441 
4442 		if (page_index->page_code != prev) {
4443 			lun->log_pages.pages_page[j] = page_index->page_code;
4444 			prev = page_index->page_code;
4445 			j++;
4446 		}
4447 		lun->log_pages.subpages_page[k*2] = page_index->page_code;
4448 		lun->log_pages.subpages_page[k*2+1] = page_index->subpage;
4449 		k++;
4450 	}
4451 	lun->log_pages.index[0].page_data = &lun->log_pages.pages_page[0];
4452 	lun->log_pages.index[0].page_len = j;
4453 	lun->log_pages.index[1].page_data = &lun->log_pages.subpages_page[0];
4454 	lun->log_pages.index[1].page_len = k * 2;
4455 	lun->log_pages.index[2].page_data = (uint8_t *)&lun->log_pages.temp_page;
4456 	lun->log_pages.index[2].page_len = sizeof(lun->log_pages.temp_page);
4457 	lun->log_pages.index[3].page_data = &lun->log_pages.lbp_page[0];
4458 	lun->log_pages.index[3].page_len = 12*CTL_NUM_LBP_PARAMS;
4459 	lun->log_pages.index[4].page_data = (uint8_t *)&lun->log_pages.stat_page;
4460 	lun->log_pages.index[4].page_len = sizeof(lun->log_pages.stat_page);
4461 	lun->log_pages.index[5].page_data = (uint8_t *)&lun->log_pages.ie_page;
4462 	lun->log_pages.index[5].page_len = sizeof(lun->log_pages.ie_page);
4463 
4464 	return (CTL_RETVAL_COMPLETE);
4465 }
4466 
4467 static int
4468 hex2bin(const char *str, uint8_t *buf, int buf_size)
4469 {
4470 	int i;
4471 	u_char c;
4472 
4473 	memset(buf, 0, buf_size);
4474 	while (isspace(str[0]))
4475 		str++;
4476 	if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
4477 		str += 2;
4478 	buf_size *= 2;
4479 	for (i = 0; str[i] != 0 && i < buf_size; i++) {
4480 		while (str[i] == '-')	/* Skip dashes in UUIDs. */
4481 			str++;
4482 		c = str[i];
4483 		if (isdigit(c))
4484 			c -= '0';
4485 		else if (isalpha(c))
4486 			c -= isupper(c) ? 'A' - 10 : 'a' - 10;
4487 		else
4488 			break;
4489 		if (c >= 16)
4490 			break;
4491 		if ((i & 1) == 0)
4492 			buf[i / 2] |= (c << 4);
4493 		else
4494 			buf[i / 2] |= c;
4495 	}
4496 	return ((i + 1) / 2);
4497 }
4498 
4499 /*
4500  * LUN allocation.
4501  *
4502  * Requirements:
4503  * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4504  *   wants us to allocate the LUN and he can block.
4505  * - ctl_softc is always set
4506  * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4507  *
4508  * Returns 0 for success, non-zero (errno) for failure.
4509  */
4510 static int
4511 ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4512 	      struct ctl_be_lun *const be_lun)
4513 {
4514 	struct ctl_lun *nlun, *lun;
4515 	struct scsi_vpd_id_descriptor *desc;
4516 	struct scsi_vpd_id_t10 *t10id;
4517 	const char *eui, *naa, *scsiname, *uuid, *vendor, *value;
4518 	int lun_number, lun_malloced;
4519 	int devidlen, idlen1, idlen2 = 0, len;
4520 
4521 	if (be_lun == NULL)
4522 		return (EINVAL);
4523 
4524 	/*
4525 	 * We currently only support Direct Access or Processor LUN types.
4526 	 */
4527 	switch (be_lun->lun_type) {
4528 	case T_DIRECT:
4529 	case T_PROCESSOR:
4530 	case T_CDROM:
4531 		break;
4532 	case T_SEQUENTIAL:
4533 	case T_CHANGER:
4534 	default:
4535 		be_lun->lun_config_status(be_lun->be_lun,
4536 					  CTL_LUN_CONFIG_FAILURE);
4537 		break;
4538 	}
4539 	if (ctl_lun == NULL) {
4540 		lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4541 		lun_malloced = 1;
4542 	} else {
4543 		lun_malloced = 0;
4544 		lun = ctl_lun;
4545 	}
4546 
4547 	memset(lun, 0, sizeof(*lun));
4548 	if (lun_malloced)
4549 		lun->flags = CTL_LUN_MALLOCED;
4550 
4551 	lun->pending_sense = malloc(sizeof(struct scsi_sense_data *) *
4552 	    ctl_max_ports, M_DEVBUF, M_WAITOK | M_ZERO);
4553 	lun->pending_ua = malloc(sizeof(ctl_ua_type *) * ctl_max_ports,
4554 	    M_DEVBUF, M_WAITOK | M_ZERO);
4555 	lun->pr_keys = malloc(sizeof(uint64_t *) * ctl_max_ports,
4556 	    M_DEVBUF, M_WAITOK | M_ZERO);
4557 
4558 	/* Generate LUN ID. */
4559 	devidlen = max(CTL_DEVID_MIN_LEN,
4560 	    strnlen(be_lun->device_id, CTL_DEVID_LEN));
4561 	idlen1 = sizeof(*t10id) + devidlen;
4562 	len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4563 	scsiname = dnvlist_get_string(be_lun->options, "scsiname", NULL);
4564 	if (scsiname != NULL) {
4565 		idlen2 = roundup2(strlen(scsiname) + 1, 4);
4566 		len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4567 	}
4568 	eui = dnvlist_get_string(be_lun->options, "eui", NULL);
4569 	if (eui != NULL) {
4570 		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4571 	}
4572 	naa = dnvlist_get_string(be_lun->options, "naa", NULL);
4573 	if (naa != NULL) {
4574 		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4575 	}
4576 	uuid = dnvlist_get_string(be_lun->options, "uuid", NULL);
4577 	if (uuid != NULL) {
4578 		len += sizeof(struct scsi_vpd_id_descriptor) + 18;
4579 	}
4580 	lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4581 	    M_CTL, M_WAITOK | M_ZERO);
4582 	desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4583 	desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4584 	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4585 	desc->length = idlen1;
4586 	t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4587 	memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4588 	if ((vendor = dnvlist_get_string(be_lun->options, "vendor", NULL)) == NULL) {
4589 		strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4590 	} else {
4591 		strncpy(t10id->vendor, vendor,
4592 		    min(sizeof(t10id->vendor), strlen(vendor)));
4593 	}
4594 	strncpy((char *)t10id->vendor_spec_id,
4595 	    (char *)be_lun->device_id, devidlen);
4596 	if (scsiname != NULL) {
4597 		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4598 		    desc->length);
4599 		desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4600 		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4601 		    SVPD_ID_TYPE_SCSI_NAME;
4602 		desc->length = idlen2;
4603 		strlcpy(desc->identifier, scsiname, idlen2);
4604 	}
4605 	if (eui != NULL) {
4606 		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4607 		    desc->length);
4608 		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4609 		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4610 		    SVPD_ID_TYPE_EUI64;
4611 		desc->length = hex2bin(eui, desc->identifier, 16);
4612 		desc->length = desc->length > 12 ? 16 :
4613 		    (desc->length > 8 ? 12 : 8);
4614 		len -= 16 - desc->length;
4615 	}
4616 	if (naa != NULL) {
4617 		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4618 		    desc->length);
4619 		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4620 		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4621 		    SVPD_ID_TYPE_NAA;
4622 		desc->length = hex2bin(naa, desc->identifier, 16);
4623 		desc->length = desc->length > 8 ? 16 : 8;
4624 		len -= 16 - desc->length;
4625 	}
4626 	if (uuid != NULL) {
4627 		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4628 		    desc->length);
4629 		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4630 		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4631 		    SVPD_ID_TYPE_UUID;
4632 		desc->identifier[0] = 0x10;
4633 		hex2bin(uuid, &desc->identifier[2], 16);
4634 		desc->length = 18;
4635 	}
4636 	lun->lun_devid->len = len;
4637 
4638 	mtx_lock(&ctl_softc->ctl_lock);
4639 	/*
4640 	 * See if the caller requested a particular LUN number.  If so, see
4641 	 * if it is available.  Otherwise, allocate the first available LUN.
4642 	 */
4643 	if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4644 		if ((be_lun->req_lun_id > (ctl_max_luns - 1))
4645 		 || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4646 			mtx_unlock(&ctl_softc->ctl_lock);
4647 			if (be_lun->req_lun_id > (ctl_max_luns - 1)) {
4648 				printf("ctl: requested LUN ID %d is higher "
4649 				       "than ctl_max_luns - 1 (%d)\n",
4650 				       be_lun->req_lun_id, ctl_max_luns - 1);
4651 			} else {
4652 				/*
4653 				 * XXX KDM return an error, or just assign
4654 				 * another LUN ID in this case??
4655 				 */
4656 				printf("ctl: requested LUN ID %d is already "
4657 				       "in use\n", be_lun->req_lun_id);
4658 			}
4659 fail:
4660 			free(lun->lun_devid, M_CTL);
4661 			if (lun->flags & CTL_LUN_MALLOCED)
4662 				free(lun, M_CTL);
4663 			be_lun->lun_config_status(be_lun->be_lun,
4664 						  CTL_LUN_CONFIG_FAILURE);
4665 			return (ENOSPC);
4666 		}
4667 		lun_number = be_lun->req_lun_id;
4668 	} else {
4669 		lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, 0, ctl_max_luns);
4670 		if (lun_number == -1) {
4671 			mtx_unlock(&ctl_softc->ctl_lock);
4672 			printf("ctl: can't allocate LUN, out of LUNs\n");
4673 			goto fail;
4674 		}
4675 	}
4676 	ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4677 	mtx_unlock(&ctl_softc->ctl_lock);
4678 
4679 	mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4680 	lun->lun = lun_number;
4681 	lun->be_lun = be_lun;
4682 	/*
4683 	 * The processor LUN is always enabled.  Disk LUNs come on line
4684 	 * disabled, and must be enabled by the backend.
4685 	 */
4686 	lun->flags |= CTL_LUN_DISABLED;
4687 	lun->backend = be_lun->be;
4688 	be_lun->ctl_lun = lun;
4689 	be_lun->lun_id = lun_number;
4690 	atomic_add_int(&be_lun->be->num_luns, 1);
4691 	if (be_lun->flags & CTL_LUN_FLAG_EJECTED)
4692 		lun->flags |= CTL_LUN_EJECTED;
4693 	if (be_lun->flags & CTL_LUN_FLAG_NO_MEDIA)
4694 		lun->flags |= CTL_LUN_NO_MEDIA;
4695 	if (be_lun->flags & CTL_LUN_FLAG_STOPPED)
4696 		lun->flags |= CTL_LUN_STOPPED;
4697 
4698 	if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4699 		lun->flags |= CTL_LUN_PRIMARY_SC;
4700 
4701 	value = dnvlist_get_string(be_lun->options, "removable", NULL);
4702 	if (value != NULL) {
4703 		if (strcmp(value, "on") == 0)
4704 			lun->flags |= CTL_LUN_REMOVABLE;
4705 	} else if (be_lun->lun_type == T_CDROM)
4706 		lun->flags |= CTL_LUN_REMOVABLE;
4707 
4708 	lun->ctl_softc = ctl_softc;
4709 #ifdef CTL_TIME_IO
4710 	lun->last_busy = getsbinuptime();
4711 #endif
4712 	TAILQ_INIT(&lun->ooa_queue);
4713 	STAILQ_INIT(&lun->error_list);
4714 	lun->ie_reported = 1;
4715 	callout_init_mtx(&lun->ie_callout, &lun->lun_lock, 0);
4716 	ctl_tpc_lun_init(lun);
4717 	if (lun->flags & CTL_LUN_REMOVABLE) {
4718 		lun->prevent = malloc((CTL_MAX_INITIATORS + 31) / 32 * 4,
4719 		    M_CTL, M_WAITOK);
4720 	}
4721 
4722 	/*
4723 	 * Initialize the mode and log page index.
4724 	 */
4725 	ctl_init_page_index(lun);
4726 	ctl_init_log_page_index(lun);
4727 
4728 	/* Setup statistics gathering */
4729 	lun->stats.item = lun_number;
4730 
4731 	/*
4732 	 * Now, before we insert this lun on the lun list, set the lun
4733 	 * inventory changed UA for all other luns.
4734 	 */
4735 	mtx_lock(&ctl_softc->ctl_lock);
4736 	STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4737 		mtx_lock(&nlun->lun_lock);
4738 		ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4739 		mtx_unlock(&nlun->lun_lock);
4740 	}
4741 	STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4742 	ctl_softc->ctl_luns[lun_number] = lun;
4743 	ctl_softc->num_luns++;
4744 	mtx_unlock(&ctl_softc->ctl_lock);
4745 
4746 	lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4747 	return (0);
4748 }
4749 
4750 /*
4751  * Delete a LUN.
4752  * Assumptions:
4753  * - LUN has already been marked invalid and any pending I/O has been taken
4754  *   care of.
4755  */
4756 static int
4757 ctl_free_lun(struct ctl_lun *lun)
4758 {
4759 	struct ctl_softc *softc = lun->ctl_softc;
4760 	struct ctl_lun *nlun;
4761 	int i;
4762 
4763 	KASSERT(TAILQ_EMPTY(&lun->ooa_queue),
4764 	    ("Freeing a LUN %p with outstanding I/O!\n", lun));
4765 
4766 	mtx_lock(&softc->ctl_lock);
4767 	STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4768 	ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4769 	softc->ctl_luns[lun->lun] = NULL;
4770 	softc->num_luns--;
4771 	STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4772 		mtx_lock(&nlun->lun_lock);
4773 		ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4774 		mtx_unlock(&nlun->lun_lock);
4775 	}
4776 	mtx_unlock(&softc->ctl_lock);
4777 
4778 	/*
4779 	 * Tell the backend to free resources, if this LUN has a backend.
4780 	 */
4781 	atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4782 	lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4783 
4784 	lun->ie_reportcnt = UINT32_MAX;
4785 	callout_drain(&lun->ie_callout);
4786 	ctl_tpc_lun_shutdown(lun);
4787 	mtx_destroy(&lun->lun_lock);
4788 	free(lun->lun_devid, M_CTL);
4789 	for (i = 0; i < ctl_max_ports; i++)
4790 		free(lun->pending_ua[i], M_CTL);
4791 	free(lun->pending_ua, M_DEVBUF);
4792 	for (i = 0; i < ctl_max_ports; i++)
4793 		free(lun->pr_keys[i], M_CTL);
4794 	free(lun->pr_keys, M_DEVBUF);
4795 	free(lun->write_buffer, M_CTL);
4796 	free(lun->prevent, M_CTL);
4797 	if (lun->flags & CTL_LUN_MALLOCED)
4798 		free(lun, M_CTL);
4799 
4800 	return (0);
4801 }
4802 
4803 static void
4804 ctl_create_lun(struct ctl_be_lun *be_lun)
4805 {
4806 
4807 	/*
4808 	 * ctl_alloc_lun() should handle all potential failure cases.
4809 	 */
4810 	ctl_alloc_lun(control_softc, NULL, be_lun);
4811 }
4812 
4813 int
4814 ctl_add_lun(struct ctl_be_lun *be_lun)
4815 {
4816 	struct ctl_softc *softc = control_softc;
4817 
4818 	mtx_lock(&softc->ctl_lock);
4819 	STAILQ_INSERT_TAIL(&softc->pending_lun_queue, be_lun, links);
4820 	mtx_unlock(&softc->ctl_lock);
4821 	wakeup(&softc->pending_lun_queue);
4822 
4823 	return (0);
4824 }
4825 
4826 int
4827 ctl_enable_lun(struct ctl_be_lun *be_lun)
4828 {
4829 	struct ctl_softc *softc;
4830 	struct ctl_port *port, *nport;
4831 	struct ctl_lun *lun;
4832 	int retval;
4833 
4834 	lun = (struct ctl_lun *)be_lun->ctl_lun;
4835 	softc = lun->ctl_softc;
4836 
4837 	mtx_lock(&softc->ctl_lock);
4838 	mtx_lock(&lun->lun_lock);
4839 	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4840 		/*
4841 		 * eh?  Why did we get called if the LUN is already
4842 		 * enabled?
4843 		 */
4844 		mtx_unlock(&lun->lun_lock);
4845 		mtx_unlock(&softc->ctl_lock);
4846 		return (0);
4847 	}
4848 	lun->flags &= ~CTL_LUN_DISABLED;
4849 	mtx_unlock(&lun->lun_lock);
4850 
4851 	STAILQ_FOREACH_SAFE(port, &softc->port_list, links, nport) {
4852 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4853 		    port->lun_map != NULL || port->lun_enable == NULL)
4854 			continue;
4855 
4856 		/*
4857 		 * Drop the lock while we call the FETD's enable routine.
4858 		 * This can lead to a callback into CTL (at least in the
4859 		 * case of the internal initiator frontend.
4860 		 */
4861 		mtx_unlock(&softc->ctl_lock);
4862 		retval = port->lun_enable(port->targ_lun_arg, lun->lun);
4863 		mtx_lock(&softc->ctl_lock);
4864 		if (retval != 0) {
4865 			printf("%s: FETD %s port %d returned error "
4866 			       "%d for lun_enable on lun %jd\n",
4867 			       __func__, port->port_name, port->targ_port,
4868 			       retval, (intmax_t)lun->lun);
4869 		}
4870 	}
4871 
4872 	mtx_unlock(&softc->ctl_lock);
4873 	ctl_isc_announce_lun(lun);
4874 
4875 	return (0);
4876 }
4877 
4878 int
4879 ctl_disable_lun(struct ctl_be_lun *be_lun)
4880 {
4881 	struct ctl_softc *softc;
4882 	struct ctl_port *port;
4883 	struct ctl_lun *lun;
4884 	int retval;
4885 
4886 	lun = (struct ctl_lun *)be_lun->ctl_lun;
4887 	softc = lun->ctl_softc;
4888 
4889 	mtx_lock(&softc->ctl_lock);
4890 	mtx_lock(&lun->lun_lock);
4891 	if (lun->flags & CTL_LUN_DISABLED) {
4892 		mtx_unlock(&lun->lun_lock);
4893 		mtx_unlock(&softc->ctl_lock);
4894 		return (0);
4895 	}
4896 	lun->flags |= CTL_LUN_DISABLED;
4897 	mtx_unlock(&lun->lun_lock);
4898 
4899 	STAILQ_FOREACH(port, &softc->port_list, links) {
4900 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4901 		    port->lun_map != NULL || port->lun_disable == NULL)
4902 			continue;
4903 
4904 		/*
4905 		 * Drop the lock before we call the frontend's disable
4906 		 * routine, to avoid lock order reversals.
4907 		 *
4908 		 * XXX KDM what happens if the frontend list changes while
4909 		 * we're traversing it?  It's unlikely, but should be handled.
4910 		 */
4911 		mtx_unlock(&softc->ctl_lock);
4912 		retval = port->lun_disable(port->targ_lun_arg, lun->lun);
4913 		mtx_lock(&softc->ctl_lock);
4914 		if (retval != 0) {
4915 			printf("%s: FETD %s port %d returned error "
4916 			       "%d for lun_disable on lun %jd\n",
4917 			       __func__, port->port_name, port->targ_port,
4918 			       retval, (intmax_t)lun->lun);
4919 		}
4920 	}
4921 
4922 	mtx_unlock(&softc->ctl_lock);
4923 	ctl_isc_announce_lun(lun);
4924 
4925 	return (0);
4926 }
4927 
4928 int
4929 ctl_start_lun(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_STOPPED;
4935 	mtx_unlock(&lun->lun_lock);
4936 	return (0);
4937 }
4938 
4939 int
4940 ctl_stop_lun(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_STOPPED;
4946 	mtx_unlock(&lun->lun_lock);
4947 	return (0);
4948 }
4949 
4950 int
4951 ctl_lun_no_media(struct ctl_be_lun *be_lun)
4952 {
4953 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4954 
4955 	mtx_lock(&lun->lun_lock);
4956 	lun->flags |= CTL_LUN_NO_MEDIA;
4957 	mtx_unlock(&lun->lun_lock);
4958 	return (0);
4959 }
4960 
4961 int
4962 ctl_lun_has_media(struct ctl_be_lun *be_lun)
4963 {
4964 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4965 	union ctl_ha_msg msg;
4966 
4967 	mtx_lock(&lun->lun_lock);
4968 	lun->flags &= ~(CTL_LUN_NO_MEDIA | CTL_LUN_EJECTED);
4969 	if (lun->flags & CTL_LUN_REMOVABLE)
4970 		ctl_est_ua_all(lun, -1, CTL_UA_MEDIUM_CHANGE);
4971 	mtx_unlock(&lun->lun_lock);
4972 	if ((lun->flags & CTL_LUN_REMOVABLE) &&
4973 	    lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
4974 		bzero(&msg.ua, sizeof(msg.ua));
4975 		msg.hdr.msg_type = CTL_MSG_UA;
4976 		msg.hdr.nexus.initid = -1;
4977 		msg.hdr.nexus.targ_port = -1;
4978 		msg.hdr.nexus.targ_lun = lun->lun;
4979 		msg.hdr.nexus.targ_mapped_lun = lun->lun;
4980 		msg.ua.ua_all = 1;
4981 		msg.ua.ua_set = 1;
4982 		msg.ua.ua_type = CTL_UA_MEDIUM_CHANGE;
4983 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
4984 		    M_WAITOK);
4985 	}
4986 	return (0);
4987 }
4988 
4989 int
4990 ctl_lun_ejected(struct ctl_be_lun *be_lun)
4991 {
4992 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4993 
4994 	mtx_lock(&lun->lun_lock);
4995 	lun->flags |= CTL_LUN_EJECTED;
4996 	mtx_unlock(&lun->lun_lock);
4997 	return (0);
4998 }
4999 
5000 int
5001 ctl_lun_primary(struct ctl_be_lun *be_lun)
5002 {
5003 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5004 
5005 	mtx_lock(&lun->lun_lock);
5006 	lun->flags |= CTL_LUN_PRIMARY_SC;
5007 	ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
5008 	mtx_unlock(&lun->lun_lock);
5009 	ctl_isc_announce_lun(lun);
5010 	return (0);
5011 }
5012 
5013 int
5014 ctl_lun_secondary(struct ctl_be_lun *be_lun)
5015 {
5016 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5017 
5018 	mtx_lock(&lun->lun_lock);
5019 	lun->flags &= ~CTL_LUN_PRIMARY_SC;
5020 	ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
5021 	mtx_unlock(&lun->lun_lock);
5022 	ctl_isc_announce_lun(lun);
5023 	return (0);
5024 }
5025 
5026 int
5027 ctl_invalidate_lun(struct ctl_be_lun *be_lun)
5028 {
5029 	struct ctl_lun *lun;
5030 
5031 	lun = (struct ctl_lun *)be_lun->ctl_lun;
5032 
5033 	mtx_lock(&lun->lun_lock);
5034 
5035 	/*
5036 	 * The LUN needs to be disabled before it can be marked invalid.
5037 	 */
5038 	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
5039 		mtx_unlock(&lun->lun_lock);
5040 		return (-1);
5041 	}
5042 	/*
5043 	 * Mark the LUN invalid.
5044 	 */
5045 	lun->flags |= CTL_LUN_INVALID;
5046 
5047 	/*
5048 	 * If there is nothing in the OOA queue, go ahead and free the LUN.
5049 	 * If we have something in the OOA queue, we'll free it when the
5050 	 * last I/O completes.
5051 	 */
5052 	if (TAILQ_EMPTY(&lun->ooa_queue)) {
5053 		mtx_unlock(&lun->lun_lock);
5054 		ctl_free_lun(lun);
5055 	} else
5056 		mtx_unlock(&lun->lun_lock);
5057 
5058 	return (0);
5059 }
5060 
5061 void
5062 ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
5063 {
5064 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5065 	union ctl_ha_msg msg;
5066 
5067 	mtx_lock(&lun->lun_lock);
5068 	ctl_est_ua_all(lun, -1, CTL_UA_CAPACITY_CHANGE);
5069 	mtx_unlock(&lun->lun_lock);
5070 	if (lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
5071 		/* Send msg to other side. */
5072 		bzero(&msg.ua, sizeof(msg.ua));
5073 		msg.hdr.msg_type = CTL_MSG_UA;
5074 		msg.hdr.nexus.initid = -1;
5075 		msg.hdr.nexus.targ_port = -1;
5076 		msg.hdr.nexus.targ_lun = lun->lun;
5077 		msg.hdr.nexus.targ_mapped_lun = lun->lun;
5078 		msg.ua.ua_all = 1;
5079 		msg.ua.ua_set = 1;
5080 		msg.ua.ua_type = CTL_UA_CAPACITY_CHANGE;
5081 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
5082 		    M_WAITOK);
5083 	}
5084 }
5085 
5086 /*
5087  * Backend "memory move is complete" callback for requests that never
5088  * make it down to say RAIDCore's configuration code.
5089  */
5090 int
5091 ctl_config_move_done(union ctl_io *io)
5092 {
5093 	int retval;
5094 
5095 	CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
5096 	KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
5097 	    ("Config I/O type isn't CTL_IO_SCSI (%d)!", io->io_hdr.io_type));
5098 
5099 	if ((io->io_hdr.port_status != 0) &&
5100 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5101 	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5102 		ctl_set_internal_failure(&io->scsiio, /*sks_valid*/ 1,
5103 		    /*retry_count*/ io->io_hdr.port_status);
5104 	} else if (io->scsiio.kern_data_resid != 0 &&
5105 	    (io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT &&
5106 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5107 	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5108 		ctl_set_invalid_field_ciu(&io->scsiio);
5109 	}
5110 
5111 	if (ctl_debug & CTL_DEBUG_CDB_DATA)
5112 		ctl_data_print(io);
5113 	if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN) ||
5114 	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5115 	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) ||
5116 	    ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
5117 		/*
5118 		 * XXX KDM just assuming a single pointer here, and not a
5119 		 * S/G list.  If we start using S/G lists for config data,
5120 		 * we'll need to know how to clean them up here as well.
5121 		 */
5122 		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5123 			free(io->scsiio.kern_data_ptr, M_CTL);
5124 		ctl_done(io);
5125 		retval = CTL_RETVAL_COMPLETE;
5126 	} else {
5127 		/*
5128 		 * XXX KDM now we need to continue data movement.  Some
5129 		 * options:
5130 		 * - call ctl_scsiio() again?  We don't do this for data
5131 		 *   writes, because for those at least we know ahead of
5132 		 *   time where the write will go and how long it is.  For
5133 		 *   config writes, though, that information is largely
5134 		 *   contained within the write itself, thus we need to
5135 		 *   parse out the data again.
5136 		 *
5137 		 * - Call some other function once the data is in?
5138 		 */
5139 
5140 		/*
5141 		 * XXX KDM call ctl_scsiio() again for now, and check flag
5142 		 * bits to see whether we're allocated or not.
5143 		 */
5144 		retval = ctl_scsiio(&io->scsiio);
5145 	}
5146 	return (retval);
5147 }
5148 
5149 /*
5150  * This gets called by a backend driver when it is done with a
5151  * data_submit method.
5152  */
5153 void
5154 ctl_data_submit_done(union ctl_io *io)
5155 {
5156 	/*
5157 	 * If the IO_CONT flag is set, we need to call the supplied
5158 	 * function to continue processing the I/O, instead of completing
5159 	 * the I/O just yet.
5160 	 *
5161 	 * If there is an error, though, we don't want to keep processing.
5162 	 * Instead, just send status back to the initiator.
5163 	 */
5164 	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5165 	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5166 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5167 	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5168 		io->scsiio.io_cont(io);
5169 		return;
5170 	}
5171 	ctl_done(io);
5172 }
5173 
5174 /*
5175  * This gets called by a backend driver when it is done with a
5176  * configuration write.
5177  */
5178 void
5179 ctl_config_write_done(union ctl_io *io)
5180 {
5181 	uint8_t *buf;
5182 
5183 	/*
5184 	 * If the IO_CONT flag is set, we need to call the supplied
5185 	 * function to continue processing the I/O, instead of completing
5186 	 * the I/O just yet.
5187 	 *
5188 	 * If there is an error, though, we don't want to keep processing.
5189 	 * Instead, just send status back to the initiator.
5190 	 */
5191 	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5192 	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5193 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5194 	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5195 		io->scsiio.io_cont(io);
5196 		return;
5197 	}
5198 	/*
5199 	 * Since a configuration write can be done for commands that actually
5200 	 * have data allocated, like write buffer, and commands that have
5201 	 * no data, like start/stop unit, we need to check here.
5202 	 */
5203 	if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5204 		buf = io->scsiio.kern_data_ptr;
5205 	else
5206 		buf = NULL;
5207 	ctl_done(io);
5208 	if (buf)
5209 		free(buf, M_CTL);
5210 }
5211 
5212 void
5213 ctl_config_read_done(union ctl_io *io)
5214 {
5215 	uint8_t *buf;
5216 
5217 	/*
5218 	 * If there is some error -- we are done, skip data transfer.
5219 	 */
5220 	if ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0 ||
5221 	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5222 	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)) {
5223 		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5224 			buf = io->scsiio.kern_data_ptr;
5225 		else
5226 			buf = NULL;
5227 		ctl_done(io);
5228 		if (buf)
5229 			free(buf, M_CTL);
5230 		return;
5231 	}
5232 
5233 	/*
5234 	 * If the IO_CONT flag is set, we need to call the supplied
5235 	 * function to continue processing the I/O, instead of completing
5236 	 * the I/O just yet.
5237 	 */
5238 	if (io->io_hdr.flags & CTL_FLAG_IO_CONT) {
5239 		io->scsiio.io_cont(io);
5240 		return;
5241 	}
5242 
5243 	ctl_datamove(io);
5244 }
5245 
5246 /*
5247  * SCSI release command.
5248  */
5249 int
5250 ctl_scsi_release(struct ctl_scsiio *ctsio)
5251 {
5252 	struct ctl_lun *lun = CTL_LUN(ctsio);
5253 	uint32_t residx;
5254 
5255 	CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5256 
5257 	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5258 
5259 	/*
5260 	 * XXX KDM right now, we only support LUN reservation.  We don't
5261 	 * support 3rd party reservations, or extent reservations, which
5262 	 * might actually need the parameter list.  If we've gotten this
5263 	 * far, we've got a LUN reservation.  Anything else got kicked out
5264 	 * above.  So, according to SPC, ignore the length.
5265 	 */
5266 
5267 	mtx_lock(&lun->lun_lock);
5268 
5269 	/*
5270 	 * According to SPC, it is not an error for an intiator to attempt
5271 	 * to release a reservation on a LUN that isn't reserved, or that
5272 	 * is reserved by another initiator.  The reservation can only be
5273 	 * released, though, by the initiator who made it or by one of
5274 	 * several reset type events.
5275 	 */
5276 	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
5277 			lun->flags &= ~CTL_LUN_RESERVED;
5278 
5279 	mtx_unlock(&lun->lun_lock);
5280 
5281 	ctl_set_success(ctsio);
5282 	ctl_done((union ctl_io *)ctsio);
5283 	return (CTL_RETVAL_COMPLETE);
5284 }
5285 
5286 int
5287 ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5288 {
5289 	struct ctl_lun *lun = CTL_LUN(ctsio);
5290 	uint32_t residx;
5291 
5292 	CTL_DEBUG_PRINT(("ctl_reserve\n"));
5293 
5294 	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5295 
5296 	/*
5297 	 * XXX KDM right now, we only support LUN reservation.  We don't
5298 	 * support 3rd party reservations, or extent reservations, which
5299 	 * might actually need the parameter list.  If we've gotten this
5300 	 * far, we've got a LUN reservation.  Anything else got kicked out
5301 	 * above.  So, according to SPC, ignore the length.
5302 	 */
5303 
5304 	mtx_lock(&lun->lun_lock);
5305 	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
5306 		ctl_set_reservation_conflict(ctsio);
5307 		goto bailout;
5308 	}
5309 
5310 	/* SPC-3 exceptions to SPC-2 RESERVE and RELEASE behavior. */
5311 	if (lun->flags & CTL_LUN_PR_RESERVED) {
5312 		ctl_set_success(ctsio);
5313 		goto bailout;
5314 	}
5315 
5316 	lun->flags |= CTL_LUN_RESERVED;
5317 	lun->res_idx = residx;
5318 	ctl_set_success(ctsio);
5319 
5320 bailout:
5321 	mtx_unlock(&lun->lun_lock);
5322 	ctl_done((union ctl_io *)ctsio);
5323 	return (CTL_RETVAL_COMPLETE);
5324 }
5325 
5326 int
5327 ctl_start_stop(struct ctl_scsiio *ctsio)
5328 {
5329 	struct ctl_lun *lun = CTL_LUN(ctsio);
5330 	struct scsi_start_stop_unit *cdb;
5331 	int retval;
5332 
5333 	CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5334 
5335 	cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5336 
5337 	if ((cdb->how & SSS_PC_MASK) == 0) {
5338 		if ((lun->flags & CTL_LUN_PR_RESERVED) &&
5339 		    (cdb->how & SSS_START) == 0) {
5340 			uint32_t residx;
5341 
5342 			residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5343 			if (ctl_get_prkey(lun, residx) == 0 ||
5344 			    (lun->pr_res_idx != residx && lun->pr_res_type < 4)) {
5345 
5346 				ctl_set_reservation_conflict(ctsio);
5347 				ctl_done((union ctl_io *)ctsio);
5348 				return (CTL_RETVAL_COMPLETE);
5349 			}
5350 		}
5351 
5352 		if ((cdb->how & SSS_LOEJ) &&
5353 		    (lun->flags & CTL_LUN_REMOVABLE) == 0) {
5354 			ctl_set_invalid_field(ctsio,
5355 					      /*sks_valid*/ 1,
5356 					      /*command*/ 1,
5357 					      /*field*/ 4,
5358 					      /*bit_valid*/ 1,
5359 					      /*bit*/ 1);
5360 			ctl_done((union ctl_io *)ctsio);
5361 			return (CTL_RETVAL_COMPLETE);
5362 		}
5363 
5364 		if ((cdb->how & SSS_START) == 0 && (cdb->how & SSS_LOEJ) &&
5365 		    lun->prevent_count > 0) {
5366 			/* "Medium removal prevented" */
5367 			ctl_set_sense(ctsio, /*current_error*/ 1,
5368 			    /*sense_key*/(lun->flags & CTL_LUN_NO_MEDIA) ?
5369 			     SSD_KEY_NOT_READY : SSD_KEY_ILLEGAL_REQUEST,
5370 			    /*asc*/ 0x53, /*ascq*/ 0x02, SSD_ELEM_NONE);
5371 			ctl_done((union ctl_io *)ctsio);
5372 			return (CTL_RETVAL_COMPLETE);
5373 		}
5374 	}
5375 
5376 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5377 	return (retval);
5378 }
5379 
5380 int
5381 ctl_prevent_allow(struct ctl_scsiio *ctsio)
5382 {
5383 	struct ctl_lun *lun = CTL_LUN(ctsio);
5384 	struct scsi_prevent *cdb;
5385 	int retval;
5386 	uint32_t initidx;
5387 
5388 	CTL_DEBUG_PRINT(("ctl_prevent_allow\n"));
5389 
5390 	cdb = (struct scsi_prevent *)ctsio->cdb;
5391 
5392 	if ((lun->flags & CTL_LUN_REMOVABLE) == 0 || lun->prevent == NULL) {
5393 		ctl_set_invalid_opcode(ctsio);
5394 		ctl_done((union ctl_io *)ctsio);
5395 		return (CTL_RETVAL_COMPLETE);
5396 	}
5397 
5398 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5399 	mtx_lock(&lun->lun_lock);
5400 	if ((cdb->how & PR_PREVENT) &&
5401 	    ctl_is_set(lun->prevent, initidx) == 0) {
5402 		ctl_set_mask(lun->prevent, initidx);
5403 		lun->prevent_count++;
5404 	} else if ((cdb->how & PR_PREVENT) == 0 &&
5405 	    ctl_is_set(lun->prevent, initidx)) {
5406 		ctl_clear_mask(lun->prevent, initidx);
5407 		lun->prevent_count--;
5408 	}
5409 	mtx_unlock(&lun->lun_lock);
5410 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5411 	return (retval);
5412 }
5413 
5414 /*
5415  * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5416  * we don't really do anything with the LBA and length fields if the user
5417  * passes them in.  Instead we'll just flush out the cache for the entire
5418  * LUN.
5419  */
5420 int
5421 ctl_sync_cache(struct ctl_scsiio *ctsio)
5422 {
5423 	struct ctl_lun *lun = CTL_LUN(ctsio);
5424 	struct ctl_lba_len_flags *lbalen;
5425 	uint64_t starting_lba;
5426 	uint32_t block_count;
5427 	int retval;
5428 	uint8_t byte2;
5429 
5430 	CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5431 
5432 	retval = 0;
5433 
5434 	switch (ctsio->cdb[0]) {
5435 	case SYNCHRONIZE_CACHE: {
5436 		struct scsi_sync_cache *cdb;
5437 		cdb = (struct scsi_sync_cache *)ctsio->cdb;
5438 
5439 		starting_lba = scsi_4btoul(cdb->begin_lba);
5440 		block_count = scsi_2btoul(cdb->lb_count);
5441 		byte2 = cdb->byte2;
5442 		break;
5443 	}
5444 	case SYNCHRONIZE_CACHE_16: {
5445 		struct scsi_sync_cache_16 *cdb;
5446 		cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5447 
5448 		starting_lba = scsi_8btou64(cdb->begin_lba);
5449 		block_count = scsi_4btoul(cdb->lb_count);
5450 		byte2 = cdb->byte2;
5451 		break;
5452 	}
5453 	default:
5454 		ctl_set_invalid_opcode(ctsio);
5455 		ctl_done((union ctl_io *)ctsio);
5456 		goto bailout;
5457 		break; /* NOTREACHED */
5458 	}
5459 
5460 	/*
5461 	 * We check the LBA and length, but don't do anything with them.
5462 	 * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5463 	 * get flushed.  This check will just help satisfy anyone who wants
5464 	 * to see an error for an out of range LBA.
5465 	 */
5466 	if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5467 		ctl_set_lba_out_of_range(ctsio,
5468 		    MAX(starting_lba, lun->be_lun->maxlba + 1));
5469 		ctl_done((union ctl_io *)ctsio);
5470 		goto bailout;
5471 	}
5472 
5473 	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5474 	lbalen->lba = starting_lba;
5475 	lbalen->len = block_count;
5476 	lbalen->flags = byte2;
5477 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5478 
5479 bailout:
5480 	return (retval);
5481 }
5482 
5483 int
5484 ctl_format(struct ctl_scsiio *ctsio)
5485 {
5486 	struct scsi_format *cdb;
5487 	int length, defect_list_len;
5488 
5489 	CTL_DEBUG_PRINT(("ctl_format\n"));
5490 
5491 	cdb = (struct scsi_format *)ctsio->cdb;
5492 
5493 	length = 0;
5494 	if (cdb->byte2 & SF_FMTDATA) {
5495 		if (cdb->byte2 & SF_LONGLIST)
5496 			length = sizeof(struct scsi_format_header_long);
5497 		else
5498 			length = sizeof(struct scsi_format_header_short);
5499 	}
5500 
5501 	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5502 	 && (length > 0)) {
5503 		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5504 		ctsio->kern_data_len = length;
5505 		ctsio->kern_total_len = length;
5506 		ctsio->kern_rel_offset = 0;
5507 		ctsio->kern_sg_entries = 0;
5508 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5509 		ctsio->be_move_done = ctl_config_move_done;
5510 		ctl_datamove((union ctl_io *)ctsio);
5511 
5512 		return (CTL_RETVAL_COMPLETE);
5513 	}
5514 
5515 	defect_list_len = 0;
5516 
5517 	if (cdb->byte2 & SF_FMTDATA) {
5518 		if (cdb->byte2 & SF_LONGLIST) {
5519 			struct scsi_format_header_long *header;
5520 
5521 			header = (struct scsi_format_header_long *)
5522 				ctsio->kern_data_ptr;
5523 
5524 			defect_list_len = scsi_4btoul(header->defect_list_len);
5525 			if (defect_list_len != 0) {
5526 				ctl_set_invalid_field(ctsio,
5527 						      /*sks_valid*/ 1,
5528 						      /*command*/ 0,
5529 						      /*field*/ 2,
5530 						      /*bit_valid*/ 0,
5531 						      /*bit*/ 0);
5532 				goto bailout;
5533 			}
5534 		} else {
5535 			struct scsi_format_header_short *header;
5536 
5537 			header = (struct scsi_format_header_short *)
5538 				ctsio->kern_data_ptr;
5539 
5540 			defect_list_len = scsi_2btoul(header->defect_list_len);
5541 			if (defect_list_len != 0) {
5542 				ctl_set_invalid_field(ctsio,
5543 						      /*sks_valid*/ 1,
5544 						      /*command*/ 0,
5545 						      /*field*/ 2,
5546 						      /*bit_valid*/ 0,
5547 						      /*bit*/ 0);
5548 				goto bailout;
5549 			}
5550 		}
5551 	}
5552 
5553 	ctl_set_success(ctsio);
5554 bailout:
5555 
5556 	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5557 		free(ctsio->kern_data_ptr, M_CTL);
5558 		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5559 	}
5560 
5561 	ctl_done((union ctl_io *)ctsio);
5562 	return (CTL_RETVAL_COMPLETE);
5563 }
5564 
5565 int
5566 ctl_read_buffer(struct ctl_scsiio *ctsio)
5567 {
5568 	struct ctl_lun *lun = CTL_LUN(ctsio);
5569 	uint64_t buffer_offset;
5570 	uint32_t len;
5571 	uint8_t byte2;
5572 	static uint8_t descr[4];
5573 	static uint8_t echo_descr[4] = { 0 };
5574 
5575 	CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5576 
5577 	switch (ctsio->cdb[0]) {
5578 	case READ_BUFFER: {
5579 		struct scsi_read_buffer *cdb;
5580 
5581 		cdb = (struct scsi_read_buffer *)ctsio->cdb;
5582 		buffer_offset = scsi_3btoul(cdb->offset);
5583 		len = scsi_3btoul(cdb->length);
5584 		byte2 = cdb->byte2;
5585 		break;
5586 	}
5587 	case READ_BUFFER_16: {
5588 		struct scsi_read_buffer_16 *cdb;
5589 
5590 		cdb = (struct scsi_read_buffer_16 *)ctsio->cdb;
5591 		buffer_offset = scsi_8btou64(cdb->offset);
5592 		len = scsi_4btoul(cdb->length);
5593 		byte2 = cdb->byte2;
5594 		break;
5595 	}
5596 	default: /* This shouldn't happen. */
5597 		ctl_set_invalid_opcode(ctsio);
5598 		ctl_done((union ctl_io *)ctsio);
5599 		return (CTL_RETVAL_COMPLETE);
5600 	}
5601 
5602 	if (buffer_offset > CTL_WRITE_BUFFER_SIZE ||
5603 	    buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5604 		ctl_set_invalid_field(ctsio,
5605 				      /*sks_valid*/ 1,
5606 				      /*command*/ 1,
5607 				      /*field*/ 6,
5608 				      /*bit_valid*/ 0,
5609 				      /*bit*/ 0);
5610 		ctl_done((union ctl_io *)ctsio);
5611 		return (CTL_RETVAL_COMPLETE);
5612 	}
5613 
5614 	if ((byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5615 		descr[0] = 0;
5616 		scsi_ulto3b(CTL_WRITE_BUFFER_SIZE, &descr[1]);
5617 		ctsio->kern_data_ptr = descr;
5618 		len = min(len, sizeof(descr));
5619 	} else if ((byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5620 		ctsio->kern_data_ptr = echo_descr;
5621 		len = min(len, sizeof(echo_descr));
5622 	} else {
5623 		if (lun->write_buffer == NULL) {
5624 			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5625 			    M_CTL, M_WAITOK);
5626 		}
5627 		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5628 	}
5629 	ctsio->kern_data_len = len;
5630 	ctsio->kern_total_len = len;
5631 	ctsio->kern_rel_offset = 0;
5632 	ctsio->kern_sg_entries = 0;
5633 	ctl_set_success(ctsio);
5634 	ctsio->be_move_done = ctl_config_move_done;
5635 	ctl_datamove((union ctl_io *)ctsio);
5636 	return (CTL_RETVAL_COMPLETE);
5637 }
5638 
5639 int
5640 ctl_write_buffer(struct ctl_scsiio *ctsio)
5641 {
5642 	struct ctl_lun *lun = CTL_LUN(ctsio);
5643 	struct scsi_write_buffer *cdb;
5644 	int buffer_offset, len;
5645 
5646 	CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5647 
5648 	cdb = (struct scsi_write_buffer *)ctsio->cdb;
5649 
5650 	len = scsi_3btoul(cdb->length);
5651 	buffer_offset = scsi_3btoul(cdb->offset);
5652 
5653 	if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5654 		ctl_set_invalid_field(ctsio,
5655 				      /*sks_valid*/ 1,
5656 				      /*command*/ 1,
5657 				      /*field*/ 6,
5658 				      /*bit_valid*/ 0,
5659 				      /*bit*/ 0);
5660 		ctl_done((union ctl_io *)ctsio);
5661 		return (CTL_RETVAL_COMPLETE);
5662 	}
5663 
5664 	/*
5665 	 * If we've got a kernel request that hasn't been malloced yet,
5666 	 * malloc it and tell the caller the data buffer is here.
5667 	 */
5668 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5669 		if (lun->write_buffer == NULL) {
5670 			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5671 			    M_CTL, M_WAITOK);
5672 		}
5673 		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5674 		ctsio->kern_data_len = len;
5675 		ctsio->kern_total_len = len;
5676 		ctsio->kern_rel_offset = 0;
5677 		ctsio->kern_sg_entries = 0;
5678 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5679 		ctsio->be_move_done = ctl_config_move_done;
5680 		ctl_datamove((union ctl_io *)ctsio);
5681 
5682 		return (CTL_RETVAL_COMPLETE);
5683 	}
5684 
5685 	ctl_set_success(ctsio);
5686 	ctl_done((union ctl_io *)ctsio);
5687 	return (CTL_RETVAL_COMPLETE);
5688 }
5689 
5690 static int
5691 ctl_write_same_cont(union ctl_io *io)
5692 {
5693 	struct ctl_lun *lun = CTL_LUN(io);
5694 	struct ctl_scsiio *ctsio;
5695 	struct ctl_lba_len_flags *lbalen;
5696 	int retval;
5697 
5698 	ctsio = &io->scsiio;
5699 	ctsio->io_hdr.status = CTL_STATUS_NONE;
5700 	lbalen = (struct ctl_lba_len_flags *)
5701 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5702 	lbalen->lba += lbalen->len;
5703 	if ((lun->be_lun->maxlba + 1) - lbalen->lba <= UINT32_MAX) {
5704 		ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
5705 		lbalen->len = (lun->be_lun->maxlba + 1) - lbalen->lba;
5706 	}
5707 
5708 	CTL_DEBUG_PRINT(("ctl_write_same_cont: calling config_write()\n"));
5709 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5710 	return (retval);
5711 }
5712 
5713 int
5714 ctl_write_same(struct ctl_scsiio *ctsio)
5715 {
5716 	struct ctl_lun *lun = CTL_LUN(ctsio);
5717 	struct ctl_lba_len_flags *lbalen;
5718 	const char *val;
5719 	uint64_t lba, ival;
5720 	uint32_t num_blocks;
5721 	int len, retval;
5722 	uint8_t byte2;
5723 
5724 	CTL_DEBUG_PRINT(("ctl_write_same\n"));
5725 
5726 	switch (ctsio->cdb[0]) {
5727 	case WRITE_SAME_10: {
5728 		struct scsi_write_same_10 *cdb;
5729 
5730 		cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5731 
5732 		lba = scsi_4btoul(cdb->addr);
5733 		num_blocks = scsi_2btoul(cdb->length);
5734 		byte2 = cdb->byte2;
5735 		break;
5736 	}
5737 	case WRITE_SAME_16: {
5738 		struct scsi_write_same_16 *cdb;
5739 
5740 		cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5741 
5742 		lba = scsi_8btou64(cdb->addr);
5743 		num_blocks = scsi_4btoul(cdb->length);
5744 		byte2 = cdb->byte2;
5745 		break;
5746 	}
5747 	default:
5748 		/*
5749 		 * We got a command we don't support.  This shouldn't
5750 		 * happen, commands should be filtered out above us.
5751 		 */
5752 		ctl_set_invalid_opcode(ctsio);
5753 		ctl_done((union ctl_io *)ctsio);
5754 
5755 		return (CTL_RETVAL_COMPLETE);
5756 		break; /* NOTREACHED */
5757 	}
5758 
5759 	/* ANCHOR flag can be used only together with UNMAP */
5760 	if ((byte2 & SWS_UNMAP) == 0 && (byte2 & SWS_ANCHOR) != 0) {
5761 		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
5762 		    /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
5763 		ctl_done((union ctl_io *)ctsio);
5764 		return (CTL_RETVAL_COMPLETE);
5765 	}
5766 
5767 	/*
5768 	 * The first check is to make sure we're in bounds, the second
5769 	 * check is to catch wrap-around problems.  If the lba + num blocks
5770 	 * is less than the lba, then we've wrapped around and the block
5771 	 * range is invalid anyway.
5772 	 */
5773 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5774 	 || ((lba + num_blocks) < lba)) {
5775 		ctl_set_lba_out_of_range(ctsio,
5776 		    MAX(lba, lun->be_lun->maxlba + 1));
5777 		ctl_done((union ctl_io *)ctsio);
5778 		return (CTL_RETVAL_COMPLETE);
5779 	}
5780 
5781 	/* Zero number of blocks means "to the last logical block" */
5782 	if (num_blocks == 0) {
5783 		ival = UINT64_MAX;
5784 		val = dnvlist_get_string(lun->be_lun->options,
5785 		    "write_same_max_lba", NULL);
5786 		if (val != NULL)
5787 			ctl_expand_number(val, &ival);
5788 		if ((lun->be_lun->maxlba + 1) - lba > ival) {
5789 			ctl_set_invalid_field(ctsio,
5790 			    /*sks_valid*/ 1, /*command*/ 1,
5791 			    /*field*/ ctsio->cdb[0] == WRITE_SAME_10 ? 7 : 10,
5792 			    /*bit_valid*/ 0, /*bit*/ 0);
5793 			ctl_done((union ctl_io *)ctsio);
5794 			return (CTL_RETVAL_COMPLETE);
5795 		}
5796 		if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5797 			ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
5798 			ctsio->io_cont = ctl_write_same_cont;
5799 			num_blocks = 1 << 31;
5800 		} else
5801 			num_blocks = (lun->be_lun->maxlba + 1) - lba;
5802 	}
5803 
5804 	len = lun->be_lun->blocksize;
5805 
5806 	/*
5807 	 * If we've got a kernel request that hasn't been malloced yet,
5808 	 * malloc it and tell the caller the data buffer is here.
5809 	 */
5810 	if ((byte2 & SWS_NDOB) == 0 &&
5811 	    (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5812 		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);
5813 		ctsio->kern_data_len = len;
5814 		ctsio->kern_total_len = len;
5815 		ctsio->kern_rel_offset = 0;
5816 		ctsio->kern_sg_entries = 0;
5817 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5818 		ctsio->be_move_done = ctl_config_move_done;
5819 		ctl_datamove((union ctl_io *)ctsio);
5820 
5821 		return (CTL_RETVAL_COMPLETE);
5822 	}
5823 
5824 	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5825 	lbalen->lba = lba;
5826 	lbalen->len = num_blocks;
5827 	lbalen->flags = byte2;
5828 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5829 
5830 	return (retval);
5831 }
5832 
5833 int
5834 ctl_unmap(struct ctl_scsiio *ctsio)
5835 {
5836 	struct ctl_lun *lun = CTL_LUN(ctsio);
5837 	struct scsi_unmap *cdb;
5838 	struct ctl_ptr_len_flags *ptrlen;
5839 	struct scsi_unmap_header *hdr;
5840 	struct scsi_unmap_desc *buf, *end, *endnz, *range;
5841 	uint64_t lba;
5842 	uint32_t num_blocks;
5843 	int len, retval;
5844 	uint8_t byte2;
5845 
5846 	CTL_DEBUG_PRINT(("ctl_unmap\n"));
5847 
5848 	cdb = (struct scsi_unmap *)ctsio->cdb;
5849 	len = scsi_2btoul(cdb->length);
5850 	byte2 = cdb->byte2;
5851 
5852 	/*
5853 	 * If we've got a kernel request that hasn't been malloced yet,
5854 	 * malloc it and tell the caller the data buffer is here.
5855 	 */
5856 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5857 		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);
5858 		ctsio->kern_data_len = len;
5859 		ctsio->kern_total_len = len;
5860 		ctsio->kern_rel_offset = 0;
5861 		ctsio->kern_sg_entries = 0;
5862 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5863 		ctsio->be_move_done = ctl_config_move_done;
5864 		ctl_datamove((union ctl_io *)ctsio);
5865 
5866 		return (CTL_RETVAL_COMPLETE);
5867 	}
5868 
5869 	len = ctsio->kern_total_len - ctsio->kern_data_resid;
5870 	hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
5871 	if (len < sizeof (*hdr) ||
5872 	    len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
5873 	    len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
5874 	    scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
5875 		ctl_set_invalid_field(ctsio,
5876 				      /*sks_valid*/ 0,
5877 				      /*command*/ 0,
5878 				      /*field*/ 0,
5879 				      /*bit_valid*/ 0,
5880 				      /*bit*/ 0);
5881 		goto done;
5882 	}
5883 	len = scsi_2btoul(hdr->desc_length);
5884 	buf = (struct scsi_unmap_desc *)(hdr + 1);
5885 	end = buf + len / sizeof(*buf);
5886 
5887 	endnz = buf;
5888 	for (range = buf; range < end; range++) {
5889 		lba = scsi_8btou64(range->lba);
5890 		num_blocks = scsi_4btoul(range->length);
5891 		if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5892 		 || ((lba + num_blocks) < lba)) {
5893 			ctl_set_lba_out_of_range(ctsio,
5894 			    MAX(lba, lun->be_lun->maxlba + 1));
5895 			ctl_done((union ctl_io *)ctsio);
5896 			return (CTL_RETVAL_COMPLETE);
5897 		}
5898 		if (num_blocks != 0)
5899 			endnz = range + 1;
5900 	}
5901 
5902 	/*
5903 	 * Block backend can not handle zero last range.
5904 	 * Filter it out and return if there is nothing left.
5905 	 */
5906 	len = (uint8_t *)endnz - (uint8_t *)buf;
5907 	if (len == 0) {
5908 		ctl_set_success(ctsio);
5909 		goto done;
5910 	}
5911 
5912 	mtx_lock(&lun->lun_lock);
5913 	ptrlen = (struct ctl_ptr_len_flags *)
5914 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5915 	ptrlen->ptr = (void *)buf;
5916 	ptrlen->len = len;
5917 	ptrlen->flags = byte2;
5918 	ctl_try_unblock_others(lun, (union ctl_io *)ctsio, FALSE);
5919 	mtx_unlock(&lun->lun_lock);
5920 
5921 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5922 	return (retval);
5923 
5924 done:
5925 	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5926 		free(ctsio->kern_data_ptr, M_CTL);
5927 		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5928 	}
5929 	ctl_done((union ctl_io *)ctsio);
5930 	return (CTL_RETVAL_COMPLETE);
5931 }
5932 
5933 int
5934 ctl_default_page_handler(struct ctl_scsiio *ctsio,
5935 			 struct ctl_page_index *page_index, uint8_t *page_ptr)
5936 {
5937 	struct ctl_lun *lun = CTL_LUN(ctsio);
5938 	uint8_t *current_cp;
5939 	int set_ua;
5940 	uint32_t initidx;
5941 
5942 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5943 	set_ua = 0;
5944 
5945 	current_cp = (page_index->page_data + (page_index->page_len *
5946 	    CTL_PAGE_CURRENT));
5947 
5948 	mtx_lock(&lun->lun_lock);
5949 	if (memcmp(current_cp, page_ptr, page_index->page_len)) {
5950 		memcpy(current_cp, page_ptr, page_index->page_len);
5951 		set_ua = 1;
5952 	}
5953 	if (set_ua != 0)
5954 		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
5955 	mtx_unlock(&lun->lun_lock);
5956 	if (set_ua) {
5957 		ctl_isc_announce_mode(lun,
5958 		    ctl_get_initindex(&ctsio->io_hdr.nexus),
5959 		    page_index->page_code, page_index->subpage);
5960 	}
5961 	return (CTL_RETVAL_COMPLETE);
5962 }
5963 
5964 static void
5965 ctl_ie_timer(void *arg)
5966 {
5967 	struct ctl_lun *lun = arg;
5968 	uint64_t t;
5969 
5970 	if (lun->ie_asc == 0)
5971 		return;
5972 
5973 	if (lun->MODE_IE.mrie == SIEP_MRIE_UA)
5974 		ctl_est_ua_all(lun, -1, CTL_UA_IE);
5975 	else
5976 		lun->ie_reported = 0;
5977 
5978 	if (lun->ie_reportcnt < scsi_4btoul(lun->MODE_IE.report_count)) {
5979 		lun->ie_reportcnt++;
5980 		t = scsi_4btoul(lun->MODE_IE.interval_timer);
5981 		if (t == 0 || t == UINT32_MAX)
5982 			t = 3000;  /* 5 min */
5983 		callout_schedule(&lun->ie_callout, t * hz / 10);
5984 	}
5985 }
5986 
5987 int
5988 ctl_ie_page_handler(struct ctl_scsiio *ctsio,
5989 			 struct ctl_page_index *page_index, uint8_t *page_ptr)
5990 {
5991 	struct ctl_lun *lun = CTL_LUN(ctsio);
5992 	struct scsi_info_exceptions_page *pg;
5993 	uint64_t t;
5994 
5995 	(void)ctl_default_page_handler(ctsio, page_index, page_ptr);
5996 
5997 	pg = (struct scsi_info_exceptions_page *)page_ptr;
5998 	mtx_lock(&lun->lun_lock);
5999 	if (pg->info_flags & SIEP_FLAGS_TEST) {
6000 		lun->ie_asc = 0x5d;
6001 		lun->ie_ascq = 0xff;
6002 		if (pg->mrie == SIEP_MRIE_UA) {
6003 			ctl_est_ua_all(lun, -1, CTL_UA_IE);
6004 			lun->ie_reported = 1;
6005 		} else {
6006 			ctl_clr_ua_all(lun, -1, CTL_UA_IE);
6007 			lun->ie_reported = -1;
6008 		}
6009 		lun->ie_reportcnt = 1;
6010 		if (lun->ie_reportcnt < scsi_4btoul(pg->report_count)) {
6011 			lun->ie_reportcnt++;
6012 			t = scsi_4btoul(pg->interval_timer);
6013 			if (t == 0 || t == UINT32_MAX)
6014 				t = 3000;  /* 5 min */
6015 			callout_reset(&lun->ie_callout, t * hz / 10,
6016 			    ctl_ie_timer, lun);
6017 		}
6018 	} else {
6019 		lun->ie_asc = 0;
6020 		lun->ie_ascq = 0;
6021 		lun->ie_reported = 1;
6022 		ctl_clr_ua_all(lun, -1, CTL_UA_IE);
6023 		lun->ie_reportcnt = UINT32_MAX;
6024 		callout_stop(&lun->ie_callout);
6025 	}
6026 	mtx_unlock(&lun->lun_lock);
6027 	return (CTL_RETVAL_COMPLETE);
6028 }
6029 
6030 static int
6031 ctl_do_mode_select(union ctl_io *io)
6032 {
6033 	struct ctl_lun *lun = CTL_LUN(io);
6034 	struct scsi_mode_page_header *page_header;
6035 	struct ctl_page_index *page_index;
6036 	struct ctl_scsiio *ctsio;
6037 	int page_len, page_len_offset, page_len_size;
6038 	union ctl_modepage_info *modepage_info;
6039 	uint16_t *len_left, *len_used;
6040 	int retval, i;
6041 
6042 	ctsio = &io->scsiio;
6043 	page_index = NULL;
6044 	page_len = 0;
6045 
6046 	modepage_info = (union ctl_modepage_info *)
6047 		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6048 	len_left = &modepage_info->header.len_left;
6049 	len_used = &modepage_info->header.len_used;
6050 
6051 do_next_page:
6052 
6053 	page_header = (struct scsi_mode_page_header *)
6054 		(ctsio->kern_data_ptr + *len_used);
6055 
6056 	if (*len_left == 0) {
6057 		free(ctsio->kern_data_ptr, M_CTL);
6058 		ctl_set_success(ctsio);
6059 		ctl_done((union ctl_io *)ctsio);
6060 		return (CTL_RETVAL_COMPLETE);
6061 	} else if (*len_left < sizeof(struct scsi_mode_page_header)) {
6062 
6063 		free(ctsio->kern_data_ptr, M_CTL);
6064 		ctl_set_param_len_error(ctsio);
6065 		ctl_done((union ctl_io *)ctsio);
6066 		return (CTL_RETVAL_COMPLETE);
6067 
6068 	} else if ((page_header->page_code & SMPH_SPF)
6069 		&& (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
6070 
6071 		free(ctsio->kern_data_ptr, M_CTL);
6072 		ctl_set_param_len_error(ctsio);
6073 		ctl_done((union ctl_io *)ctsio);
6074 		return (CTL_RETVAL_COMPLETE);
6075 	}
6076 
6077 
6078 	/*
6079 	 * XXX KDM should we do something with the block descriptor?
6080 	 */
6081 	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6082 		page_index = &lun->mode_pages.index[i];
6083 		if (lun->be_lun->lun_type == T_DIRECT &&
6084 		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6085 			continue;
6086 		if (lun->be_lun->lun_type == T_PROCESSOR &&
6087 		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6088 			continue;
6089 		if (lun->be_lun->lun_type == T_CDROM &&
6090 		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6091 			continue;
6092 
6093 		if ((page_index->page_code & SMPH_PC_MASK) !=
6094 		    (page_header->page_code & SMPH_PC_MASK))
6095 			continue;
6096 
6097 		/*
6098 		 * If neither page has a subpage code, then we've got a
6099 		 * match.
6100 		 */
6101 		if (((page_index->page_code & SMPH_SPF) == 0)
6102 		 && ((page_header->page_code & SMPH_SPF) == 0)) {
6103 			page_len = page_header->page_length;
6104 			break;
6105 		}
6106 
6107 		/*
6108 		 * If both pages have subpages, then the subpage numbers
6109 		 * have to match.
6110 		 */
6111 		if ((page_index->page_code & SMPH_SPF)
6112 		  && (page_header->page_code & SMPH_SPF)) {
6113 			struct scsi_mode_page_header_sp *sph;
6114 
6115 			sph = (struct scsi_mode_page_header_sp *)page_header;
6116 			if (page_index->subpage == sph->subpage) {
6117 				page_len = scsi_2btoul(sph->page_length);
6118 				break;
6119 			}
6120 		}
6121 	}
6122 
6123 	/*
6124 	 * If we couldn't find the page, or if we don't have a mode select
6125 	 * handler for it, send back an error to the user.
6126 	 */
6127 	if ((i >= CTL_NUM_MODE_PAGES)
6128 	 || (page_index->select_handler == NULL)) {
6129 		ctl_set_invalid_field(ctsio,
6130 				      /*sks_valid*/ 1,
6131 				      /*command*/ 0,
6132 				      /*field*/ *len_used,
6133 				      /*bit_valid*/ 0,
6134 				      /*bit*/ 0);
6135 		free(ctsio->kern_data_ptr, M_CTL);
6136 		ctl_done((union ctl_io *)ctsio);
6137 		return (CTL_RETVAL_COMPLETE);
6138 	}
6139 
6140 	if (page_index->page_code & SMPH_SPF) {
6141 		page_len_offset = 2;
6142 		page_len_size = 2;
6143 	} else {
6144 		page_len_size = 1;
6145 		page_len_offset = 1;
6146 	}
6147 
6148 	/*
6149 	 * If the length the initiator gives us isn't the one we specify in
6150 	 * the mode page header, or if they didn't specify enough data in
6151 	 * the CDB to avoid truncating this page, kick out the request.
6152 	 */
6153 	if (page_len != page_index->page_len - page_len_offset - page_len_size) {
6154 		ctl_set_invalid_field(ctsio,
6155 				      /*sks_valid*/ 1,
6156 				      /*command*/ 0,
6157 				      /*field*/ *len_used + page_len_offset,
6158 				      /*bit_valid*/ 0,
6159 				      /*bit*/ 0);
6160 		free(ctsio->kern_data_ptr, M_CTL);
6161 		ctl_done((union ctl_io *)ctsio);
6162 		return (CTL_RETVAL_COMPLETE);
6163 	}
6164 	if (*len_left < page_index->page_len) {
6165 		free(ctsio->kern_data_ptr, M_CTL);
6166 		ctl_set_param_len_error(ctsio);
6167 		ctl_done((union ctl_io *)ctsio);
6168 		return (CTL_RETVAL_COMPLETE);
6169 	}
6170 
6171 	/*
6172 	 * Run through the mode page, checking to make sure that the bits
6173 	 * the user changed are actually legal for him to change.
6174 	 */
6175 	for (i = 0; i < page_index->page_len; i++) {
6176 		uint8_t *user_byte, *change_mask, *current_byte;
6177 		int bad_bit;
6178 		int j;
6179 
6180 		user_byte = (uint8_t *)page_header + i;
6181 		change_mask = page_index->page_data +
6182 			      (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6183 		current_byte = page_index->page_data +
6184 			       (page_index->page_len * CTL_PAGE_CURRENT) + i;
6185 
6186 		/*
6187 		 * Check to see whether the user set any bits in this byte
6188 		 * that he is not allowed to set.
6189 		 */
6190 		if ((*user_byte & ~(*change_mask)) ==
6191 		    (*current_byte & ~(*change_mask)))
6192 			continue;
6193 
6194 		/*
6195 		 * Go through bit by bit to determine which one is illegal.
6196 		 */
6197 		bad_bit = 0;
6198 		for (j = 7; j >= 0; j--) {
6199 			if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6200 			    (((1 << i) & ~(*change_mask)) & *current_byte)) {
6201 				bad_bit = i;
6202 				break;
6203 			}
6204 		}
6205 		ctl_set_invalid_field(ctsio,
6206 				      /*sks_valid*/ 1,
6207 				      /*command*/ 0,
6208 				      /*field*/ *len_used + i,
6209 				      /*bit_valid*/ 1,
6210 				      /*bit*/ bad_bit);
6211 		free(ctsio->kern_data_ptr, M_CTL);
6212 		ctl_done((union ctl_io *)ctsio);
6213 		return (CTL_RETVAL_COMPLETE);
6214 	}
6215 
6216 	/*
6217 	 * Decrement these before we call the page handler, since we may
6218 	 * end up getting called back one way or another before the handler
6219 	 * returns to this context.
6220 	 */
6221 	*len_left -= page_index->page_len;
6222 	*len_used += page_index->page_len;
6223 
6224 	retval = page_index->select_handler(ctsio, page_index,
6225 					    (uint8_t *)page_header);
6226 
6227 	/*
6228 	 * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6229 	 * wait until this queued command completes to finish processing
6230 	 * the mode page.  If it returns anything other than
6231 	 * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6232 	 * already set the sense information, freed the data pointer, and
6233 	 * completed the io for us.
6234 	 */
6235 	if (retval != CTL_RETVAL_COMPLETE)
6236 		goto bailout_no_done;
6237 
6238 	/*
6239 	 * If the initiator sent us more than one page, parse the next one.
6240 	 */
6241 	if (*len_left > 0)
6242 		goto do_next_page;
6243 
6244 	ctl_set_success(ctsio);
6245 	free(ctsio->kern_data_ptr, M_CTL);
6246 	ctl_done((union ctl_io *)ctsio);
6247 
6248 bailout_no_done:
6249 
6250 	return (CTL_RETVAL_COMPLETE);
6251 
6252 }
6253 
6254 int
6255 ctl_mode_select(struct ctl_scsiio *ctsio)
6256 {
6257 	struct ctl_lun *lun = CTL_LUN(ctsio);
6258 	union ctl_modepage_info *modepage_info;
6259 	int bd_len, i, header_size, param_len, rtd;
6260 	uint32_t initidx;
6261 
6262 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6263 	switch (ctsio->cdb[0]) {
6264 	case MODE_SELECT_6: {
6265 		struct scsi_mode_select_6 *cdb;
6266 
6267 		cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6268 
6269 		rtd = (cdb->byte2 & SMS_RTD) ? 1 : 0;
6270 		param_len = cdb->length;
6271 		header_size = sizeof(struct scsi_mode_header_6);
6272 		break;
6273 	}
6274 	case MODE_SELECT_10: {
6275 		struct scsi_mode_select_10 *cdb;
6276 
6277 		cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6278 
6279 		rtd = (cdb->byte2 & SMS_RTD) ? 1 : 0;
6280 		param_len = scsi_2btoul(cdb->length);
6281 		header_size = sizeof(struct scsi_mode_header_10);
6282 		break;
6283 	}
6284 	default:
6285 		ctl_set_invalid_opcode(ctsio);
6286 		ctl_done((union ctl_io *)ctsio);
6287 		return (CTL_RETVAL_COMPLETE);
6288 	}
6289 
6290 	if (rtd) {
6291 		if (param_len != 0) {
6292 			ctl_set_invalid_field(ctsio, /*sks_valid*/ 0,
6293 			    /*command*/ 1, /*field*/ 0,
6294 			    /*bit_valid*/ 0, /*bit*/ 0);
6295 			ctl_done((union ctl_io *)ctsio);
6296 			return (CTL_RETVAL_COMPLETE);
6297 		}
6298 
6299 		/* Revert to defaults. */
6300 		ctl_init_page_index(lun);
6301 		mtx_lock(&lun->lun_lock);
6302 		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
6303 		mtx_unlock(&lun->lun_lock);
6304 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6305 			ctl_isc_announce_mode(lun, -1,
6306 			    lun->mode_pages.index[i].page_code & SMPH_PC_MASK,
6307 			    lun->mode_pages.index[i].subpage);
6308 		}
6309 		ctl_set_success(ctsio);
6310 		ctl_done((union ctl_io *)ctsio);
6311 		return (CTL_RETVAL_COMPLETE);
6312 	}
6313 
6314 	/*
6315 	 * From SPC-3:
6316 	 * "A parameter list length of zero indicates that the Data-Out Buffer
6317 	 * shall be empty. This condition shall not be considered as an error."
6318 	 */
6319 	if (param_len == 0) {
6320 		ctl_set_success(ctsio);
6321 		ctl_done((union ctl_io *)ctsio);
6322 		return (CTL_RETVAL_COMPLETE);
6323 	}
6324 
6325 	/*
6326 	 * Since we'll hit this the first time through, prior to
6327 	 * allocation, we don't need to free a data buffer here.
6328 	 */
6329 	if (param_len < header_size) {
6330 		ctl_set_param_len_error(ctsio);
6331 		ctl_done((union ctl_io *)ctsio);
6332 		return (CTL_RETVAL_COMPLETE);
6333 	}
6334 
6335 	/*
6336 	 * Allocate the data buffer and grab the user's data.  In theory,
6337 	 * we shouldn't have to sanity check the parameter list length here
6338 	 * because the maximum size is 64K.  We should be able to malloc
6339 	 * that much without too many problems.
6340 	 */
6341 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6342 		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6343 		ctsio->kern_data_len = param_len;
6344 		ctsio->kern_total_len = param_len;
6345 		ctsio->kern_rel_offset = 0;
6346 		ctsio->kern_sg_entries = 0;
6347 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6348 		ctsio->be_move_done = ctl_config_move_done;
6349 		ctl_datamove((union ctl_io *)ctsio);
6350 
6351 		return (CTL_RETVAL_COMPLETE);
6352 	}
6353 
6354 	switch (ctsio->cdb[0]) {
6355 	case MODE_SELECT_6: {
6356 		struct scsi_mode_header_6 *mh6;
6357 
6358 		mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6359 		bd_len = mh6->blk_desc_len;
6360 		break;
6361 	}
6362 	case MODE_SELECT_10: {
6363 		struct scsi_mode_header_10 *mh10;
6364 
6365 		mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6366 		bd_len = scsi_2btoul(mh10->blk_desc_len);
6367 		break;
6368 	}
6369 	default:
6370 		panic("%s: Invalid CDB type %#x", __func__, ctsio->cdb[0]);
6371 	}
6372 
6373 	if (param_len < (header_size + bd_len)) {
6374 		free(ctsio->kern_data_ptr, M_CTL);
6375 		ctl_set_param_len_error(ctsio);
6376 		ctl_done((union ctl_io *)ctsio);
6377 		return (CTL_RETVAL_COMPLETE);
6378 	}
6379 
6380 	/*
6381 	 * Set the IO_CONT flag, so that if this I/O gets passed to
6382 	 * ctl_config_write_done(), it'll get passed back to
6383 	 * ctl_do_mode_select() for further processing, or completion if
6384 	 * we're all done.
6385 	 */
6386 	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6387 	ctsio->io_cont = ctl_do_mode_select;
6388 
6389 	modepage_info = (union ctl_modepage_info *)
6390 		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6391 	memset(modepage_info, 0, sizeof(*modepage_info));
6392 	modepage_info->header.len_left = param_len - header_size - bd_len;
6393 	modepage_info->header.len_used = header_size + bd_len;
6394 
6395 	return (ctl_do_mode_select((union ctl_io *)ctsio));
6396 }
6397 
6398 int
6399 ctl_mode_sense(struct ctl_scsiio *ctsio)
6400 {
6401 	struct ctl_lun *lun = CTL_LUN(ctsio);
6402 	int pc, page_code, llba, subpage;
6403 	int alloc_len, page_len, header_len, bd_len, total_len;
6404 	void *block_desc;
6405 	struct ctl_page_index *page_index;
6406 
6407 	llba = 0;
6408 
6409 	CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6410 
6411 	switch (ctsio->cdb[0]) {
6412 	case MODE_SENSE_6: {
6413 		struct scsi_mode_sense_6 *cdb;
6414 
6415 		cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6416 
6417 		header_len = sizeof(struct scsi_mode_hdr_6);
6418 		if (cdb->byte2 & SMS_DBD)
6419 			bd_len = 0;
6420 		else
6421 			bd_len = sizeof(struct scsi_mode_block_descr);
6422 		header_len += bd_len;
6423 
6424 		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6425 		page_code = cdb->page & SMS_PAGE_CODE;
6426 		subpage = cdb->subpage;
6427 		alloc_len = cdb->length;
6428 		break;
6429 	}
6430 	case MODE_SENSE_10: {
6431 		struct scsi_mode_sense_10 *cdb;
6432 
6433 		cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6434 
6435 		header_len = sizeof(struct scsi_mode_hdr_10);
6436 		if (cdb->byte2 & SMS_DBD) {
6437 			bd_len = 0;
6438 		} else if (lun->be_lun->lun_type == T_DIRECT) {
6439 			if (cdb->byte2 & SMS10_LLBAA) {
6440 				llba = 1;
6441 				bd_len = sizeof(struct scsi_mode_block_descr_dlong);
6442 			} else
6443 				bd_len = sizeof(struct scsi_mode_block_descr_dshort);
6444 		} else
6445 			bd_len = sizeof(struct scsi_mode_block_descr);
6446 		header_len += bd_len;
6447 
6448 		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6449 		page_code = cdb->page & SMS_PAGE_CODE;
6450 		subpage = cdb->subpage;
6451 		alloc_len = scsi_2btoul(cdb->length);
6452 		break;
6453 	}
6454 	default:
6455 		ctl_set_invalid_opcode(ctsio);
6456 		ctl_done((union ctl_io *)ctsio);
6457 		return (CTL_RETVAL_COMPLETE);
6458 		break; /* NOTREACHED */
6459 	}
6460 
6461 	/*
6462 	 * We have to make a first pass through to calculate the size of
6463 	 * the pages that match the user's query.  Then we allocate enough
6464 	 * memory to hold it, and actually copy the data into the buffer.
6465 	 */
6466 	switch (page_code) {
6467 	case SMS_ALL_PAGES_PAGE: {
6468 		u_int i;
6469 
6470 		page_len = 0;
6471 
6472 		/*
6473 		 * At the moment, values other than 0 and 0xff here are
6474 		 * reserved according to SPC-3.
6475 		 */
6476 		if ((subpage != SMS_SUBPAGE_PAGE_0)
6477 		 && (subpage != SMS_SUBPAGE_ALL)) {
6478 			ctl_set_invalid_field(ctsio,
6479 					      /*sks_valid*/ 1,
6480 					      /*command*/ 1,
6481 					      /*field*/ 3,
6482 					      /*bit_valid*/ 0,
6483 					      /*bit*/ 0);
6484 			ctl_done((union ctl_io *)ctsio);
6485 			return (CTL_RETVAL_COMPLETE);
6486 		}
6487 
6488 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6489 			page_index = &lun->mode_pages.index[i];
6490 
6491 			/* Make sure the page is supported for this dev type */
6492 			if (lun->be_lun->lun_type == T_DIRECT &&
6493 			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6494 				continue;
6495 			if (lun->be_lun->lun_type == T_PROCESSOR &&
6496 			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6497 				continue;
6498 			if (lun->be_lun->lun_type == T_CDROM &&
6499 			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6500 				continue;
6501 
6502 			/*
6503 			 * We don't use this subpage if the user didn't
6504 			 * request all subpages.
6505 			 */
6506 			if ((page_index->subpage != 0)
6507 			 && (subpage == SMS_SUBPAGE_PAGE_0))
6508 				continue;
6509 
6510 			page_len += page_index->page_len;
6511 		}
6512 		break;
6513 	}
6514 	default: {
6515 		u_int i;
6516 
6517 		page_len = 0;
6518 
6519 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6520 			page_index = &lun->mode_pages.index[i];
6521 
6522 			/* Make sure the page is supported for this dev type */
6523 			if (lun->be_lun->lun_type == T_DIRECT &&
6524 			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6525 				continue;
6526 			if (lun->be_lun->lun_type == T_PROCESSOR &&
6527 			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6528 				continue;
6529 			if (lun->be_lun->lun_type == T_CDROM &&
6530 			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6531 				continue;
6532 
6533 			/* Look for the right page code */
6534 			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6535 				continue;
6536 
6537 			/* Look for the right subpage or the subpage wildcard*/
6538 			if ((page_index->subpage != subpage)
6539 			 && (subpage != SMS_SUBPAGE_ALL))
6540 				continue;
6541 
6542 			page_len += page_index->page_len;
6543 		}
6544 
6545 		if (page_len == 0) {
6546 			ctl_set_invalid_field(ctsio,
6547 					      /*sks_valid*/ 1,
6548 					      /*command*/ 1,
6549 					      /*field*/ 2,
6550 					      /*bit_valid*/ 1,
6551 					      /*bit*/ 5);
6552 			ctl_done((union ctl_io *)ctsio);
6553 			return (CTL_RETVAL_COMPLETE);
6554 		}
6555 		break;
6556 	}
6557 	}
6558 
6559 	total_len = header_len + page_len;
6560 
6561 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6562 	ctsio->kern_sg_entries = 0;
6563 	ctsio->kern_rel_offset = 0;
6564 	ctsio->kern_data_len = min(total_len, alloc_len);
6565 	ctsio->kern_total_len = ctsio->kern_data_len;
6566 
6567 	switch (ctsio->cdb[0]) {
6568 	case MODE_SENSE_6: {
6569 		struct scsi_mode_hdr_6 *header;
6570 
6571 		header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6572 
6573 		header->datalen = MIN(total_len - 1, 254);
6574 		if (lun->be_lun->lun_type == T_DIRECT) {
6575 			header->dev_specific = 0x10; /* DPOFUA */
6576 			if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6577 			    (lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0)
6578 				header->dev_specific |= 0x80; /* WP */
6579 		}
6580 		header->block_descr_len = bd_len;
6581 		block_desc = &header[1];
6582 		break;
6583 	}
6584 	case MODE_SENSE_10: {
6585 		struct scsi_mode_hdr_10 *header;
6586 		int datalen;
6587 
6588 		header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6589 
6590 		datalen = MIN(total_len - 2, 65533);
6591 		scsi_ulto2b(datalen, header->datalen);
6592 		if (lun->be_lun->lun_type == T_DIRECT) {
6593 			header->dev_specific = 0x10; /* DPOFUA */
6594 			if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6595 			    (lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0)
6596 				header->dev_specific |= 0x80; /* WP */
6597 		}
6598 		if (llba)
6599 			header->flags |= SMH_LONGLBA;
6600 		scsi_ulto2b(bd_len, header->block_descr_len);
6601 		block_desc = &header[1];
6602 		break;
6603 	}
6604 	default:
6605 		panic("%s: Invalid CDB type %#x", __func__, ctsio->cdb[0]);
6606 	}
6607 
6608 	/*
6609 	 * If we've got a disk, use its blocksize in the block
6610 	 * descriptor.  Otherwise, just set it to 0.
6611 	 */
6612 	if (bd_len > 0) {
6613 		if (lun->be_lun->lun_type == T_DIRECT) {
6614 			if (llba) {
6615 				struct scsi_mode_block_descr_dlong *bd = block_desc;
6616 				if (lun->be_lun->maxlba != 0)
6617 					scsi_u64to8b(lun->be_lun->maxlba + 1,
6618 					    bd->num_blocks);
6619 				scsi_ulto4b(lun->be_lun->blocksize,
6620 				    bd->block_len);
6621 			} else {
6622 				struct scsi_mode_block_descr_dshort *bd = block_desc;
6623 				if (lun->be_lun->maxlba != 0)
6624 					scsi_ulto4b(MIN(lun->be_lun->maxlba+1,
6625 					    UINT32_MAX), bd->num_blocks);
6626 				scsi_ulto3b(lun->be_lun->blocksize,
6627 				    bd->block_len);
6628 			}
6629 		} else {
6630 			struct scsi_mode_block_descr *bd = block_desc;
6631 			scsi_ulto3b(0, bd->block_len);
6632 		}
6633 	}
6634 
6635 	switch (page_code) {
6636 	case SMS_ALL_PAGES_PAGE: {
6637 		int i, data_used;
6638 
6639 		data_used = header_len;
6640 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6641 			struct ctl_page_index *page_index;
6642 
6643 			page_index = &lun->mode_pages.index[i];
6644 			if (lun->be_lun->lun_type == T_DIRECT &&
6645 			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6646 				continue;
6647 			if (lun->be_lun->lun_type == T_PROCESSOR &&
6648 			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6649 				continue;
6650 			if (lun->be_lun->lun_type == T_CDROM &&
6651 			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6652 				continue;
6653 
6654 			/*
6655 			 * We don't use this subpage if the user didn't
6656 			 * request all subpages.  We already checked (above)
6657 			 * to make sure the user only specified a subpage
6658 			 * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
6659 			 */
6660 			if ((page_index->subpage != 0)
6661 			 && (subpage == SMS_SUBPAGE_PAGE_0))
6662 				continue;
6663 
6664 			/*
6665 			 * Call the handler, if it exists, to update the
6666 			 * page to the latest values.
6667 			 */
6668 			if (page_index->sense_handler != NULL)
6669 				page_index->sense_handler(ctsio, page_index,pc);
6670 
6671 			memcpy(ctsio->kern_data_ptr + data_used,
6672 			       page_index->page_data +
6673 			       (page_index->page_len * pc),
6674 			       page_index->page_len);
6675 			data_used += page_index->page_len;
6676 		}
6677 		break;
6678 	}
6679 	default: {
6680 		int i, data_used;
6681 
6682 		data_used = header_len;
6683 
6684 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6685 			struct ctl_page_index *page_index;
6686 
6687 			page_index = &lun->mode_pages.index[i];
6688 
6689 			/* Look for the right page code */
6690 			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6691 				continue;
6692 
6693 			/* Look for the right subpage or the subpage wildcard*/
6694 			if ((page_index->subpage != subpage)
6695 			 && (subpage != SMS_SUBPAGE_ALL))
6696 				continue;
6697 
6698 			/* Make sure the page is supported for this dev type */
6699 			if (lun->be_lun->lun_type == T_DIRECT &&
6700 			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6701 				continue;
6702 			if (lun->be_lun->lun_type == T_PROCESSOR &&
6703 			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6704 				continue;
6705 			if (lun->be_lun->lun_type == T_CDROM &&
6706 			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6707 				continue;
6708 
6709 			/*
6710 			 * Call the handler, if it exists, to update the
6711 			 * page to the latest values.
6712 			 */
6713 			if (page_index->sense_handler != NULL)
6714 				page_index->sense_handler(ctsio, page_index,pc);
6715 
6716 			memcpy(ctsio->kern_data_ptr + data_used,
6717 			       page_index->page_data +
6718 			       (page_index->page_len * pc),
6719 			       page_index->page_len);
6720 			data_used += page_index->page_len;
6721 		}
6722 		break;
6723 	}
6724 	}
6725 
6726 	ctl_set_success(ctsio);
6727 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6728 	ctsio->be_move_done = ctl_config_move_done;
6729 	ctl_datamove((union ctl_io *)ctsio);
6730 	return (CTL_RETVAL_COMPLETE);
6731 }
6732 
6733 int
6734 ctl_temp_log_sense_handler(struct ctl_scsiio *ctsio,
6735 			       struct ctl_page_index *page_index,
6736 			       int pc)
6737 {
6738 	struct ctl_lun *lun = CTL_LUN(ctsio);
6739 	struct scsi_log_temperature *data;
6740 	const char *value;
6741 
6742 	data = (struct scsi_log_temperature *)page_index->page_data;
6743 
6744 	scsi_ulto2b(SLP_TEMPERATURE, data->hdr.param_code);
6745 	data->hdr.param_control = SLP_LBIN;
6746 	data->hdr.param_len = sizeof(struct scsi_log_temperature) -
6747 	    sizeof(struct scsi_log_param_header);
6748 	if ((value = dnvlist_get_string(lun->be_lun->options, "temperature",
6749 	    NULL)) != NULL)
6750 		data->temperature = strtol(value, NULL, 0);
6751 	else
6752 		data->temperature = 0xff;
6753 	data++;
6754 
6755 	scsi_ulto2b(SLP_REFTEMPERATURE, data->hdr.param_code);
6756 	data->hdr.param_control = SLP_LBIN;
6757 	data->hdr.param_len = sizeof(struct scsi_log_temperature) -
6758 	    sizeof(struct scsi_log_param_header);
6759 	if ((value = dnvlist_get_string(lun->be_lun->options, "reftemperature",
6760 	    NULL)) != NULL)
6761 		data->temperature = strtol(value, NULL, 0);
6762 	else
6763 		data->temperature = 0xff;
6764 	return (0);
6765 }
6766 
6767 int
6768 ctl_lbp_log_sense_handler(struct ctl_scsiio *ctsio,
6769 			       struct ctl_page_index *page_index,
6770 			       int pc)
6771 {
6772 	struct ctl_lun *lun = CTL_LUN(ctsio);
6773 	struct scsi_log_param_header *phdr;
6774 	uint8_t *data;
6775 	uint64_t val;
6776 
6777 	data = page_index->page_data;
6778 
6779 	if (lun->backend->lun_attr != NULL &&
6780 	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksavail"))
6781 	     != UINT64_MAX) {
6782 		phdr = (struct scsi_log_param_header *)data;
6783 		scsi_ulto2b(0x0001, phdr->param_code);
6784 		phdr->param_control = SLP_LBIN | SLP_LP;
6785 		phdr->param_len = 8;
6786 		data = (uint8_t *)(phdr + 1);
6787 		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6788 		data[4] = 0x02; /* per-pool */
6789 		data += phdr->param_len;
6790 	}
6791 
6792 	if (lun->backend->lun_attr != NULL &&
6793 	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksused"))
6794 	     != UINT64_MAX) {
6795 		phdr = (struct scsi_log_param_header *)data;
6796 		scsi_ulto2b(0x0002, phdr->param_code);
6797 		phdr->param_control = SLP_LBIN | SLP_LP;
6798 		phdr->param_len = 8;
6799 		data = (uint8_t *)(phdr + 1);
6800 		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6801 		data[4] = 0x01; /* per-LUN */
6802 		data += phdr->param_len;
6803 	}
6804 
6805 	if (lun->backend->lun_attr != NULL &&
6806 	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksavail"))
6807 	     != UINT64_MAX) {
6808 		phdr = (struct scsi_log_param_header *)data;
6809 		scsi_ulto2b(0x00f1, phdr->param_code);
6810 		phdr->param_control = SLP_LBIN | SLP_LP;
6811 		phdr->param_len = 8;
6812 		data = (uint8_t *)(phdr + 1);
6813 		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6814 		data[4] = 0x02; /* per-pool */
6815 		data += phdr->param_len;
6816 	}
6817 
6818 	if (lun->backend->lun_attr != NULL &&
6819 	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksused"))
6820 	     != UINT64_MAX) {
6821 		phdr = (struct scsi_log_param_header *)data;
6822 		scsi_ulto2b(0x00f2, phdr->param_code);
6823 		phdr->param_control = SLP_LBIN | SLP_LP;
6824 		phdr->param_len = 8;
6825 		data = (uint8_t *)(phdr + 1);
6826 		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6827 		data[4] = 0x02; /* per-pool */
6828 		data += phdr->param_len;
6829 	}
6830 
6831 	page_index->page_len = data - page_index->page_data;
6832 	return (0);
6833 }
6834 
6835 int
6836 ctl_sap_log_sense_handler(struct ctl_scsiio *ctsio,
6837 			       struct ctl_page_index *page_index,
6838 			       int pc)
6839 {
6840 	struct ctl_lun *lun = CTL_LUN(ctsio);
6841 	struct stat_page *data;
6842 	struct bintime *t;
6843 
6844 	data = (struct stat_page *)page_index->page_data;
6845 
6846 	scsi_ulto2b(SLP_SAP, data->sap.hdr.param_code);
6847 	data->sap.hdr.param_control = SLP_LBIN;
6848 	data->sap.hdr.param_len = sizeof(struct scsi_log_stat_and_perf) -
6849 	    sizeof(struct scsi_log_param_header);
6850 	scsi_u64to8b(lun->stats.operations[CTL_STATS_READ],
6851 	    data->sap.read_num);
6852 	scsi_u64to8b(lun->stats.operations[CTL_STATS_WRITE],
6853 	    data->sap.write_num);
6854 	if (lun->be_lun->blocksize > 0) {
6855 		scsi_u64to8b(lun->stats.bytes[CTL_STATS_WRITE] /
6856 		    lun->be_lun->blocksize, data->sap.recvieved_lba);
6857 		scsi_u64to8b(lun->stats.bytes[CTL_STATS_READ] /
6858 		    lun->be_lun->blocksize, data->sap.transmitted_lba);
6859 	}
6860 	t = &lun->stats.time[CTL_STATS_READ];
6861 	scsi_u64to8b((uint64_t)t->sec * 1000 + t->frac / (UINT64_MAX / 1000),
6862 	    data->sap.read_int);
6863 	t = &lun->stats.time[CTL_STATS_WRITE];
6864 	scsi_u64to8b((uint64_t)t->sec * 1000 + t->frac / (UINT64_MAX / 1000),
6865 	    data->sap.write_int);
6866 	scsi_u64to8b(0, data->sap.weighted_num);
6867 	scsi_u64to8b(0, data->sap.weighted_int);
6868 	scsi_ulto2b(SLP_IT, data->it.hdr.param_code);
6869 	data->it.hdr.param_control = SLP_LBIN;
6870 	data->it.hdr.param_len = sizeof(struct scsi_log_idle_time) -
6871 	    sizeof(struct scsi_log_param_header);
6872 #ifdef CTL_TIME_IO
6873 	scsi_u64to8b(lun->idle_time / SBT_1MS, data->it.idle_int);
6874 #endif
6875 	scsi_ulto2b(SLP_TI, data->ti.hdr.param_code);
6876 	data->it.hdr.param_control = SLP_LBIN;
6877 	data->ti.hdr.param_len = sizeof(struct scsi_log_time_interval) -
6878 	    sizeof(struct scsi_log_param_header);
6879 	scsi_ulto4b(3, data->ti.exponent);
6880 	scsi_ulto4b(1, data->ti.integer);
6881 	return (0);
6882 }
6883 
6884 int
6885 ctl_ie_log_sense_handler(struct ctl_scsiio *ctsio,
6886 			       struct ctl_page_index *page_index,
6887 			       int pc)
6888 {
6889 	struct ctl_lun *lun = CTL_LUN(ctsio);
6890 	struct scsi_log_informational_exceptions *data;
6891 	const char *value;
6892 
6893 	data = (struct scsi_log_informational_exceptions *)page_index->page_data;
6894 
6895 	scsi_ulto2b(SLP_IE_GEN, data->hdr.param_code);
6896 	data->hdr.param_control = SLP_LBIN;
6897 	data->hdr.param_len = sizeof(struct scsi_log_informational_exceptions) -
6898 	    sizeof(struct scsi_log_param_header);
6899 	data->ie_asc = lun->ie_asc;
6900 	data->ie_ascq = lun->ie_ascq;
6901 	if ((value = dnvlist_get_string(lun->be_lun->options, "temperature",
6902 	    NULL)) != NULL)
6903 		data->temperature = strtol(value, NULL, 0);
6904 	else
6905 		data->temperature = 0xff;
6906 	return (0);
6907 }
6908 
6909 int
6910 ctl_log_sense(struct ctl_scsiio *ctsio)
6911 {
6912 	struct ctl_lun *lun = CTL_LUN(ctsio);
6913 	int i, pc, page_code, subpage;
6914 	int alloc_len, total_len;
6915 	struct ctl_page_index *page_index;
6916 	struct scsi_log_sense *cdb;
6917 	struct scsi_log_header *header;
6918 
6919 	CTL_DEBUG_PRINT(("ctl_log_sense\n"));
6920 
6921 	cdb = (struct scsi_log_sense *)ctsio->cdb;
6922 	pc = (cdb->page & SLS_PAGE_CTRL_MASK) >> 6;
6923 	page_code = cdb->page & SLS_PAGE_CODE;
6924 	subpage = cdb->subpage;
6925 	alloc_len = scsi_2btoul(cdb->length);
6926 
6927 	page_index = NULL;
6928 	for (i = 0; i < CTL_NUM_LOG_PAGES; i++) {
6929 		page_index = &lun->log_pages.index[i];
6930 
6931 		/* Look for the right page code */
6932 		if ((page_index->page_code & SL_PAGE_CODE) != page_code)
6933 			continue;
6934 
6935 		/* Look for the right subpage or the subpage wildcard*/
6936 		if (page_index->subpage != subpage)
6937 			continue;
6938 
6939 		break;
6940 	}
6941 	if (i >= CTL_NUM_LOG_PAGES) {
6942 		ctl_set_invalid_field(ctsio,
6943 				      /*sks_valid*/ 1,
6944 				      /*command*/ 1,
6945 				      /*field*/ 2,
6946 				      /*bit_valid*/ 0,
6947 				      /*bit*/ 0);
6948 		ctl_done((union ctl_io *)ctsio);
6949 		return (CTL_RETVAL_COMPLETE);
6950 	}
6951 
6952 	total_len = sizeof(struct scsi_log_header) + page_index->page_len;
6953 
6954 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6955 	ctsio->kern_sg_entries = 0;
6956 	ctsio->kern_rel_offset = 0;
6957 	ctsio->kern_data_len = min(total_len, alloc_len);
6958 	ctsio->kern_total_len = ctsio->kern_data_len;
6959 
6960 	header = (struct scsi_log_header *)ctsio->kern_data_ptr;
6961 	header->page = page_index->page_code;
6962 	if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING)
6963 		header->page |= SL_DS;
6964 	if (page_index->subpage) {
6965 		header->page |= SL_SPF;
6966 		header->subpage = page_index->subpage;
6967 	}
6968 	scsi_ulto2b(page_index->page_len, header->datalen);
6969 
6970 	/*
6971 	 * Call the handler, if it exists, to update the
6972 	 * page to the latest values.
6973 	 */
6974 	if (page_index->sense_handler != NULL)
6975 		page_index->sense_handler(ctsio, page_index, pc);
6976 
6977 	memcpy(header + 1, page_index->page_data, page_index->page_len);
6978 
6979 	ctl_set_success(ctsio);
6980 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6981 	ctsio->be_move_done = ctl_config_move_done;
6982 	ctl_datamove((union ctl_io *)ctsio);
6983 	return (CTL_RETVAL_COMPLETE);
6984 }
6985 
6986 int
6987 ctl_read_capacity(struct ctl_scsiio *ctsio)
6988 {
6989 	struct ctl_lun *lun = CTL_LUN(ctsio);
6990 	struct scsi_read_capacity *cdb;
6991 	struct scsi_read_capacity_data *data;
6992 	uint32_t lba;
6993 
6994 	CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
6995 
6996 	cdb = (struct scsi_read_capacity *)ctsio->cdb;
6997 
6998 	lba = scsi_4btoul(cdb->addr);
6999 	if (((cdb->pmi & SRC_PMI) == 0)
7000 	 && (lba != 0)) {
7001 		ctl_set_invalid_field(/*ctsio*/ ctsio,
7002 				      /*sks_valid*/ 1,
7003 				      /*command*/ 1,
7004 				      /*field*/ 2,
7005 				      /*bit_valid*/ 0,
7006 				      /*bit*/ 0);
7007 		ctl_done((union ctl_io *)ctsio);
7008 		return (CTL_RETVAL_COMPLETE);
7009 	}
7010 
7011 	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7012 	data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
7013 	ctsio->kern_data_len = sizeof(*data);
7014 	ctsio->kern_total_len = sizeof(*data);
7015 	ctsio->kern_rel_offset = 0;
7016 	ctsio->kern_sg_entries = 0;
7017 
7018 	/*
7019 	 * If the maximum LBA is greater than 0xfffffffe, the user must
7020 	 * issue a SERVICE ACTION IN (16) command, with the read capacity
7021 	 * serivce action set.
7022 	 */
7023 	if (lun->be_lun->maxlba > 0xfffffffe)
7024 		scsi_ulto4b(0xffffffff, data->addr);
7025 	else
7026 		scsi_ulto4b(lun->be_lun->maxlba, data->addr);
7027 
7028 	/*
7029 	 * XXX KDM this may not be 512 bytes...
7030 	 */
7031 	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7032 
7033 	ctl_set_success(ctsio);
7034 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7035 	ctsio->be_move_done = ctl_config_move_done;
7036 	ctl_datamove((union ctl_io *)ctsio);
7037 	return (CTL_RETVAL_COMPLETE);
7038 }
7039 
7040 int
7041 ctl_read_capacity_16(struct ctl_scsiio *ctsio)
7042 {
7043 	struct ctl_lun *lun = CTL_LUN(ctsio);
7044 	struct scsi_read_capacity_16 *cdb;
7045 	struct scsi_read_capacity_data_long *data;
7046 	uint64_t lba;
7047 	uint32_t alloc_len;
7048 
7049 	CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
7050 
7051 	cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
7052 
7053 	alloc_len = scsi_4btoul(cdb->alloc_len);
7054 	lba = scsi_8btou64(cdb->addr);
7055 
7056 	if ((cdb->reladr & SRC16_PMI)
7057 	 && (lba != 0)) {
7058 		ctl_set_invalid_field(/*ctsio*/ ctsio,
7059 				      /*sks_valid*/ 1,
7060 				      /*command*/ 1,
7061 				      /*field*/ 2,
7062 				      /*bit_valid*/ 0,
7063 				      /*bit*/ 0);
7064 		ctl_done((union ctl_io *)ctsio);
7065 		return (CTL_RETVAL_COMPLETE);
7066 	}
7067 
7068 	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7069 	data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
7070 	ctsio->kern_rel_offset = 0;
7071 	ctsio->kern_sg_entries = 0;
7072 	ctsio->kern_data_len = min(sizeof(*data), alloc_len);
7073 	ctsio->kern_total_len = ctsio->kern_data_len;
7074 
7075 	scsi_u64to8b(lun->be_lun->maxlba, data->addr);
7076 	/* XXX KDM this may not be 512 bytes... */
7077 	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7078 	data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
7079 	scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
7080 	if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
7081 		data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
7082 
7083 	ctl_set_success(ctsio);
7084 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7085 	ctsio->be_move_done = ctl_config_move_done;
7086 	ctl_datamove((union ctl_io *)ctsio);
7087 	return (CTL_RETVAL_COMPLETE);
7088 }
7089 
7090 int
7091 ctl_get_lba_status(struct ctl_scsiio *ctsio)
7092 {
7093 	struct ctl_lun *lun = CTL_LUN(ctsio);
7094 	struct scsi_get_lba_status *cdb;
7095 	struct scsi_get_lba_status_data *data;
7096 	struct ctl_lba_len_flags *lbalen;
7097 	uint64_t lba;
7098 	uint32_t alloc_len, total_len;
7099 	int retval;
7100 
7101 	CTL_DEBUG_PRINT(("ctl_get_lba_status\n"));
7102 
7103 	cdb = (struct scsi_get_lba_status *)ctsio->cdb;
7104 	lba = scsi_8btou64(cdb->addr);
7105 	alloc_len = scsi_4btoul(cdb->alloc_len);
7106 
7107 	if (lba > lun->be_lun->maxlba) {
7108 		ctl_set_lba_out_of_range(ctsio, lba);
7109 		ctl_done((union ctl_io *)ctsio);
7110 		return (CTL_RETVAL_COMPLETE);
7111 	}
7112 
7113 	total_len = sizeof(*data) + sizeof(data->descr[0]);
7114 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7115 	data = (struct scsi_get_lba_status_data *)ctsio->kern_data_ptr;
7116 	ctsio->kern_rel_offset = 0;
7117 	ctsio->kern_sg_entries = 0;
7118 	ctsio->kern_data_len = min(total_len, alloc_len);
7119 	ctsio->kern_total_len = ctsio->kern_data_len;
7120 
7121 	/* Fill dummy data in case backend can't tell anything. */
7122 	scsi_ulto4b(4 + sizeof(data->descr[0]), data->length);
7123 	scsi_u64to8b(lba, data->descr[0].addr);
7124 	scsi_ulto4b(MIN(UINT32_MAX, lun->be_lun->maxlba + 1 - lba),
7125 	    data->descr[0].length);
7126 	data->descr[0].status = 0; /* Mapped or unknown. */
7127 
7128 	ctl_set_success(ctsio);
7129 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7130 	ctsio->be_move_done = ctl_config_move_done;
7131 
7132 	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
7133 	lbalen->lba = lba;
7134 	lbalen->len = total_len;
7135 	lbalen->flags = 0;
7136 	retval = lun->backend->config_read((union ctl_io *)ctsio);
7137 	return (retval);
7138 }
7139 
7140 int
7141 ctl_read_defect(struct ctl_scsiio *ctsio)
7142 {
7143 	struct scsi_read_defect_data_10 *ccb10;
7144 	struct scsi_read_defect_data_12 *ccb12;
7145 	struct scsi_read_defect_data_hdr_10 *data10;
7146 	struct scsi_read_defect_data_hdr_12 *data12;
7147 	uint32_t alloc_len, data_len;
7148 	uint8_t format;
7149 
7150 	CTL_DEBUG_PRINT(("ctl_read_defect\n"));
7151 
7152 	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7153 		ccb10 = (struct scsi_read_defect_data_10 *)&ctsio->cdb;
7154 		format = ccb10->format;
7155 		alloc_len = scsi_2btoul(ccb10->alloc_length);
7156 		data_len = sizeof(*data10);
7157 	} else {
7158 		ccb12 = (struct scsi_read_defect_data_12 *)&ctsio->cdb;
7159 		format = ccb12->format;
7160 		alloc_len = scsi_4btoul(ccb12->alloc_length);
7161 		data_len = sizeof(*data12);
7162 	}
7163 	if (alloc_len == 0) {
7164 		ctl_set_success(ctsio);
7165 		ctl_done((union ctl_io *)ctsio);
7166 		return (CTL_RETVAL_COMPLETE);
7167 	}
7168 
7169 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
7170 	ctsio->kern_rel_offset = 0;
7171 	ctsio->kern_sg_entries = 0;
7172 	ctsio->kern_data_len = min(data_len, alloc_len);
7173 	ctsio->kern_total_len = ctsio->kern_data_len;
7174 
7175 	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7176 		data10 = (struct scsi_read_defect_data_hdr_10 *)
7177 		    ctsio->kern_data_ptr;
7178 		data10->format = format;
7179 		scsi_ulto2b(0, data10->length);
7180 	} else {
7181 		data12 = (struct scsi_read_defect_data_hdr_12 *)
7182 		    ctsio->kern_data_ptr;
7183 		data12->format = format;
7184 		scsi_ulto2b(0, data12->generation);
7185 		scsi_ulto4b(0, data12->length);
7186 	}
7187 
7188 	ctl_set_success(ctsio);
7189 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7190 	ctsio->be_move_done = ctl_config_move_done;
7191 	ctl_datamove((union ctl_io *)ctsio);
7192 	return (CTL_RETVAL_COMPLETE);
7193 }
7194 
7195 int
7196 ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7197 {
7198 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
7199 	struct ctl_lun *lun = CTL_LUN(ctsio);
7200 	struct scsi_maintenance_in *cdb;
7201 	int retval;
7202 	int alloc_len, ext, total_len = 0, g, pc, pg, ts, os;
7203 	int num_ha_groups, num_target_ports, shared_group;
7204 	struct ctl_port *port;
7205 	struct scsi_target_group_data *rtg_ptr;
7206 	struct scsi_target_group_data_extended *rtg_ext_ptr;
7207 	struct scsi_target_port_group_descriptor *tpg_desc;
7208 
7209 	CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7210 
7211 	cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7212 	retval = CTL_RETVAL_COMPLETE;
7213 
7214 	switch (cdb->byte2 & STG_PDF_MASK) {
7215 	case STG_PDF_LENGTH:
7216 		ext = 0;
7217 		break;
7218 	case STG_PDF_EXTENDED:
7219 		ext = 1;
7220 		break;
7221 	default:
7222 		ctl_set_invalid_field(/*ctsio*/ ctsio,
7223 				      /*sks_valid*/ 1,
7224 				      /*command*/ 1,
7225 				      /*field*/ 2,
7226 				      /*bit_valid*/ 1,
7227 				      /*bit*/ 5);
7228 		ctl_done((union ctl_io *)ctsio);
7229 		return(retval);
7230 	}
7231 
7232 	num_target_ports = 0;
7233 	shared_group = (softc->is_single != 0);
7234 	mtx_lock(&softc->ctl_lock);
7235 	STAILQ_FOREACH(port, &softc->port_list, links) {
7236 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7237 			continue;
7238 		if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7239 			continue;
7240 		num_target_ports++;
7241 		if (port->status & CTL_PORT_STATUS_HA_SHARED)
7242 			shared_group = 1;
7243 	}
7244 	mtx_unlock(&softc->ctl_lock);
7245 	num_ha_groups = (softc->is_single) ? 0 : NUM_HA_SHELVES;
7246 
7247 	if (ext)
7248 		total_len = sizeof(struct scsi_target_group_data_extended);
7249 	else
7250 		total_len = sizeof(struct scsi_target_group_data);
7251 	total_len += sizeof(struct scsi_target_port_group_descriptor) *
7252 		(shared_group + num_ha_groups) +
7253 	    sizeof(struct scsi_target_port_descriptor) * num_target_ports;
7254 
7255 	alloc_len = scsi_4btoul(cdb->length);
7256 
7257 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7258 	ctsio->kern_sg_entries = 0;
7259 	ctsio->kern_rel_offset = 0;
7260 	ctsio->kern_data_len = min(total_len, alloc_len);
7261 	ctsio->kern_total_len = ctsio->kern_data_len;
7262 
7263 	if (ext) {
7264 		rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7265 		    ctsio->kern_data_ptr;
7266 		scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7267 		rtg_ext_ptr->format_type = 0x10;
7268 		rtg_ext_ptr->implicit_transition_time = 0;
7269 		tpg_desc = &rtg_ext_ptr->groups[0];
7270 	} else {
7271 		rtg_ptr = (struct scsi_target_group_data *)
7272 		    ctsio->kern_data_ptr;
7273 		scsi_ulto4b(total_len - 4, rtg_ptr->length);
7274 		tpg_desc = &rtg_ptr->groups[0];
7275 	}
7276 
7277 	mtx_lock(&softc->ctl_lock);
7278 	pg = softc->port_min / softc->port_cnt;
7279 	if (lun->flags & (CTL_LUN_PRIMARY_SC | CTL_LUN_PEER_SC_PRIMARY)) {
7280 		/* Some shelf is known to be primary. */
7281 		if (softc->ha_link == CTL_HA_LINK_OFFLINE)
7282 			os = TPG_ASYMMETRIC_ACCESS_UNAVAILABLE;
7283 		else if (softc->ha_link == CTL_HA_LINK_UNKNOWN)
7284 			os = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7285 		else if (softc->ha_mode == CTL_HA_MODE_ACT_STBY)
7286 			os = TPG_ASYMMETRIC_ACCESS_STANDBY;
7287 		else
7288 			os = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7289 		if (lun->flags & CTL_LUN_PRIMARY_SC) {
7290 			ts = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7291 		} else {
7292 			ts = os;
7293 			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7294 		}
7295 	} else {
7296 		/* No known primary shelf. */
7297 		if (softc->ha_link == CTL_HA_LINK_OFFLINE) {
7298 			ts = TPG_ASYMMETRIC_ACCESS_UNAVAILABLE;
7299 			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7300 		} else if (softc->ha_link == CTL_HA_LINK_UNKNOWN) {
7301 			ts = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7302 			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7303 		} else {
7304 			ts = os = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7305 		}
7306 	}
7307 	if (shared_group) {
7308 		tpg_desc->pref_state = ts;
7309 		tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP |
7310 		    TPG_U_SUP | TPG_T_SUP;
7311 		scsi_ulto2b(1, tpg_desc->target_port_group);
7312 		tpg_desc->status = TPG_IMPLICIT;
7313 		pc = 0;
7314 		STAILQ_FOREACH(port, &softc->port_list, links) {
7315 			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7316 				continue;
7317 			if (!softc->is_single &&
7318 			    (port->status & CTL_PORT_STATUS_HA_SHARED) == 0)
7319 				continue;
7320 			if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7321 				continue;
7322 			scsi_ulto2b(port->targ_port, tpg_desc->descriptors[pc].
7323 			    relative_target_port_identifier);
7324 			pc++;
7325 		}
7326 		tpg_desc->target_port_count = pc;
7327 		tpg_desc = (struct scsi_target_port_group_descriptor *)
7328 		    &tpg_desc->descriptors[pc];
7329 	}
7330 	for (g = 0; g < num_ha_groups; g++) {
7331 		tpg_desc->pref_state = (g == pg) ? ts : os;
7332 		tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP |
7333 		    TPG_U_SUP | TPG_T_SUP;
7334 		scsi_ulto2b(2 + g, tpg_desc->target_port_group);
7335 		tpg_desc->status = TPG_IMPLICIT;
7336 		pc = 0;
7337 		STAILQ_FOREACH(port, &softc->port_list, links) {
7338 			if (port->targ_port < g * softc->port_cnt ||
7339 			    port->targ_port >= (g + 1) * softc->port_cnt)
7340 				continue;
7341 			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7342 				continue;
7343 			if (port->status & CTL_PORT_STATUS_HA_SHARED)
7344 				continue;
7345 			if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7346 				continue;
7347 			scsi_ulto2b(port->targ_port, tpg_desc->descriptors[pc].
7348 			    relative_target_port_identifier);
7349 			pc++;
7350 		}
7351 		tpg_desc->target_port_count = pc;
7352 		tpg_desc = (struct scsi_target_port_group_descriptor *)
7353 		    &tpg_desc->descriptors[pc];
7354 	}
7355 	mtx_unlock(&softc->ctl_lock);
7356 
7357 	ctl_set_success(ctsio);
7358 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7359 	ctsio->be_move_done = ctl_config_move_done;
7360 	ctl_datamove((union ctl_io *)ctsio);
7361 	return(retval);
7362 }
7363 
7364 int
7365 ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7366 {
7367 	struct ctl_lun *lun = CTL_LUN(ctsio);
7368 	struct scsi_report_supported_opcodes *cdb;
7369 	const struct ctl_cmd_entry *entry, *sentry;
7370 	struct scsi_report_supported_opcodes_all *all;
7371 	struct scsi_report_supported_opcodes_descr *descr;
7372 	struct scsi_report_supported_opcodes_one *one;
7373 	int retval;
7374 	int alloc_len, total_len;
7375 	int opcode, service_action, i, j, num;
7376 
7377 	CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7378 
7379 	cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7380 	retval = CTL_RETVAL_COMPLETE;
7381 
7382 	opcode = cdb->requested_opcode;
7383 	service_action = scsi_2btoul(cdb->requested_service_action);
7384 	switch (cdb->options & RSO_OPTIONS_MASK) {
7385 	case RSO_OPTIONS_ALL:
7386 		num = 0;
7387 		for (i = 0; i < 256; i++) {
7388 			entry = &ctl_cmd_table[i];
7389 			if (entry->flags & CTL_CMD_FLAG_SA5) {
7390 				for (j = 0; j < 32; j++) {
7391 					sentry = &((const struct ctl_cmd_entry *)
7392 					    entry->execute)[j];
7393 					if (ctl_cmd_applicable(
7394 					    lun->be_lun->lun_type, sentry))
7395 						num++;
7396 				}
7397 			} else {
7398 				if (ctl_cmd_applicable(lun->be_lun->lun_type,
7399 				    entry))
7400 					num++;
7401 			}
7402 		}
7403 		total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7404 		    num * sizeof(struct scsi_report_supported_opcodes_descr);
7405 		break;
7406 	case RSO_OPTIONS_OC:
7407 		if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7408 			ctl_set_invalid_field(/*ctsio*/ ctsio,
7409 					      /*sks_valid*/ 1,
7410 					      /*command*/ 1,
7411 					      /*field*/ 2,
7412 					      /*bit_valid*/ 1,
7413 					      /*bit*/ 2);
7414 			ctl_done((union ctl_io *)ctsio);
7415 			return (CTL_RETVAL_COMPLETE);
7416 		}
7417 		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7418 		break;
7419 	case RSO_OPTIONS_OC_SA:
7420 		if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7421 		    service_action >= 32) {
7422 			ctl_set_invalid_field(/*ctsio*/ ctsio,
7423 					      /*sks_valid*/ 1,
7424 					      /*command*/ 1,
7425 					      /*field*/ 2,
7426 					      /*bit_valid*/ 1,
7427 					      /*bit*/ 2);
7428 			ctl_done((union ctl_io *)ctsio);
7429 			return (CTL_RETVAL_COMPLETE);
7430 		}
7431 		/* FALLTHROUGH */
7432 	case RSO_OPTIONS_OC_ASA:
7433 		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7434 		break;
7435 	default:
7436 		ctl_set_invalid_field(/*ctsio*/ ctsio,
7437 				      /*sks_valid*/ 1,
7438 				      /*command*/ 1,
7439 				      /*field*/ 2,
7440 				      /*bit_valid*/ 1,
7441 				      /*bit*/ 2);
7442 		ctl_done((union ctl_io *)ctsio);
7443 		return (CTL_RETVAL_COMPLETE);
7444 	}
7445 
7446 	alloc_len = scsi_4btoul(cdb->length);
7447 
7448 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7449 	ctsio->kern_sg_entries = 0;
7450 	ctsio->kern_rel_offset = 0;
7451 	ctsio->kern_data_len = min(total_len, alloc_len);
7452 	ctsio->kern_total_len = ctsio->kern_data_len;
7453 
7454 	switch (cdb->options & RSO_OPTIONS_MASK) {
7455 	case RSO_OPTIONS_ALL:
7456 		all = (struct scsi_report_supported_opcodes_all *)
7457 		    ctsio->kern_data_ptr;
7458 		num = 0;
7459 		for (i = 0; i < 256; i++) {
7460 			entry = &ctl_cmd_table[i];
7461 			if (entry->flags & CTL_CMD_FLAG_SA5) {
7462 				for (j = 0; j < 32; j++) {
7463 					sentry = &((const struct ctl_cmd_entry *)
7464 					    entry->execute)[j];
7465 					if (!ctl_cmd_applicable(
7466 					    lun->be_lun->lun_type, sentry))
7467 						continue;
7468 					descr = &all->descr[num++];
7469 					descr->opcode = i;
7470 					scsi_ulto2b(j, descr->service_action);
7471 					descr->flags = RSO_SERVACTV;
7472 					scsi_ulto2b(sentry->length,
7473 					    descr->cdb_length);
7474 				}
7475 			} else {
7476 				if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7477 				    entry))
7478 					continue;
7479 				descr = &all->descr[num++];
7480 				descr->opcode = i;
7481 				scsi_ulto2b(0, descr->service_action);
7482 				descr->flags = 0;
7483 				scsi_ulto2b(entry->length, descr->cdb_length);
7484 			}
7485 		}
7486 		scsi_ulto4b(
7487 		    num * sizeof(struct scsi_report_supported_opcodes_descr),
7488 		    all->length);
7489 		break;
7490 	case RSO_OPTIONS_OC:
7491 		one = (struct scsi_report_supported_opcodes_one *)
7492 		    ctsio->kern_data_ptr;
7493 		entry = &ctl_cmd_table[opcode];
7494 		goto fill_one;
7495 	case RSO_OPTIONS_OC_SA:
7496 		one = (struct scsi_report_supported_opcodes_one *)
7497 		    ctsio->kern_data_ptr;
7498 		entry = &ctl_cmd_table[opcode];
7499 		entry = &((const struct ctl_cmd_entry *)
7500 		    entry->execute)[service_action];
7501 fill_one:
7502 		if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7503 			one->support = 3;
7504 			scsi_ulto2b(entry->length, one->cdb_length);
7505 			one->cdb_usage[0] = opcode;
7506 			memcpy(&one->cdb_usage[1], entry->usage,
7507 			    entry->length - 1);
7508 		} else
7509 			one->support = 1;
7510 		break;
7511 	case RSO_OPTIONS_OC_ASA:
7512 		one = (struct scsi_report_supported_opcodes_one *)
7513 		    ctsio->kern_data_ptr;
7514 		entry = &ctl_cmd_table[opcode];
7515 		if (entry->flags & CTL_CMD_FLAG_SA5) {
7516 			entry = &((const struct ctl_cmd_entry *)
7517 			    entry->execute)[service_action];
7518 		} else if (service_action != 0) {
7519 			one->support = 1;
7520 			break;
7521 		}
7522 		goto fill_one;
7523 	}
7524 
7525 	ctl_set_success(ctsio);
7526 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7527 	ctsio->be_move_done = ctl_config_move_done;
7528 	ctl_datamove((union ctl_io *)ctsio);
7529 	return(retval);
7530 }
7531 
7532 int
7533 ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7534 {
7535 	struct scsi_report_supported_tmf *cdb;
7536 	struct scsi_report_supported_tmf_ext_data *data;
7537 	int retval;
7538 	int alloc_len, total_len;
7539 
7540 	CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7541 
7542 	cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7543 
7544 	retval = CTL_RETVAL_COMPLETE;
7545 
7546 	if (cdb->options & RST_REPD)
7547 		total_len = sizeof(struct scsi_report_supported_tmf_ext_data);
7548 	else
7549 		total_len = sizeof(struct scsi_report_supported_tmf_data);
7550 	alloc_len = scsi_4btoul(cdb->length);
7551 
7552 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7553 	ctsio->kern_sg_entries = 0;
7554 	ctsio->kern_rel_offset = 0;
7555 	ctsio->kern_data_len = min(total_len, alloc_len);
7556 	ctsio->kern_total_len = ctsio->kern_data_len;
7557 
7558 	data = (struct scsi_report_supported_tmf_ext_data *)ctsio->kern_data_ptr;
7559 	data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_QTS |
7560 	    RST_TRS;
7561 	data->byte2 |= RST_QAES | RST_QTSS | RST_ITNRS;
7562 	data->length = total_len - 4;
7563 
7564 	ctl_set_success(ctsio);
7565 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7566 	ctsio->be_move_done = ctl_config_move_done;
7567 	ctl_datamove((union ctl_io *)ctsio);
7568 	return (retval);
7569 }
7570 
7571 int
7572 ctl_report_timestamp(struct ctl_scsiio *ctsio)
7573 {
7574 	struct scsi_report_timestamp *cdb;
7575 	struct scsi_report_timestamp_data *data;
7576 	struct timeval tv;
7577 	int64_t timestamp;
7578 	int retval;
7579 	int alloc_len, total_len;
7580 
7581 	CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7582 
7583 	cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7584 
7585 	retval = CTL_RETVAL_COMPLETE;
7586 
7587 	total_len = sizeof(struct scsi_report_timestamp_data);
7588 	alloc_len = scsi_4btoul(cdb->length);
7589 
7590 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7591 	ctsio->kern_sg_entries = 0;
7592 	ctsio->kern_rel_offset = 0;
7593 	ctsio->kern_data_len = min(total_len, alloc_len);
7594 	ctsio->kern_total_len = ctsio->kern_data_len;
7595 
7596 	data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7597 	scsi_ulto2b(sizeof(*data) - 2, data->length);
7598 	data->origin = RTS_ORIG_OUTSIDE;
7599 	getmicrotime(&tv);
7600 	timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7601 	scsi_ulto4b(timestamp >> 16, data->timestamp);
7602 	scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7603 
7604 	ctl_set_success(ctsio);
7605 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7606 	ctsio->be_move_done = ctl_config_move_done;
7607 	ctl_datamove((union ctl_io *)ctsio);
7608 	return (retval);
7609 }
7610 
7611 int
7612 ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7613 {
7614 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
7615 	struct ctl_lun *lun = CTL_LUN(ctsio);
7616 	struct scsi_per_res_in *cdb;
7617 	int alloc_len, total_len = 0;
7618 	/* struct scsi_per_res_in_rsrv in_data; */
7619 	uint64_t key;
7620 
7621 	CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7622 
7623 	cdb = (struct scsi_per_res_in *)ctsio->cdb;
7624 
7625 	alloc_len = scsi_2btoul(cdb->length);
7626 
7627 retry:
7628 	mtx_lock(&lun->lun_lock);
7629 	switch (cdb->action) {
7630 	case SPRI_RK: /* read keys */
7631 		total_len = sizeof(struct scsi_per_res_in_keys) +
7632 			lun->pr_key_count *
7633 			sizeof(struct scsi_per_res_key);
7634 		break;
7635 	case SPRI_RR: /* read reservation */
7636 		if (lun->flags & CTL_LUN_PR_RESERVED)
7637 			total_len = sizeof(struct scsi_per_res_in_rsrv);
7638 		else
7639 			total_len = sizeof(struct scsi_per_res_in_header);
7640 		break;
7641 	case SPRI_RC: /* report capabilities */
7642 		total_len = sizeof(struct scsi_per_res_cap);
7643 		break;
7644 	case SPRI_RS: /* read full status */
7645 		total_len = sizeof(struct scsi_per_res_in_header) +
7646 		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7647 		    lun->pr_key_count;
7648 		break;
7649 	default:
7650 		panic("%s: Invalid PR type %#x", __func__, cdb->action);
7651 	}
7652 	mtx_unlock(&lun->lun_lock);
7653 
7654 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7655 	ctsio->kern_rel_offset = 0;
7656 	ctsio->kern_sg_entries = 0;
7657 	ctsio->kern_data_len = min(total_len, alloc_len);
7658 	ctsio->kern_total_len = ctsio->kern_data_len;
7659 
7660 	mtx_lock(&lun->lun_lock);
7661 	switch (cdb->action) {
7662 	case SPRI_RK: { // read keys
7663         struct scsi_per_res_in_keys *res_keys;
7664 		int i, key_count;
7665 
7666 		res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7667 
7668 		/*
7669 		 * We had to drop the lock to allocate our buffer, which
7670 		 * leaves time for someone to come in with another
7671 		 * persistent reservation.  (That is unlikely, though,
7672 		 * since this should be the only persistent reservation
7673 		 * command active right now.)
7674 		 */
7675 		if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7676 		    (lun->pr_key_count *
7677 		     sizeof(struct scsi_per_res_key)))){
7678 			mtx_unlock(&lun->lun_lock);
7679 			free(ctsio->kern_data_ptr, M_CTL);
7680 			printf("%s: reservation length changed, retrying\n",
7681 			       __func__);
7682 			goto retry;
7683 		}
7684 
7685 		scsi_ulto4b(lun->pr_generation, res_keys->header.generation);
7686 
7687 		scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7688 			     lun->pr_key_count, res_keys->header.length);
7689 
7690 		for (i = 0, key_count = 0; i < CTL_MAX_INITIATORS; i++) {
7691 			if ((key = ctl_get_prkey(lun, i)) == 0)
7692 				continue;
7693 
7694 			/*
7695 			 * We used lun->pr_key_count to calculate the
7696 			 * size to allocate.  If it turns out the number of
7697 			 * initiators with the registered flag set is
7698 			 * larger than that (i.e. they haven't been kept in
7699 			 * sync), we've got a problem.
7700 			 */
7701 			if (key_count >= lun->pr_key_count) {
7702 				key_count++;
7703 				continue;
7704 			}
7705 			scsi_u64to8b(key, res_keys->keys[key_count].key);
7706 			key_count++;
7707 		}
7708 		break;
7709 	}
7710 	case SPRI_RR: { // read reservation
7711 		struct scsi_per_res_in_rsrv *res;
7712 		int tmp_len, header_only;
7713 
7714 		res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7715 
7716 		scsi_ulto4b(lun->pr_generation, res->header.generation);
7717 
7718 		if (lun->flags & CTL_LUN_PR_RESERVED)
7719 		{
7720 			tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7721 			scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7722 				    res->header.length);
7723 			header_only = 0;
7724 		} else {
7725 			tmp_len = sizeof(struct scsi_per_res_in_header);
7726 			scsi_ulto4b(0, res->header.length);
7727 			header_only = 1;
7728 		}
7729 
7730 		/*
7731 		 * We had to drop the lock to allocate our buffer, which
7732 		 * leaves time for someone to come in with another
7733 		 * persistent reservation.  (That is unlikely, though,
7734 		 * since this should be the only persistent reservation
7735 		 * command active right now.)
7736 		 */
7737 		if (tmp_len != total_len) {
7738 			mtx_unlock(&lun->lun_lock);
7739 			free(ctsio->kern_data_ptr, M_CTL);
7740 			printf("%s: reservation status changed, retrying\n",
7741 			       __func__);
7742 			goto retry;
7743 		}
7744 
7745 		/*
7746 		 * No reservation held, so we're done.
7747 		 */
7748 		if (header_only != 0)
7749 			break;
7750 
7751 		/*
7752 		 * If the registration is an All Registrants type, the key
7753 		 * is 0, since it doesn't really matter.
7754 		 */
7755 		if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7756 			scsi_u64to8b(ctl_get_prkey(lun, lun->pr_res_idx),
7757 			    res->data.reservation);
7758 		}
7759 		res->data.scopetype = lun->pr_res_type;
7760 		break;
7761 	}
7762 	case SPRI_RC:     //report capabilities
7763 	{
7764 		struct scsi_per_res_cap *res_cap;
7765 		uint16_t type_mask;
7766 
7767 		res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7768 		scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7769 		res_cap->flags1 = SPRI_CRH;
7770 		res_cap->flags2 = SPRI_TMV | SPRI_ALLOW_5;
7771 		type_mask = SPRI_TM_WR_EX_AR |
7772 			    SPRI_TM_EX_AC_RO |
7773 			    SPRI_TM_WR_EX_RO |
7774 			    SPRI_TM_EX_AC |
7775 			    SPRI_TM_WR_EX |
7776 			    SPRI_TM_EX_AC_AR;
7777 		scsi_ulto2b(type_mask, res_cap->type_mask);
7778 		break;
7779 	}
7780 	case SPRI_RS: { // read full status
7781 		struct scsi_per_res_in_full *res_status;
7782 		struct scsi_per_res_in_full_desc *res_desc;
7783 		struct ctl_port *port;
7784 		int i, len;
7785 
7786 		res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7787 
7788 		/*
7789 		 * We had to drop the lock to allocate our buffer, which
7790 		 * leaves time for someone to come in with another
7791 		 * persistent reservation.  (That is unlikely, though,
7792 		 * since this should be the only persistent reservation
7793 		 * command active right now.)
7794 		 */
7795 		if (total_len < (sizeof(struct scsi_per_res_in_header) +
7796 		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7797 		     lun->pr_key_count)){
7798 			mtx_unlock(&lun->lun_lock);
7799 			free(ctsio->kern_data_ptr, M_CTL);
7800 			printf("%s: reservation length changed, retrying\n",
7801 			       __func__);
7802 			goto retry;
7803 		}
7804 
7805 		scsi_ulto4b(lun->pr_generation, res_status->header.generation);
7806 
7807 		res_desc = &res_status->desc[0];
7808 		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7809 			if ((key = ctl_get_prkey(lun, i)) == 0)
7810 				continue;
7811 
7812 			scsi_u64to8b(key, res_desc->res_key.key);
7813 			if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7814 			    (lun->pr_res_idx == i ||
7815 			     lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7816 				res_desc->flags = SPRI_FULL_R_HOLDER;
7817 				res_desc->scopetype = lun->pr_res_type;
7818 			}
7819 			scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7820 			    res_desc->rel_trgt_port_id);
7821 			len = 0;
7822 			port = softc->ctl_ports[i / CTL_MAX_INIT_PER_PORT];
7823 			if (port != NULL)
7824 				len = ctl_create_iid(port,
7825 				    i % CTL_MAX_INIT_PER_PORT,
7826 				    res_desc->transport_id);
7827 			scsi_ulto4b(len, res_desc->additional_length);
7828 			res_desc = (struct scsi_per_res_in_full_desc *)
7829 			    &res_desc->transport_id[len];
7830 		}
7831 		scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7832 		    res_status->header.length);
7833 		break;
7834 	}
7835 	default:
7836 		panic("%s: Invalid PR type %#x", __func__, cdb->action);
7837 	}
7838 	mtx_unlock(&lun->lun_lock);
7839 
7840 	ctl_set_success(ctsio);
7841 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7842 	ctsio->be_move_done = ctl_config_move_done;
7843 	ctl_datamove((union ctl_io *)ctsio);
7844 	return (CTL_RETVAL_COMPLETE);
7845 }
7846 
7847 /*
7848  * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
7849  * it should return.
7850  */
7851 static int
7852 ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
7853 		uint64_t sa_res_key, uint8_t type, uint32_t residx,
7854 		struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
7855 		struct scsi_per_res_out_parms* param)
7856 {
7857 	union ctl_ha_msg persis_io;
7858 	int i;
7859 
7860 	mtx_lock(&lun->lun_lock);
7861 	if (sa_res_key == 0) {
7862 		if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
7863 			/* validate scope and type */
7864 			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7865 			     SPR_LU_SCOPE) {
7866 				mtx_unlock(&lun->lun_lock);
7867 				ctl_set_invalid_field(/*ctsio*/ ctsio,
7868 						      /*sks_valid*/ 1,
7869 						      /*command*/ 1,
7870 						      /*field*/ 2,
7871 						      /*bit_valid*/ 1,
7872 						      /*bit*/ 4);
7873 				ctl_done((union ctl_io *)ctsio);
7874 				return (1);
7875 			}
7876 
7877 		        if (type>8 || type==2 || type==4 || type==0) {
7878 				mtx_unlock(&lun->lun_lock);
7879 				ctl_set_invalid_field(/*ctsio*/ ctsio,
7880        	           				      /*sks_valid*/ 1,
7881 						      /*command*/ 1,
7882 						      /*field*/ 2,
7883 						      /*bit_valid*/ 1,
7884 						      /*bit*/ 0);
7885 				ctl_done((union ctl_io *)ctsio);
7886 				return (1);
7887 		        }
7888 
7889 			/*
7890 			 * Unregister everybody else and build UA for
7891 			 * them
7892 			 */
7893 			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
7894 				if (i == residx || ctl_get_prkey(lun, i) == 0)
7895 					continue;
7896 
7897 				ctl_clr_prkey(lun, i);
7898 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7899 			}
7900 			lun->pr_key_count = 1;
7901 			lun->pr_res_type = type;
7902 			if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
7903 			    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
7904 				lun->pr_res_idx = residx;
7905 			lun->pr_generation++;
7906 			mtx_unlock(&lun->lun_lock);
7907 
7908 			/* send msg to other side */
7909 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7910 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7911 			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7912 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
7913 			persis_io.pr.pr_info.res_type = type;
7914 			memcpy(persis_io.pr.pr_info.sa_res_key,
7915 			       param->serv_act_res_key,
7916 			       sizeof(param->serv_act_res_key));
7917 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7918 			    sizeof(persis_io.pr), M_WAITOK);
7919 		} else {
7920 			/* not all registrants */
7921 			mtx_unlock(&lun->lun_lock);
7922 			free(ctsio->kern_data_ptr, M_CTL);
7923 			ctl_set_invalid_field(ctsio,
7924 					      /*sks_valid*/ 1,
7925 					      /*command*/ 0,
7926 					      /*field*/ 8,
7927 					      /*bit_valid*/ 0,
7928 					      /*bit*/ 0);
7929 			ctl_done((union ctl_io *)ctsio);
7930 			return (1);
7931 		}
7932 	} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
7933 		|| !(lun->flags & CTL_LUN_PR_RESERVED)) {
7934 		int found = 0;
7935 
7936 		if (res_key == sa_res_key) {
7937 			/* special case */
7938 			/*
7939 			 * The spec implies this is not good but doesn't
7940 			 * say what to do. There are two choices either
7941 			 * generate a res conflict or check condition
7942 			 * with illegal field in parameter data. Since
7943 			 * that is what is done when the sa_res_key is
7944 			 * zero I'll take that approach since this has
7945 			 * to do with the sa_res_key.
7946 			 */
7947 			mtx_unlock(&lun->lun_lock);
7948 			free(ctsio->kern_data_ptr, M_CTL);
7949 			ctl_set_invalid_field(ctsio,
7950 					      /*sks_valid*/ 1,
7951 					      /*command*/ 0,
7952 					      /*field*/ 8,
7953 					      /*bit_valid*/ 0,
7954 					      /*bit*/ 0);
7955 			ctl_done((union ctl_io *)ctsio);
7956 			return (1);
7957 		}
7958 
7959 		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7960 			if (ctl_get_prkey(lun, i) != sa_res_key)
7961 				continue;
7962 
7963 			found = 1;
7964 			ctl_clr_prkey(lun, i);
7965 			lun->pr_key_count--;
7966 			ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7967 		}
7968 		if (!found) {
7969 			mtx_unlock(&lun->lun_lock);
7970 			free(ctsio->kern_data_ptr, M_CTL);
7971 			ctl_set_reservation_conflict(ctsio);
7972 			ctl_done((union ctl_io *)ctsio);
7973 			return (CTL_RETVAL_COMPLETE);
7974 		}
7975 		lun->pr_generation++;
7976 		mtx_unlock(&lun->lun_lock);
7977 
7978 		/* send msg to other side */
7979 		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7980 		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7981 		persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7982 		persis_io.pr.pr_info.residx = lun->pr_res_idx;
7983 		persis_io.pr.pr_info.res_type = type;
7984 		memcpy(persis_io.pr.pr_info.sa_res_key,
7985 		       param->serv_act_res_key,
7986 		       sizeof(param->serv_act_res_key));
7987 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7988 		    sizeof(persis_io.pr), M_WAITOK);
7989 	} else {
7990 		/* Reserved but not all registrants */
7991 		/* sa_res_key is res holder */
7992 		if (sa_res_key == ctl_get_prkey(lun, lun->pr_res_idx)) {
7993 			/* validate scope and type */
7994 			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7995 			     SPR_LU_SCOPE) {
7996 				mtx_unlock(&lun->lun_lock);
7997 				ctl_set_invalid_field(/*ctsio*/ ctsio,
7998 						      /*sks_valid*/ 1,
7999 						      /*command*/ 1,
8000 						      /*field*/ 2,
8001 						      /*bit_valid*/ 1,
8002 						      /*bit*/ 4);
8003 				ctl_done((union ctl_io *)ctsio);
8004 				return (1);
8005 			}
8006 
8007 			if (type>8 || type==2 || type==4 || type==0) {
8008 				mtx_unlock(&lun->lun_lock);
8009 				ctl_set_invalid_field(/*ctsio*/ ctsio,
8010 						      /*sks_valid*/ 1,
8011 						      /*command*/ 1,
8012 						      /*field*/ 2,
8013 						      /*bit_valid*/ 1,
8014 						      /*bit*/ 0);
8015 				ctl_done((union ctl_io *)ctsio);
8016 				return (1);
8017 			}
8018 
8019 			/*
8020 			 * Do the following:
8021 			 * if sa_res_key != res_key remove all
8022 			 * registrants w/sa_res_key and generate UA
8023 			 * for these registrants(Registrations
8024 			 * Preempted) if it wasn't an exclusive
8025 			 * reservation generate UA(Reservations
8026 			 * Preempted) for all other registered nexuses
8027 			 * if the type has changed. Establish the new
8028 			 * reservation and holder. If res_key and
8029 			 * sa_res_key are the same do the above
8030 			 * except don't unregister the res holder.
8031 			 */
8032 
8033 			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
8034 				if (i == residx || ctl_get_prkey(lun, i) == 0)
8035 					continue;
8036 
8037 				if (sa_res_key == ctl_get_prkey(lun, i)) {
8038 					ctl_clr_prkey(lun, i);
8039 					lun->pr_key_count--;
8040 					ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8041 				} else if (type != lun->pr_res_type &&
8042 				    (lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8043 				     lun->pr_res_type == SPR_TYPE_EX_AC_RO)) {
8044 					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8045 				}
8046 			}
8047 			lun->pr_res_type = type;
8048 			if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8049 			    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8050 				lun->pr_res_idx = residx;
8051 			else
8052 				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8053 			lun->pr_generation++;
8054 			mtx_unlock(&lun->lun_lock);
8055 
8056 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8057 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8058 			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8059 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8060 			persis_io.pr.pr_info.res_type = type;
8061 			memcpy(persis_io.pr.pr_info.sa_res_key,
8062 			       param->serv_act_res_key,
8063 			       sizeof(param->serv_act_res_key));
8064 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8065 			    sizeof(persis_io.pr), M_WAITOK);
8066 		} else {
8067 			/*
8068 			 * sa_res_key is not the res holder just
8069 			 * remove registrants
8070 			 */
8071 			int found=0;
8072 
8073 			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8074 				if (sa_res_key != ctl_get_prkey(lun, i))
8075 					continue;
8076 
8077 				found = 1;
8078 				ctl_clr_prkey(lun, i);
8079 				lun->pr_key_count--;
8080 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8081 			}
8082 
8083 			if (!found) {
8084 				mtx_unlock(&lun->lun_lock);
8085 				free(ctsio->kern_data_ptr, M_CTL);
8086 				ctl_set_reservation_conflict(ctsio);
8087 				ctl_done((union ctl_io *)ctsio);
8088 		        	return (1);
8089 			}
8090 			lun->pr_generation++;
8091 			mtx_unlock(&lun->lun_lock);
8092 
8093 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8094 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8095 			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8096 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8097 			persis_io.pr.pr_info.res_type = type;
8098 			memcpy(persis_io.pr.pr_info.sa_res_key,
8099 			       param->serv_act_res_key,
8100 			       sizeof(param->serv_act_res_key));
8101 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8102 			    sizeof(persis_io.pr), M_WAITOK);
8103 		}
8104 	}
8105 	return (0);
8106 }
8107 
8108 static void
8109 ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8110 {
8111 	uint64_t sa_res_key;
8112 	int i;
8113 
8114 	sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8115 
8116 	if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8117 	 || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8118 	 || sa_res_key != ctl_get_prkey(lun, lun->pr_res_idx)) {
8119 		if (sa_res_key == 0) {
8120 			/*
8121 			 * Unregister everybody else and build UA for
8122 			 * them
8123 			 */
8124 			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
8125 				if (i == msg->pr.pr_info.residx ||
8126 				    ctl_get_prkey(lun, i) == 0)
8127 					continue;
8128 
8129 				ctl_clr_prkey(lun, i);
8130 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8131 			}
8132 
8133 			lun->pr_key_count = 1;
8134 			lun->pr_res_type = msg->pr.pr_info.res_type;
8135 			if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8136 			    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8137 				lun->pr_res_idx = msg->pr.pr_info.residx;
8138 		} else {
8139 		        for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8140 				if (sa_res_key == ctl_get_prkey(lun, i))
8141 					continue;
8142 
8143 				ctl_clr_prkey(lun, i);
8144 				lun->pr_key_count--;
8145 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8146 			}
8147 		}
8148 	} else {
8149 		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8150 			if (i == msg->pr.pr_info.residx ||
8151 			    ctl_get_prkey(lun, i) == 0)
8152 				continue;
8153 
8154 			if (sa_res_key == ctl_get_prkey(lun, i)) {
8155 				ctl_clr_prkey(lun, i);
8156 				lun->pr_key_count--;
8157 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8158 			} else if (msg->pr.pr_info.res_type != lun->pr_res_type
8159 			    && (lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8160 			     lun->pr_res_type == SPR_TYPE_EX_AC_RO)) {
8161 				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8162 			}
8163 		}
8164 		lun->pr_res_type = msg->pr.pr_info.res_type;
8165 		if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8166 		    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8167 			lun->pr_res_idx = msg->pr.pr_info.residx;
8168 		else
8169 			lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8170 	}
8171 	lun->pr_generation++;
8172 
8173 }
8174 
8175 
8176 int
8177 ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8178 {
8179 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
8180 	struct ctl_lun *lun = CTL_LUN(ctsio);
8181 	int retval;
8182 	u_int32_t param_len;
8183 	struct scsi_per_res_out *cdb;
8184 	struct scsi_per_res_out_parms* param;
8185 	uint32_t residx;
8186 	uint64_t res_key, sa_res_key, key;
8187 	uint8_t type;
8188 	union ctl_ha_msg persis_io;
8189 	int    i;
8190 
8191 	CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8192 
8193 	cdb = (struct scsi_per_res_out *)ctsio->cdb;
8194 	retval = CTL_RETVAL_COMPLETE;
8195 
8196 	/*
8197 	 * We only support whole-LUN scope.  The scope & type are ignored for
8198 	 * register, register and ignore existing key and clear.
8199 	 * We sometimes ignore scope and type on preempts too!!
8200 	 * Verify reservation type here as well.
8201 	 */
8202 	type = cdb->scope_type & SPR_TYPE_MASK;
8203 	if ((cdb->action == SPRO_RESERVE)
8204 	 || (cdb->action == SPRO_RELEASE)) {
8205 		if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8206 			ctl_set_invalid_field(/*ctsio*/ ctsio,
8207 					      /*sks_valid*/ 1,
8208 					      /*command*/ 1,
8209 					      /*field*/ 2,
8210 					      /*bit_valid*/ 1,
8211 					      /*bit*/ 4);
8212 			ctl_done((union ctl_io *)ctsio);
8213 			return (CTL_RETVAL_COMPLETE);
8214 		}
8215 
8216 		if (type>8 || type==2 || type==4 || type==0) {
8217 			ctl_set_invalid_field(/*ctsio*/ ctsio,
8218 					      /*sks_valid*/ 1,
8219 					      /*command*/ 1,
8220 					      /*field*/ 2,
8221 					      /*bit_valid*/ 1,
8222 					      /*bit*/ 0);
8223 			ctl_done((union ctl_io *)ctsio);
8224 			return (CTL_RETVAL_COMPLETE);
8225 		}
8226 	}
8227 
8228 	param_len = scsi_4btoul(cdb->length);
8229 
8230 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8231 		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8232 		ctsio->kern_data_len = param_len;
8233 		ctsio->kern_total_len = param_len;
8234 		ctsio->kern_rel_offset = 0;
8235 		ctsio->kern_sg_entries = 0;
8236 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8237 		ctsio->be_move_done = ctl_config_move_done;
8238 		ctl_datamove((union ctl_io *)ctsio);
8239 
8240 		return (CTL_RETVAL_COMPLETE);
8241 	}
8242 
8243 	param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8244 
8245 	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
8246 	res_key = scsi_8btou64(param->res_key.key);
8247 	sa_res_key = scsi_8btou64(param->serv_act_res_key);
8248 
8249 	/*
8250 	 * Validate the reservation key here except for SPRO_REG_IGNO
8251 	 * This must be done for all other service actions
8252 	 */
8253 	if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8254 		mtx_lock(&lun->lun_lock);
8255 		if ((key = ctl_get_prkey(lun, residx)) != 0) {
8256 			if (res_key != key) {
8257 				/*
8258 				 * The current key passed in doesn't match
8259 				 * the one the initiator previously
8260 				 * registered.
8261 				 */
8262 				mtx_unlock(&lun->lun_lock);
8263 				free(ctsio->kern_data_ptr, M_CTL);
8264 				ctl_set_reservation_conflict(ctsio);
8265 				ctl_done((union ctl_io *)ctsio);
8266 				return (CTL_RETVAL_COMPLETE);
8267 			}
8268 		} else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8269 			/*
8270 			 * We are not registered
8271 			 */
8272 			mtx_unlock(&lun->lun_lock);
8273 			free(ctsio->kern_data_ptr, M_CTL);
8274 			ctl_set_reservation_conflict(ctsio);
8275 			ctl_done((union ctl_io *)ctsio);
8276 			return (CTL_RETVAL_COMPLETE);
8277 		} else if (res_key != 0) {
8278 			/*
8279 			 * We are not registered and trying to register but
8280 			 * the register key isn't zero.
8281 			 */
8282 			mtx_unlock(&lun->lun_lock);
8283 			free(ctsio->kern_data_ptr, M_CTL);
8284 			ctl_set_reservation_conflict(ctsio);
8285 			ctl_done((union ctl_io *)ctsio);
8286 			return (CTL_RETVAL_COMPLETE);
8287 		}
8288 		mtx_unlock(&lun->lun_lock);
8289 	}
8290 
8291 	switch (cdb->action & SPRO_ACTION_MASK) {
8292 	case SPRO_REGISTER:
8293 	case SPRO_REG_IGNO: {
8294 
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 			/*
8383 			 * If we aren't registered currently then increment
8384 			 * the key count and set the registered flag.
8385 			 */
8386 			ctl_alloc_prkey(lun, residx);
8387 			if (ctl_get_prkey(lun, residx) == 0)
8388 				lun->pr_key_count++;
8389 			ctl_set_prkey(lun, residx, sa_res_key);
8390 			lun->pr_generation++;
8391 			mtx_unlock(&lun->lun_lock);
8392 
8393 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8394 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8395 			persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8396 			persis_io.pr.pr_info.residx = residx;
8397 			memcpy(persis_io.pr.pr_info.sa_res_key,
8398 			       param->serv_act_res_key,
8399 			       sizeof(param->serv_act_res_key));
8400 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8401 			    sizeof(persis_io.pr), M_WAITOK);
8402 		}
8403 
8404 		break;
8405 	}
8406 	case SPRO_RESERVE:
8407 		mtx_lock(&lun->lun_lock);
8408 		if (lun->flags & CTL_LUN_PR_RESERVED) {
8409 			/*
8410 			 * if this isn't the reservation holder and it's
8411 			 * not a "all registrants" type or if the type is
8412 			 * different then we have a conflict
8413 			 */
8414 			if ((lun->pr_res_idx != residx
8415 			  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8416 			 || lun->pr_res_type != type) {
8417 				mtx_unlock(&lun->lun_lock);
8418 				free(ctsio->kern_data_ptr, M_CTL);
8419 				ctl_set_reservation_conflict(ctsio);
8420 				ctl_done((union ctl_io *)ctsio);
8421 				return (CTL_RETVAL_COMPLETE);
8422 			}
8423 			mtx_unlock(&lun->lun_lock);
8424 		} else /* create a reservation */ {
8425 			/*
8426 			 * If it's not an "all registrants" type record
8427 			 * reservation holder
8428 			 */
8429 			if (type != SPR_TYPE_WR_EX_AR
8430 			 && type != SPR_TYPE_EX_AC_AR)
8431 				lun->pr_res_idx = residx; /* Res holder */
8432 			else
8433 				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8434 
8435 			lun->flags |= CTL_LUN_PR_RESERVED;
8436 			lun->pr_res_type = type;
8437 
8438 			mtx_unlock(&lun->lun_lock);
8439 
8440 			/* send msg to other side */
8441 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8442 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8443 			persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8444 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8445 			persis_io.pr.pr_info.res_type = type;
8446 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8447 			    sizeof(persis_io.pr), M_WAITOK);
8448 		}
8449 		break;
8450 
8451 	case SPRO_RELEASE:
8452 		mtx_lock(&lun->lun_lock);
8453 		if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8454 			/* No reservation exists return good status */
8455 			mtx_unlock(&lun->lun_lock);
8456 			goto done;
8457 		}
8458 		/*
8459 		 * Is this nexus a reservation holder?
8460 		 */
8461 		if (lun->pr_res_idx != residx
8462 		 && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8463 			/*
8464 			 * not a res holder return good status but
8465 			 * do nothing
8466 			 */
8467 			mtx_unlock(&lun->lun_lock);
8468 			goto done;
8469 		}
8470 
8471 		if (lun->pr_res_type != type) {
8472 			mtx_unlock(&lun->lun_lock);
8473 			free(ctsio->kern_data_ptr, M_CTL);
8474 			ctl_set_illegal_pr_release(ctsio);
8475 			ctl_done((union ctl_io *)ctsio);
8476 			return (CTL_RETVAL_COMPLETE);
8477 		}
8478 
8479 		/* okay to release */
8480 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8481 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8482 		lun->pr_res_type = 0;
8483 
8484 		/*
8485 		 * If this isn't an exclusive access reservation and NUAR
8486 		 * is not set, generate UA for all other registrants.
8487 		 */
8488 		if (type != SPR_TYPE_EX_AC && type != SPR_TYPE_WR_EX &&
8489 		    (lun->MODE_CTRL.queue_flags & SCP_NUAR) == 0) {
8490 			for (i = softc->init_min; i < softc->init_max; i++) {
8491 				if (i == residx || ctl_get_prkey(lun, i) == 0)
8492 					continue;
8493 				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8494 			}
8495 		}
8496 		mtx_unlock(&lun->lun_lock);
8497 
8498 		/* Send msg to other side */
8499 		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8500 		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8501 		persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8502 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8503 		     sizeof(persis_io.pr), M_WAITOK);
8504 		break;
8505 
8506 	case SPRO_CLEAR:
8507 		/* send msg to other side */
8508 
8509 		mtx_lock(&lun->lun_lock);
8510 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8511 		lun->pr_res_type = 0;
8512 		lun->pr_key_count = 0;
8513 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8514 
8515 		ctl_clr_prkey(lun, residx);
8516 		for (i = 0; i < CTL_MAX_INITIATORS; i++)
8517 			if (ctl_get_prkey(lun, i) != 0) {
8518 				ctl_clr_prkey(lun, i);
8519 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8520 			}
8521 		lun->pr_generation++;
8522 		mtx_unlock(&lun->lun_lock);
8523 
8524 		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8525 		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8526 		persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8527 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8528 		     sizeof(persis_io.pr), M_WAITOK);
8529 		break;
8530 
8531 	case SPRO_PREEMPT:
8532 	case SPRO_PRE_ABO: {
8533 		int nretval;
8534 
8535 		nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8536 					  residx, ctsio, cdb, param);
8537 		if (nretval != 0)
8538 			return (CTL_RETVAL_COMPLETE);
8539 		break;
8540 	}
8541 	default:
8542 		panic("%s: Invalid PR type %#x", __func__, cdb->action);
8543 	}
8544 
8545 done:
8546 	free(ctsio->kern_data_ptr, M_CTL);
8547 	ctl_set_success(ctsio);
8548 	ctl_done((union ctl_io *)ctsio);
8549 
8550 	return (retval);
8551 }
8552 
8553 /*
8554  * This routine is for handling a message from the other SC pertaining to
8555  * persistent reserve out. All the error checking will have been done
8556  * so only perorming the action need be done here to keep the two
8557  * in sync.
8558  */
8559 static void
8560 ctl_hndl_per_res_out_on_other_sc(union ctl_io *io)
8561 {
8562 	struct ctl_softc *softc = CTL_SOFTC(io);
8563 	union ctl_ha_msg *msg = (union ctl_ha_msg *)&io->presio.pr_msg;
8564 	struct ctl_lun *lun;
8565 	int i;
8566 	uint32_t residx, targ_lun;
8567 
8568 	targ_lun = msg->hdr.nexus.targ_mapped_lun;
8569 	mtx_lock(&softc->ctl_lock);
8570 	if (targ_lun >= ctl_max_luns ||
8571 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
8572 		mtx_unlock(&softc->ctl_lock);
8573 		return;
8574 	}
8575 	mtx_lock(&lun->lun_lock);
8576 	mtx_unlock(&softc->ctl_lock);
8577 	if (lun->flags & CTL_LUN_DISABLED) {
8578 		mtx_unlock(&lun->lun_lock);
8579 		return;
8580 	}
8581 	residx = ctl_get_initindex(&msg->hdr.nexus);
8582 	switch(msg->pr.pr_info.action) {
8583 	case CTL_PR_REG_KEY:
8584 		ctl_alloc_prkey(lun, msg->pr.pr_info.residx);
8585 		if (ctl_get_prkey(lun, msg->pr.pr_info.residx) == 0)
8586 			lun->pr_key_count++;
8587 		ctl_set_prkey(lun, msg->pr.pr_info.residx,
8588 		    scsi_8btou64(msg->pr.pr_info.sa_res_key));
8589 		lun->pr_generation++;
8590 		break;
8591 
8592 	case CTL_PR_UNREG_KEY:
8593 		ctl_clr_prkey(lun, msg->pr.pr_info.residx);
8594 		lun->pr_key_count--;
8595 
8596 		/* XXX Need to see if the reservation has been released */
8597 		/* if so do we need to generate UA? */
8598 		if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8599 			lun->flags &= ~CTL_LUN_PR_RESERVED;
8600 			lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8601 
8602 			if ((lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8603 			     lun->pr_res_type == SPR_TYPE_EX_AC_RO) &&
8604 			    lun->pr_key_count) {
8605 				/*
8606 				 * If the reservation is a registrants
8607 				 * only type we need to generate a UA
8608 				 * for other registered inits.  The
8609 				 * sense code should be RESERVATIONS
8610 				 * RELEASED
8611 				 */
8612 
8613 				for (i = softc->init_min; i < softc->init_max; i++) {
8614 					if (ctl_get_prkey(lun, i) == 0)
8615 						continue;
8616 
8617 					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8618 				}
8619 			}
8620 			lun->pr_res_type = 0;
8621 		} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8622 			if (lun->pr_key_count==0) {
8623 				lun->flags &= ~CTL_LUN_PR_RESERVED;
8624 				lun->pr_res_type = 0;
8625 				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8626 			}
8627 		}
8628 		lun->pr_generation++;
8629 		break;
8630 
8631 	case CTL_PR_RESERVE:
8632 		lun->flags |= CTL_LUN_PR_RESERVED;
8633 		lun->pr_res_type = msg->pr.pr_info.res_type;
8634 		lun->pr_res_idx = msg->pr.pr_info.residx;
8635 
8636 		break;
8637 
8638 	case CTL_PR_RELEASE:
8639 		/*
8640 		 * If this isn't an exclusive access reservation and NUAR
8641 		 * is not set, generate UA for all other registrants.
8642 		 */
8643 		if (lun->pr_res_type != SPR_TYPE_EX_AC &&
8644 		    lun->pr_res_type != SPR_TYPE_WR_EX &&
8645 		    (lun->MODE_CTRL.queue_flags & SCP_NUAR) == 0) {
8646 			for (i = softc->init_min; i < softc->init_max; i++) {
8647 				if (i == residx || ctl_get_prkey(lun, i) == 0)
8648 					continue;
8649 				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8650 			}
8651 		}
8652 
8653 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8654 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8655 		lun->pr_res_type = 0;
8656 		break;
8657 
8658 	case CTL_PR_PREEMPT:
8659 		ctl_pro_preempt_other(lun, msg);
8660 		break;
8661 	case CTL_PR_CLEAR:
8662 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8663 		lun->pr_res_type = 0;
8664 		lun->pr_key_count = 0;
8665 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8666 
8667 		for (i=0; i < CTL_MAX_INITIATORS; i++) {
8668 			if (ctl_get_prkey(lun, i) == 0)
8669 				continue;
8670 			ctl_clr_prkey(lun, i);
8671 			ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8672 		}
8673 		lun->pr_generation++;
8674 		break;
8675 	}
8676 
8677 	mtx_unlock(&lun->lun_lock);
8678 }
8679 
8680 int
8681 ctl_read_write(struct ctl_scsiio *ctsio)
8682 {
8683 	struct ctl_lun *lun = CTL_LUN(ctsio);
8684 	struct ctl_lba_len_flags *lbalen;
8685 	uint64_t lba;
8686 	uint32_t num_blocks;
8687 	int flags, retval;
8688 	int isread;
8689 
8690 	CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8691 
8692 	flags = 0;
8693 	isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8694 	      || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8695 	switch (ctsio->cdb[0]) {
8696 	case READ_6:
8697 	case WRITE_6: {
8698 		struct scsi_rw_6 *cdb;
8699 
8700 		cdb = (struct scsi_rw_6 *)ctsio->cdb;
8701 
8702 		lba = scsi_3btoul(cdb->addr);
8703 		/* only 5 bits are valid in the most significant address byte */
8704 		lba &= 0x1fffff;
8705 		num_blocks = cdb->length;
8706 		/*
8707 		 * This is correct according to SBC-2.
8708 		 */
8709 		if (num_blocks == 0)
8710 			num_blocks = 256;
8711 		break;
8712 	}
8713 	case READ_10:
8714 	case WRITE_10: {
8715 		struct scsi_rw_10 *cdb;
8716 
8717 		cdb = (struct scsi_rw_10 *)ctsio->cdb;
8718 		if (cdb->byte2 & SRW10_FUA)
8719 			flags |= CTL_LLF_FUA;
8720 		if (cdb->byte2 & SRW10_DPO)
8721 			flags |= CTL_LLF_DPO;
8722 		lba = scsi_4btoul(cdb->addr);
8723 		num_blocks = scsi_2btoul(cdb->length);
8724 		break;
8725 	}
8726 	case WRITE_VERIFY_10: {
8727 		struct scsi_write_verify_10 *cdb;
8728 
8729 		cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
8730 		flags |= CTL_LLF_FUA;
8731 		if (cdb->byte2 & SWV_DPO)
8732 			flags |= CTL_LLF_DPO;
8733 		lba = scsi_4btoul(cdb->addr);
8734 		num_blocks = scsi_2btoul(cdb->length);
8735 		break;
8736 	}
8737 	case READ_12:
8738 	case WRITE_12: {
8739 		struct scsi_rw_12 *cdb;
8740 
8741 		cdb = (struct scsi_rw_12 *)ctsio->cdb;
8742 		if (cdb->byte2 & SRW12_FUA)
8743 			flags |= CTL_LLF_FUA;
8744 		if (cdb->byte2 & SRW12_DPO)
8745 			flags |= CTL_LLF_DPO;
8746 		lba = scsi_4btoul(cdb->addr);
8747 		num_blocks = scsi_4btoul(cdb->length);
8748 		break;
8749 	}
8750 	case WRITE_VERIFY_12: {
8751 		struct scsi_write_verify_12 *cdb;
8752 
8753 		cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
8754 		flags |= CTL_LLF_FUA;
8755 		if (cdb->byte2 & SWV_DPO)
8756 			flags |= CTL_LLF_DPO;
8757 		lba = scsi_4btoul(cdb->addr);
8758 		num_blocks = scsi_4btoul(cdb->length);
8759 		break;
8760 	}
8761 	case READ_16:
8762 	case WRITE_16: {
8763 		struct scsi_rw_16 *cdb;
8764 
8765 		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8766 		if (cdb->byte2 & SRW12_FUA)
8767 			flags |= CTL_LLF_FUA;
8768 		if (cdb->byte2 & SRW12_DPO)
8769 			flags |= CTL_LLF_DPO;
8770 		lba = scsi_8btou64(cdb->addr);
8771 		num_blocks = scsi_4btoul(cdb->length);
8772 		break;
8773 	}
8774 	case WRITE_ATOMIC_16: {
8775 		struct scsi_write_atomic_16 *cdb;
8776 
8777 		if (lun->be_lun->atomicblock == 0) {
8778 			ctl_set_invalid_opcode(ctsio);
8779 			ctl_done((union ctl_io *)ctsio);
8780 			return (CTL_RETVAL_COMPLETE);
8781 		}
8782 
8783 		cdb = (struct scsi_write_atomic_16 *)ctsio->cdb;
8784 		if (cdb->byte2 & SRW12_FUA)
8785 			flags |= CTL_LLF_FUA;
8786 		if (cdb->byte2 & SRW12_DPO)
8787 			flags |= CTL_LLF_DPO;
8788 		lba = scsi_8btou64(cdb->addr);
8789 		num_blocks = scsi_2btoul(cdb->length);
8790 		if (num_blocks > lun->be_lun->atomicblock) {
8791 			ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
8792 			    /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
8793 			    /*bit*/ 0);
8794 			ctl_done((union ctl_io *)ctsio);
8795 			return (CTL_RETVAL_COMPLETE);
8796 		}
8797 		break;
8798 	}
8799 	case WRITE_VERIFY_16: {
8800 		struct scsi_write_verify_16 *cdb;
8801 
8802 		cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
8803 		flags |= CTL_LLF_FUA;
8804 		if (cdb->byte2 & SWV_DPO)
8805 			flags |= CTL_LLF_DPO;
8806 		lba = scsi_8btou64(cdb->addr);
8807 		num_blocks = scsi_4btoul(cdb->length);
8808 		break;
8809 	}
8810 	default:
8811 		/*
8812 		 * We got a command we don't support.  This shouldn't
8813 		 * happen, commands should be filtered out above us.
8814 		 */
8815 		ctl_set_invalid_opcode(ctsio);
8816 		ctl_done((union ctl_io *)ctsio);
8817 
8818 		return (CTL_RETVAL_COMPLETE);
8819 		break; /* NOTREACHED */
8820 	}
8821 
8822 	/*
8823 	 * The first check is to make sure we're in bounds, the second
8824 	 * check is to catch wrap-around problems.  If the lba + num blocks
8825 	 * is less than the lba, then we've wrapped around and the block
8826 	 * range is invalid anyway.
8827 	 */
8828 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8829 	 || ((lba + num_blocks) < lba)) {
8830 		ctl_set_lba_out_of_range(ctsio,
8831 		    MAX(lba, lun->be_lun->maxlba + 1));
8832 		ctl_done((union ctl_io *)ctsio);
8833 		return (CTL_RETVAL_COMPLETE);
8834 	}
8835 
8836 	/*
8837 	 * According to SBC-3, a transfer length of 0 is not an error.
8838 	 * Note that this cannot happen with WRITE(6) or READ(6), since 0
8839 	 * translates to 256 blocks for those commands.
8840 	 */
8841 	if (num_blocks == 0) {
8842 		ctl_set_success(ctsio);
8843 		ctl_done((union ctl_io *)ctsio);
8844 		return (CTL_RETVAL_COMPLETE);
8845 	}
8846 
8847 	/* Set FUA and/or DPO if caches are disabled. */
8848 	if (isread) {
8849 		if ((lun->MODE_CACHING.flags1 & SCP_RCD) != 0)
8850 			flags |= CTL_LLF_FUA | CTL_LLF_DPO;
8851 	} else {
8852 		if ((lun->MODE_CACHING.flags1 & SCP_WCE) == 0)
8853 			flags |= CTL_LLF_FUA;
8854 	}
8855 
8856 	lbalen = (struct ctl_lba_len_flags *)
8857 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8858 	lbalen->lba = lba;
8859 	lbalen->len = num_blocks;
8860 	lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
8861 
8862 	ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
8863 	ctsio->kern_rel_offset = 0;
8864 
8865 	CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
8866 
8867 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8868 	return (retval);
8869 }
8870 
8871 static int
8872 ctl_cnw_cont(union ctl_io *io)
8873 {
8874 	struct ctl_lun *lun = CTL_LUN(io);
8875 	struct ctl_scsiio *ctsio;
8876 	struct ctl_lba_len_flags *lbalen;
8877 	int retval;
8878 
8879 	ctsio = &io->scsiio;
8880 	ctsio->io_hdr.status = CTL_STATUS_NONE;
8881 	ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
8882 	lbalen = (struct ctl_lba_len_flags *)
8883 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8884 	lbalen->flags &= ~CTL_LLF_COMPARE;
8885 	lbalen->flags |= CTL_LLF_WRITE;
8886 
8887 	CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
8888 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8889 	return (retval);
8890 }
8891 
8892 int
8893 ctl_cnw(struct ctl_scsiio *ctsio)
8894 {
8895 	struct ctl_lun *lun = CTL_LUN(ctsio);
8896 	struct ctl_lba_len_flags *lbalen;
8897 	uint64_t lba;
8898 	uint32_t num_blocks;
8899 	int flags, retval;
8900 
8901 	CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
8902 
8903 	flags = 0;
8904 	switch (ctsio->cdb[0]) {
8905 	case COMPARE_AND_WRITE: {
8906 		struct scsi_compare_and_write *cdb;
8907 
8908 		cdb = (struct scsi_compare_and_write *)ctsio->cdb;
8909 		if (cdb->byte2 & SRW10_FUA)
8910 			flags |= CTL_LLF_FUA;
8911 		if (cdb->byte2 & SRW10_DPO)
8912 			flags |= CTL_LLF_DPO;
8913 		lba = scsi_8btou64(cdb->addr);
8914 		num_blocks = cdb->length;
8915 		break;
8916 	}
8917 	default:
8918 		/*
8919 		 * We got a command we don't support.  This shouldn't
8920 		 * happen, commands should be filtered out above us.
8921 		 */
8922 		ctl_set_invalid_opcode(ctsio);
8923 		ctl_done((union ctl_io *)ctsio);
8924 
8925 		return (CTL_RETVAL_COMPLETE);
8926 		break; /* NOTREACHED */
8927 	}
8928 
8929 	/*
8930 	 * The first check is to make sure we're in bounds, the second
8931 	 * check is to catch wrap-around problems.  If the lba + num blocks
8932 	 * is less than the lba, then we've wrapped around and the block
8933 	 * range is invalid anyway.
8934 	 */
8935 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8936 	 || ((lba + num_blocks) < lba)) {
8937 		ctl_set_lba_out_of_range(ctsio,
8938 		    MAX(lba, lun->be_lun->maxlba + 1));
8939 		ctl_done((union ctl_io *)ctsio);
8940 		return (CTL_RETVAL_COMPLETE);
8941 	}
8942 
8943 	/*
8944 	 * According to SBC-3, a transfer length of 0 is not an error.
8945 	 */
8946 	if (num_blocks == 0) {
8947 		ctl_set_success(ctsio);
8948 		ctl_done((union ctl_io *)ctsio);
8949 		return (CTL_RETVAL_COMPLETE);
8950 	}
8951 
8952 	/* Set FUA if write cache is disabled. */
8953 	if ((lun->MODE_CACHING.flags1 & SCP_WCE) == 0)
8954 		flags |= CTL_LLF_FUA;
8955 
8956 	ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
8957 	ctsio->kern_rel_offset = 0;
8958 
8959 	/*
8960 	 * Set the IO_CONT flag, so that if this I/O gets passed to
8961 	 * ctl_data_submit_done(), it'll get passed back to
8962 	 * ctl_ctl_cnw_cont() for further processing.
8963 	 */
8964 	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
8965 	ctsio->io_cont = ctl_cnw_cont;
8966 
8967 	lbalen = (struct ctl_lba_len_flags *)
8968 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8969 	lbalen->lba = lba;
8970 	lbalen->len = num_blocks;
8971 	lbalen->flags = CTL_LLF_COMPARE | flags;
8972 
8973 	CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
8974 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8975 	return (retval);
8976 }
8977 
8978 int
8979 ctl_verify(struct ctl_scsiio *ctsio)
8980 {
8981 	struct ctl_lun *lun = CTL_LUN(ctsio);
8982 	struct ctl_lba_len_flags *lbalen;
8983 	uint64_t lba;
8984 	uint32_t num_blocks;
8985 	int bytchk, flags;
8986 	int retval;
8987 
8988 	CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
8989 
8990 	bytchk = 0;
8991 	flags = CTL_LLF_FUA;
8992 	switch (ctsio->cdb[0]) {
8993 	case VERIFY_10: {
8994 		struct scsi_verify_10 *cdb;
8995 
8996 		cdb = (struct scsi_verify_10 *)ctsio->cdb;
8997 		if (cdb->byte2 & SVFY_BYTCHK)
8998 			bytchk = 1;
8999 		if (cdb->byte2 & SVFY_DPO)
9000 			flags |= CTL_LLF_DPO;
9001 		lba = scsi_4btoul(cdb->addr);
9002 		num_blocks = scsi_2btoul(cdb->length);
9003 		break;
9004 	}
9005 	case VERIFY_12: {
9006 		struct scsi_verify_12 *cdb;
9007 
9008 		cdb = (struct scsi_verify_12 *)ctsio->cdb;
9009 		if (cdb->byte2 & SVFY_BYTCHK)
9010 			bytchk = 1;
9011 		if (cdb->byte2 & SVFY_DPO)
9012 			flags |= CTL_LLF_DPO;
9013 		lba = scsi_4btoul(cdb->addr);
9014 		num_blocks = scsi_4btoul(cdb->length);
9015 		break;
9016 	}
9017 	case VERIFY_16: {
9018 		struct scsi_rw_16 *cdb;
9019 
9020 		cdb = (struct scsi_rw_16 *)ctsio->cdb;
9021 		if (cdb->byte2 & SVFY_BYTCHK)
9022 			bytchk = 1;
9023 		if (cdb->byte2 & SVFY_DPO)
9024 			flags |= CTL_LLF_DPO;
9025 		lba = scsi_8btou64(cdb->addr);
9026 		num_blocks = scsi_4btoul(cdb->length);
9027 		break;
9028 	}
9029 	default:
9030 		/*
9031 		 * We got a command we don't support.  This shouldn't
9032 		 * happen, commands should be filtered out above us.
9033 		 */
9034 		ctl_set_invalid_opcode(ctsio);
9035 		ctl_done((union ctl_io *)ctsio);
9036 		return (CTL_RETVAL_COMPLETE);
9037 	}
9038 
9039 	/*
9040 	 * The first check is to make sure we're in bounds, the second
9041 	 * check is to catch wrap-around problems.  If the lba + num blocks
9042 	 * is less than the lba, then we've wrapped around and the block
9043 	 * range is invalid anyway.
9044 	 */
9045 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9046 	 || ((lba + num_blocks) < lba)) {
9047 		ctl_set_lba_out_of_range(ctsio,
9048 		    MAX(lba, lun->be_lun->maxlba + 1));
9049 		ctl_done((union ctl_io *)ctsio);
9050 		return (CTL_RETVAL_COMPLETE);
9051 	}
9052 
9053 	/*
9054 	 * According to SBC-3, a transfer length of 0 is not an error.
9055 	 */
9056 	if (num_blocks == 0) {
9057 		ctl_set_success(ctsio);
9058 		ctl_done((union ctl_io *)ctsio);
9059 		return (CTL_RETVAL_COMPLETE);
9060 	}
9061 
9062 	lbalen = (struct ctl_lba_len_flags *)
9063 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9064 	lbalen->lba = lba;
9065 	lbalen->len = num_blocks;
9066 	if (bytchk) {
9067 		lbalen->flags = CTL_LLF_COMPARE | flags;
9068 		ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9069 	} else {
9070 		lbalen->flags = CTL_LLF_VERIFY | flags;
9071 		ctsio->kern_total_len = 0;
9072 	}
9073 	ctsio->kern_rel_offset = 0;
9074 
9075 	CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9076 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9077 	return (retval);
9078 }
9079 
9080 int
9081 ctl_report_luns(struct ctl_scsiio *ctsio)
9082 {
9083 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9084 	struct ctl_port *port = CTL_PORT(ctsio);
9085 	struct ctl_lun *lun, *request_lun = CTL_LUN(ctsio);
9086 	struct scsi_report_luns *cdb;
9087 	struct scsi_report_luns_data *lun_data;
9088 	int num_filled, num_luns, num_port_luns, retval;
9089 	uint32_t alloc_len, lun_datalen;
9090 	uint32_t initidx, targ_lun_id, lun_id;
9091 
9092 	retval = CTL_RETVAL_COMPLETE;
9093 	cdb = (struct scsi_report_luns *)ctsio->cdb;
9094 
9095 	CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9096 
9097 	num_luns = 0;
9098 	num_port_luns = port->lun_map ? port->lun_map_size : ctl_max_luns;
9099 	mtx_lock(&softc->ctl_lock);
9100 	for (targ_lun_id = 0; targ_lun_id < num_port_luns; targ_lun_id++) {
9101 		if (ctl_lun_map_from_port(port, targ_lun_id) != UINT32_MAX)
9102 			num_luns++;
9103 	}
9104 	mtx_unlock(&softc->ctl_lock);
9105 
9106 	switch (cdb->select_report) {
9107 	case RPL_REPORT_DEFAULT:
9108 	case RPL_REPORT_ALL:
9109 	case RPL_REPORT_NONSUBSID:
9110 		break;
9111 	case RPL_REPORT_WELLKNOWN:
9112 	case RPL_REPORT_ADMIN:
9113 	case RPL_REPORT_CONGLOM:
9114 		num_luns = 0;
9115 		break;
9116 	default:
9117 		ctl_set_invalid_field(ctsio,
9118 				      /*sks_valid*/ 1,
9119 				      /*command*/ 1,
9120 				      /*field*/ 2,
9121 				      /*bit_valid*/ 0,
9122 				      /*bit*/ 0);
9123 		ctl_done((union ctl_io *)ctsio);
9124 		return (retval);
9125 		break; /* NOTREACHED */
9126 	}
9127 
9128 	alloc_len = scsi_4btoul(cdb->length);
9129 	/*
9130 	 * The initiator has to allocate at least 16 bytes for this request,
9131 	 * so he can at least get the header and the first LUN.  Otherwise
9132 	 * we reject the request (per SPC-3 rev 14, section 6.21).
9133 	 */
9134 	if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9135 	    sizeof(struct scsi_report_luns_lundata))) {
9136 		ctl_set_invalid_field(ctsio,
9137 				      /*sks_valid*/ 1,
9138 				      /*command*/ 1,
9139 				      /*field*/ 6,
9140 				      /*bit_valid*/ 0,
9141 				      /*bit*/ 0);
9142 		ctl_done((union ctl_io *)ctsio);
9143 		return (retval);
9144 	}
9145 
9146 	lun_datalen = sizeof(*lun_data) +
9147 		(num_luns * sizeof(struct scsi_report_luns_lundata));
9148 
9149 	ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9150 	lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9151 	ctsio->kern_sg_entries = 0;
9152 
9153 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9154 
9155 	mtx_lock(&softc->ctl_lock);
9156 	for (targ_lun_id = 0, num_filled = 0;
9157 	    targ_lun_id < num_port_luns && num_filled < num_luns;
9158 	    targ_lun_id++) {
9159 		lun_id = ctl_lun_map_from_port(port, targ_lun_id);
9160 		if (lun_id == UINT32_MAX)
9161 			continue;
9162 		lun = softc->ctl_luns[lun_id];
9163 		if (lun == NULL)
9164 			continue;
9165 
9166 		be64enc(lun_data->luns[num_filled++].lundata,
9167 		    ctl_encode_lun(targ_lun_id));
9168 
9169 		/*
9170 		 * According to SPC-3, rev 14 section 6.21:
9171 		 *
9172 		 * "The execution of a REPORT LUNS command to any valid and
9173 		 * installed logical unit shall clear the REPORTED LUNS DATA
9174 		 * HAS CHANGED unit attention condition for all logical
9175 		 * units of that target with respect to the requesting
9176 		 * initiator. A valid and installed logical unit is one
9177 		 * having a PERIPHERAL QUALIFIER of 000b in the standard
9178 		 * INQUIRY data (see 6.4.2)."
9179 		 *
9180 		 * If request_lun is NULL, the LUN this report luns command
9181 		 * was issued to is either disabled or doesn't exist. In that
9182 		 * case, we shouldn't clear any pending lun change unit
9183 		 * attention.
9184 		 */
9185 		if (request_lun != NULL) {
9186 			mtx_lock(&lun->lun_lock);
9187 			ctl_clr_ua(lun, initidx, CTL_UA_LUN_CHANGE);
9188 			mtx_unlock(&lun->lun_lock);
9189 		}
9190 	}
9191 	mtx_unlock(&softc->ctl_lock);
9192 
9193 	/*
9194 	 * It's quite possible that we've returned fewer LUNs than we allocated
9195 	 * space for.  Trim it.
9196 	 */
9197 	lun_datalen = sizeof(*lun_data) +
9198 		(num_filled * sizeof(struct scsi_report_luns_lundata));
9199 	ctsio->kern_rel_offset = 0;
9200 	ctsio->kern_sg_entries = 0;
9201 	ctsio->kern_data_len = min(lun_datalen, alloc_len);
9202 	ctsio->kern_total_len = ctsio->kern_data_len;
9203 
9204 	/*
9205 	 * We set this to the actual data length, regardless of how much
9206 	 * space we actually have to return results.  If the user looks at
9207 	 * this value, he'll know whether or not he allocated enough space
9208 	 * and reissue the command if necessary.  We don't support well
9209 	 * known logical units, so if the user asks for that, return none.
9210 	 */
9211 	scsi_ulto4b(lun_datalen - 8, lun_data->length);
9212 
9213 	/*
9214 	 * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9215 	 * this request.
9216 	 */
9217 	ctl_set_success(ctsio);
9218 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9219 	ctsio->be_move_done = ctl_config_move_done;
9220 	ctl_datamove((union ctl_io *)ctsio);
9221 	return (retval);
9222 }
9223 
9224 int
9225 ctl_request_sense(struct ctl_scsiio *ctsio)
9226 {
9227 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9228 	struct ctl_lun *lun = CTL_LUN(ctsio);
9229 	struct scsi_request_sense *cdb;
9230 	struct scsi_sense_data *sense_ptr, *ps;
9231 	uint32_t initidx;
9232 	int have_error;
9233 	u_int sense_len = SSD_FULL_SIZE;
9234 	scsi_sense_data_type sense_format;
9235 	ctl_ua_type ua_type;
9236 	uint8_t asc = 0, ascq = 0;
9237 
9238 	cdb = (struct scsi_request_sense *)ctsio->cdb;
9239 
9240 	CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9241 
9242 	/*
9243 	 * Determine which sense format the user wants.
9244 	 */
9245 	if (cdb->byte2 & SRS_DESC)
9246 		sense_format = SSD_TYPE_DESC;
9247 	else
9248 		sense_format = SSD_TYPE_FIXED;
9249 
9250 	ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9251 	sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9252 	ctsio->kern_sg_entries = 0;
9253 	ctsio->kern_rel_offset = 0;
9254 
9255 	/*
9256 	 * struct scsi_sense_data, which is currently set to 256 bytes, is
9257 	 * larger than the largest allowed value for the length field in the
9258 	 * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9259 	 */
9260 	ctsio->kern_data_len = cdb->length;
9261 	ctsio->kern_total_len = cdb->length;
9262 
9263 	/*
9264 	 * If we don't have a LUN, we don't have any pending sense.
9265 	 */
9266 	if (lun == NULL ||
9267 	    ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
9268 	     softc->ha_link < CTL_HA_LINK_UNKNOWN)) {
9269 		/* "Logical unit not supported" */
9270 		ctl_set_sense_data(sense_ptr, &sense_len, NULL, sense_format,
9271 		    /*current_error*/ 1,
9272 		    /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
9273 		    /*asc*/ 0x25,
9274 		    /*ascq*/ 0x00,
9275 		    SSD_ELEM_NONE);
9276 		goto send;
9277 	}
9278 
9279 	have_error = 0;
9280 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9281 	/*
9282 	 * Check for pending sense, and then for pending unit attentions.
9283 	 * Pending sense gets returned first, then pending unit attentions.
9284 	 */
9285 	mtx_lock(&lun->lun_lock);
9286 	ps = lun->pending_sense[initidx / CTL_MAX_INIT_PER_PORT];
9287 	if (ps != NULL)
9288 		ps += initidx % CTL_MAX_INIT_PER_PORT;
9289 	if (ps != NULL && ps->error_code != 0) {
9290 		scsi_sense_data_type stored_format;
9291 
9292 		/*
9293 		 * Check to see which sense format was used for the stored
9294 		 * sense data.
9295 		 */
9296 		stored_format = scsi_sense_type(ps);
9297 
9298 		/*
9299 		 * If the user requested a different sense format than the
9300 		 * one we stored, then we need to convert it to the other
9301 		 * format.  If we're going from descriptor to fixed format
9302 		 * sense data, we may lose things in translation, depending
9303 		 * on what options were used.
9304 		 *
9305 		 * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9306 		 * for some reason we'll just copy it out as-is.
9307 		 */
9308 		if ((stored_format == SSD_TYPE_FIXED)
9309 		 && (sense_format == SSD_TYPE_DESC))
9310 			ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9311 			    ps, (struct scsi_sense_data_desc *)sense_ptr);
9312 		else if ((stored_format == SSD_TYPE_DESC)
9313 		      && (sense_format == SSD_TYPE_FIXED))
9314 			ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9315 			    ps, (struct scsi_sense_data_fixed *)sense_ptr);
9316 		else
9317 			memcpy(sense_ptr, ps, sizeof(*sense_ptr));
9318 
9319 		ps->error_code = 0;
9320 		have_error = 1;
9321 	} else {
9322 		ua_type = ctl_build_ua(lun, initidx, sense_ptr, &sense_len,
9323 		    sense_format);
9324 		if (ua_type != CTL_UA_NONE)
9325 			have_error = 1;
9326 	}
9327 	if (have_error == 0) {
9328 		/*
9329 		 * Report informational exception if have one and allowed.
9330 		 */
9331 		if (lun->MODE_IE.mrie != SIEP_MRIE_NO) {
9332 			asc = lun->ie_asc;
9333 			ascq = lun->ie_ascq;
9334 		}
9335 		ctl_set_sense_data(sense_ptr, &sense_len, lun, sense_format,
9336 		    /*current_error*/ 1,
9337 		    /*sense_key*/ SSD_KEY_NO_SENSE,
9338 		    /*asc*/ asc,
9339 		    /*ascq*/ ascq,
9340 		    SSD_ELEM_NONE);
9341 	}
9342 	mtx_unlock(&lun->lun_lock);
9343 
9344 send:
9345 	/*
9346 	 * We report the SCSI status as OK, since the status of the command
9347 	 * itself is OK.  We're reporting sense as parameter data.
9348 	 */
9349 	ctl_set_success(ctsio);
9350 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9351 	ctsio->be_move_done = ctl_config_move_done;
9352 	ctl_datamove((union ctl_io *)ctsio);
9353 	return (CTL_RETVAL_COMPLETE);
9354 }
9355 
9356 int
9357 ctl_tur(struct ctl_scsiio *ctsio)
9358 {
9359 
9360 	CTL_DEBUG_PRINT(("ctl_tur\n"));
9361 
9362 	ctl_set_success(ctsio);
9363 	ctl_done((union ctl_io *)ctsio);
9364 
9365 	return (CTL_RETVAL_COMPLETE);
9366 }
9367 
9368 /*
9369  * SCSI VPD page 0x00, the Supported VPD Pages page.
9370  */
9371 static int
9372 ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9373 {
9374 	struct ctl_lun *lun = CTL_LUN(ctsio);
9375 	struct scsi_vpd_supported_pages *pages;
9376 	int sup_page_size;
9377 	int p;
9378 
9379 	sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9380 	    SCSI_EVPD_NUM_SUPPORTED_PAGES;
9381 	ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9382 	pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9383 	ctsio->kern_rel_offset = 0;
9384 	ctsio->kern_sg_entries = 0;
9385 	ctsio->kern_data_len = min(sup_page_size, alloc_len);
9386 	ctsio->kern_total_len = ctsio->kern_data_len;
9387 
9388 	/*
9389 	 * The control device is always connected.  The disk device, on the
9390 	 * other hand, may not be online all the time.  Need to change this
9391 	 * to figure out whether the disk device is actually online or not.
9392 	 */
9393 	if (lun != NULL)
9394 		pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9395 				lun->be_lun->lun_type;
9396 	else
9397 		pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9398 
9399 	p = 0;
9400 	/* Supported VPD pages */
9401 	pages->page_list[p++] = SVPD_SUPPORTED_PAGES;
9402 	/* Serial Number */
9403 	pages->page_list[p++] = SVPD_UNIT_SERIAL_NUMBER;
9404 	/* Device Identification */
9405 	pages->page_list[p++] = SVPD_DEVICE_ID;
9406 	/* Extended INQUIRY Data */
9407 	pages->page_list[p++] = SVPD_EXTENDED_INQUIRY_DATA;
9408 	/* Mode Page Policy */
9409 	pages->page_list[p++] = SVPD_MODE_PAGE_POLICY;
9410 	/* SCSI Ports */
9411 	pages->page_list[p++] = SVPD_SCSI_PORTS;
9412 	/* Third-party Copy */
9413 	pages->page_list[p++] = SVPD_SCSI_TPC;
9414 	/* SCSI Feature Sets */
9415 	pages->page_list[p++] = SVPD_SCSI_SFS;
9416 	if (lun != NULL && lun->be_lun->lun_type == T_DIRECT) {
9417 		/* Block limits */
9418 		pages->page_list[p++] = SVPD_BLOCK_LIMITS;
9419 		/* Block Device Characteristics */
9420 		pages->page_list[p++] = SVPD_BDC;
9421 		/* Logical Block Provisioning */
9422 		pages->page_list[p++] = SVPD_LBP;
9423 	}
9424 	pages->length = p;
9425 
9426 	ctl_set_success(ctsio);
9427 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9428 	ctsio->be_move_done = ctl_config_move_done;
9429 	ctl_datamove((union ctl_io *)ctsio);
9430 	return (CTL_RETVAL_COMPLETE);
9431 }
9432 
9433 /*
9434  * SCSI VPD page 0x80, the Unit Serial Number page.
9435  */
9436 static int
9437 ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9438 {
9439 	struct ctl_lun *lun = CTL_LUN(ctsio);
9440 	struct scsi_vpd_unit_serial_number *sn_ptr;
9441 	int data_len;
9442 
9443 	data_len = 4 + CTL_SN_LEN;
9444 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9445 	sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9446 	ctsio->kern_rel_offset = 0;
9447 	ctsio->kern_sg_entries = 0;
9448 	ctsio->kern_data_len = min(data_len, alloc_len);
9449 	ctsio->kern_total_len = ctsio->kern_data_len;
9450 
9451 	/*
9452 	 * The control device is always connected.  The disk device, on the
9453 	 * other hand, may not be online all the time.  Need to change this
9454 	 * to figure out whether the disk device is actually online or not.
9455 	 */
9456 	if (lun != NULL)
9457 		sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9458 				  lun->be_lun->lun_type;
9459 	else
9460 		sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9461 
9462 	sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9463 	sn_ptr->length = CTL_SN_LEN;
9464 	/*
9465 	 * If we don't have a LUN, we just leave the serial number as
9466 	 * all spaces.
9467 	 */
9468 	if (lun != NULL) {
9469 		strncpy((char *)sn_ptr->serial_num,
9470 			(char *)lun->be_lun->serial_num, CTL_SN_LEN);
9471 	} else
9472 		memset(sn_ptr->serial_num, 0x20, CTL_SN_LEN);
9473 
9474 	ctl_set_success(ctsio);
9475 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9476 	ctsio->be_move_done = ctl_config_move_done;
9477 	ctl_datamove((union ctl_io *)ctsio);
9478 	return (CTL_RETVAL_COMPLETE);
9479 }
9480 
9481 
9482 /*
9483  * SCSI VPD page 0x86, the Extended INQUIRY Data page.
9484  */
9485 static int
9486 ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9487 {
9488 	struct ctl_lun *lun = CTL_LUN(ctsio);
9489 	struct scsi_vpd_extended_inquiry_data *eid_ptr;
9490 	int data_len;
9491 
9492 	data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
9493 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9494 	eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9495 	ctsio->kern_sg_entries = 0;
9496 	ctsio->kern_rel_offset = 0;
9497 	ctsio->kern_data_len = min(data_len, alloc_len);
9498 	ctsio->kern_total_len = ctsio->kern_data_len;
9499 
9500 	/*
9501 	 * The control device is always connected.  The disk device, on the
9502 	 * other hand, may not be online all the time.
9503 	 */
9504 	if (lun != NULL)
9505 		eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9506 				     lun->be_lun->lun_type;
9507 	else
9508 		eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9509 	eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9510 	scsi_ulto2b(data_len - 4, eid_ptr->page_length);
9511 	/*
9512 	 * We support head of queue, ordered and simple tags.
9513 	 */
9514 	eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9515 	/*
9516 	 * Volatile cache supported.
9517 	 */
9518 	eid_ptr->flags3 = SVPD_EID_V_SUP;
9519 
9520 	/*
9521 	 * This means that we clear the REPORTED LUNS DATA HAS CHANGED unit
9522 	 * attention for a particular IT nexus on all LUNs once we report
9523 	 * it to that nexus once.  This bit is required as of SPC-4.
9524 	 */
9525 	eid_ptr->flags4 = SVPD_EID_LUICLR;
9526 
9527 	/*
9528 	 * We support revert to defaults (RTD) bit in MODE SELECT.
9529 	 */
9530 	eid_ptr->flags5 = SVPD_EID_RTD_SUP;
9531 
9532 	/*
9533 	 * XXX KDM in order to correctly answer this, we would need
9534 	 * information from the SIM to determine how much sense data it
9535 	 * can send.  So this would really be a path inquiry field, most
9536 	 * likely.  This can be set to a maximum of 252 according to SPC-4,
9537 	 * but the hardware may or may not be able to support that much.
9538 	 * 0 just means that the maximum sense data length is not reported.
9539 	 */
9540 	eid_ptr->max_sense_length = 0;
9541 
9542 	ctl_set_success(ctsio);
9543 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9544 	ctsio->be_move_done = ctl_config_move_done;
9545 	ctl_datamove((union ctl_io *)ctsio);
9546 	return (CTL_RETVAL_COMPLETE);
9547 }
9548 
9549 static int
9550 ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
9551 {
9552 	struct ctl_lun *lun = CTL_LUN(ctsio);
9553 	struct scsi_vpd_mode_page_policy *mpp_ptr;
9554 	int data_len;
9555 
9556 	data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9557 	    sizeof(struct scsi_vpd_mode_page_policy_descr);
9558 
9559 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9560 	mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
9561 	ctsio->kern_rel_offset = 0;
9562 	ctsio->kern_sg_entries = 0;
9563 	ctsio->kern_data_len = min(data_len, alloc_len);
9564 	ctsio->kern_total_len = ctsio->kern_data_len;
9565 
9566 	/*
9567 	 * The control device is always connected.  The disk device, on the
9568 	 * other hand, may not be online all the time.
9569 	 */
9570 	if (lun != NULL)
9571 		mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9572 				     lun->be_lun->lun_type;
9573 	else
9574 		mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9575 	mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
9576 	scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
9577 	mpp_ptr->descr[0].page_code = 0x3f;
9578 	mpp_ptr->descr[0].subpage_code = 0xff;
9579 	mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
9580 
9581 	ctl_set_success(ctsio);
9582 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9583 	ctsio->be_move_done = ctl_config_move_done;
9584 	ctl_datamove((union ctl_io *)ctsio);
9585 	return (CTL_RETVAL_COMPLETE);
9586 }
9587 
9588 /*
9589  * SCSI VPD page 0x83, the Device Identification page.
9590  */
9591 static int
9592 ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9593 {
9594 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9595 	struct ctl_port *port = CTL_PORT(ctsio);
9596 	struct ctl_lun *lun = CTL_LUN(ctsio);
9597 	struct scsi_vpd_device_id *devid_ptr;
9598 	struct scsi_vpd_id_descriptor *desc;
9599 	int data_len, g;
9600 	uint8_t proto;
9601 
9602 	data_len = sizeof(struct scsi_vpd_device_id) +
9603 	    sizeof(struct scsi_vpd_id_descriptor) +
9604 		sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9605 	    sizeof(struct scsi_vpd_id_descriptor) +
9606 		sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9607 	if (lun && lun->lun_devid)
9608 		data_len += lun->lun_devid->len;
9609 	if (port && port->port_devid)
9610 		data_len += port->port_devid->len;
9611 	if (port && port->target_devid)
9612 		data_len += port->target_devid->len;
9613 
9614 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9615 	devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9616 	ctsio->kern_sg_entries = 0;
9617 	ctsio->kern_rel_offset = 0;
9618 	ctsio->kern_sg_entries = 0;
9619 	ctsio->kern_data_len = min(data_len, alloc_len);
9620 	ctsio->kern_total_len = ctsio->kern_data_len;
9621 
9622 	/*
9623 	 * The control device is always connected.  The disk device, on the
9624 	 * other hand, may not be online all the time.
9625 	 */
9626 	if (lun != NULL)
9627 		devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9628 				     lun->be_lun->lun_type;
9629 	else
9630 		devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9631 	devid_ptr->page_code = SVPD_DEVICE_ID;
9632 	scsi_ulto2b(data_len - 4, devid_ptr->length);
9633 
9634 	if (port && port->port_type == CTL_PORT_FC)
9635 		proto = SCSI_PROTO_FC << 4;
9636 	else if (port && port->port_type == CTL_PORT_SAS)
9637 		proto = SCSI_PROTO_SAS << 4;
9638 	else if (port && port->port_type == CTL_PORT_ISCSI)
9639 		proto = SCSI_PROTO_ISCSI << 4;
9640 	else
9641 		proto = SCSI_PROTO_SPI << 4;
9642 	desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
9643 
9644 	/*
9645 	 * We're using a LUN association here.  i.e., this device ID is a
9646 	 * per-LUN identifier.
9647 	 */
9648 	if (lun && lun->lun_devid) {
9649 		memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
9650 		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9651 		    lun->lun_devid->len);
9652 	}
9653 
9654 	/*
9655 	 * This is for the WWPN which is a port association.
9656 	 */
9657 	if (port && port->port_devid) {
9658 		memcpy(desc, port->port_devid->data, port->port_devid->len);
9659 		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9660 		    port->port_devid->len);
9661 	}
9662 
9663 	/*
9664 	 * This is for the Relative Target Port(type 4h) identifier
9665 	 */
9666 	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9667 	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9668 	    SVPD_ID_TYPE_RELTARG;
9669 	desc->length = 4;
9670 	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
9671 	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9672 	    sizeof(struct scsi_vpd_id_rel_trgt_port_id));
9673 
9674 	/*
9675 	 * This is for the Target Port Group(type 5h) identifier
9676 	 */
9677 	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9678 	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9679 	    SVPD_ID_TYPE_TPORTGRP;
9680 	desc->length = 4;
9681 	if (softc->is_single ||
9682 	    (port && port->status & CTL_PORT_STATUS_HA_SHARED))
9683 		g = 1;
9684 	else
9685 		g = 2 + ctsio->io_hdr.nexus.targ_port / softc->port_cnt;
9686 	scsi_ulto2b(g, &desc->identifier[2]);
9687 	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9688 	    sizeof(struct scsi_vpd_id_trgt_port_grp_id));
9689 
9690 	/*
9691 	 * This is for the Target identifier
9692 	 */
9693 	if (port && port->target_devid) {
9694 		memcpy(desc, port->target_devid->data, port->target_devid->len);
9695 	}
9696 
9697 	ctl_set_success(ctsio);
9698 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9699 	ctsio->be_move_done = ctl_config_move_done;
9700 	ctl_datamove((union ctl_io *)ctsio);
9701 	return (CTL_RETVAL_COMPLETE);
9702 }
9703 
9704 static int
9705 ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
9706 {
9707 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9708 	struct ctl_lun *lun = CTL_LUN(ctsio);
9709 	struct scsi_vpd_scsi_ports *sp;
9710 	struct scsi_vpd_port_designation *pd;
9711 	struct scsi_vpd_port_designation_cont *pdc;
9712 	struct ctl_port *port;
9713 	int data_len, num_target_ports, iid_len, id_len;
9714 
9715 	num_target_ports = 0;
9716 	iid_len = 0;
9717 	id_len = 0;
9718 	mtx_lock(&softc->ctl_lock);
9719 	STAILQ_FOREACH(port, &softc->port_list, links) {
9720 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9721 			continue;
9722 		if (lun != NULL &&
9723 		    ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
9724 			continue;
9725 		num_target_ports++;
9726 		if (port->init_devid)
9727 			iid_len += port->init_devid->len;
9728 		if (port->port_devid)
9729 			id_len += port->port_devid->len;
9730 	}
9731 	mtx_unlock(&softc->ctl_lock);
9732 
9733 	data_len = sizeof(struct scsi_vpd_scsi_ports) +
9734 	    num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
9735 	     sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
9736 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9737 	sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
9738 	ctsio->kern_sg_entries = 0;
9739 	ctsio->kern_rel_offset = 0;
9740 	ctsio->kern_sg_entries = 0;
9741 	ctsio->kern_data_len = min(data_len, alloc_len);
9742 	ctsio->kern_total_len = ctsio->kern_data_len;
9743 
9744 	/*
9745 	 * The control device is always connected.  The disk device, on the
9746 	 * other hand, may not be online all the time.  Need to change this
9747 	 * to figure out whether the disk device is actually online or not.
9748 	 */
9749 	if (lun != NULL)
9750 		sp->device = (SID_QUAL_LU_CONNECTED << 5) |
9751 				  lun->be_lun->lun_type;
9752 	else
9753 		sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9754 
9755 	sp->page_code = SVPD_SCSI_PORTS;
9756 	scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
9757 	    sp->page_length);
9758 	pd = &sp->design[0];
9759 
9760 	mtx_lock(&softc->ctl_lock);
9761 	STAILQ_FOREACH(port, &softc->port_list, links) {
9762 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9763 			continue;
9764 		if (lun != NULL &&
9765 		    ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
9766 			continue;
9767 		scsi_ulto2b(port->targ_port, pd->relative_port_id);
9768 		if (port->init_devid) {
9769 			iid_len = port->init_devid->len;
9770 			memcpy(pd->initiator_transportid,
9771 			    port->init_devid->data, port->init_devid->len);
9772 		} else
9773 			iid_len = 0;
9774 		scsi_ulto2b(iid_len, pd->initiator_transportid_length);
9775 		pdc = (struct scsi_vpd_port_designation_cont *)
9776 		    (&pd->initiator_transportid[iid_len]);
9777 		if (port->port_devid) {
9778 			id_len = port->port_devid->len;
9779 			memcpy(pdc->target_port_descriptors,
9780 			    port->port_devid->data, port->port_devid->len);
9781 		} else
9782 			id_len = 0;
9783 		scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
9784 		pd = (struct scsi_vpd_port_designation *)
9785 		    ((uint8_t *)pdc->target_port_descriptors + id_len);
9786 	}
9787 	mtx_unlock(&softc->ctl_lock);
9788 
9789 	ctl_set_success(ctsio);
9790 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9791 	ctsio->be_move_done = ctl_config_move_done;
9792 	ctl_datamove((union ctl_io *)ctsio);
9793 	return (CTL_RETVAL_COMPLETE);
9794 }
9795 
9796 static int
9797 ctl_inquiry_evpd_sfs(struct ctl_scsiio *ctsio, int alloc_len)
9798 {
9799 	struct ctl_lun *lun = CTL_LUN(ctsio);
9800 	struct scsi_vpd_sfs *sfs_ptr;
9801 	int sfs_page_size, n;
9802 
9803 	sfs_page_size = sizeof(*sfs_ptr) + 5 * 2;
9804 	ctsio->kern_data_ptr = malloc(sfs_page_size, M_CTL, M_WAITOK | M_ZERO);
9805 	sfs_ptr = (struct scsi_vpd_sfs *)ctsio->kern_data_ptr;
9806 	ctsio->kern_sg_entries = 0;
9807 	ctsio->kern_rel_offset = 0;
9808 	ctsio->kern_sg_entries = 0;
9809 	ctsio->kern_data_len = min(sfs_page_size, alloc_len);
9810 	ctsio->kern_total_len = ctsio->kern_data_len;
9811 
9812 	/*
9813 	 * The control device is always connected.  The disk device, on the
9814 	 * other hand, may not be online all the time.  Need to change this
9815 	 * to figure out whether the disk device is actually online or not.
9816 	 */
9817 	if (lun != NULL)
9818 		sfs_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9819 				  lun->be_lun->lun_type;
9820 	else
9821 		sfs_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9822 
9823 	sfs_ptr->page_code = SVPD_SCSI_SFS;
9824 	n = 0;
9825 	/* Discovery 2016 */
9826 	scsi_ulto2b(0x0001, &sfs_ptr->codes[2 * n++]);
9827 	if (lun != NULL && lun->be_lun->lun_type == T_DIRECT) {
9828 		 /* SBC Base 2016 */
9829 		scsi_ulto2b(0x0101, &sfs_ptr->codes[2 * n++]);
9830 		 /* SBC Base 2010 */
9831 		scsi_ulto2b(0x0102, &sfs_ptr->codes[2 * n++]);
9832 		if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9833 			/* Basic Provisioning 2016 */
9834 			scsi_ulto2b(0x0103, &sfs_ptr->codes[2 * n++]);
9835 		}
9836 		/* Drive Maintenance 2016 */
9837 		//scsi_ulto2b(0x0104, &sfs_ptr->codes[2 * n++]);
9838 	}
9839 	scsi_ulto2b(4 + 2 * n, sfs_ptr->page_length);
9840 
9841 	ctl_set_success(ctsio);
9842 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9843 	ctsio->be_move_done = ctl_config_move_done;
9844 	ctl_datamove((union ctl_io *)ctsio);
9845 	return (CTL_RETVAL_COMPLETE);
9846 }
9847 
9848 static int
9849 ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
9850 {
9851 	struct ctl_lun *lun = CTL_LUN(ctsio);
9852 	struct scsi_vpd_block_limits *bl_ptr;
9853 	const char *val;
9854 	uint64_t ival;
9855 
9856 	ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
9857 	bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
9858 	ctsio->kern_sg_entries = 0;
9859 	ctsio->kern_rel_offset = 0;
9860 	ctsio->kern_sg_entries = 0;
9861 	ctsio->kern_data_len = min(sizeof(*bl_ptr), alloc_len);
9862 	ctsio->kern_total_len = ctsio->kern_data_len;
9863 
9864 	/*
9865 	 * The control device is always connected.  The disk device, on the
9866 	 * other hand, may not be online all the time.  Need to change this
9867 	 * to figure out whether the disk device is actually online or not.
9868 	 */
9869 	if (lun != NULL)
9870 		bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9871 				  lun->be_lun->lun_type;
9872 	else
9873 		bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9874 
9875 	bl_ptr->page_code = SVPD_BLOCK_LIMITS;
9876 	scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
9877 	bl_ptr->max_cmp_write_len = 0xff;
9878 	scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
9879 	if (lun != NULL) {
9880 		scsi_ulto4b(lun->be_lun->opttxferlen, bl_ptr->opt_txfer_len);
9881 		if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9882 			ival = 0xffffffff;
9883 			val = dnvlist_get_string(lun->be_lun->options,
9884 			    "unmap_max_lba", NULL);
9885 			if (val != NULL)
9886 				ctl_expand_number(val, &ival);
9887 			scsi_ulto4b(ival, bl_ptr->max_unmap_lba_cnt);
9888 			ival = 0xffffffff;
9889 			val = dnvlist_get_string(lun->be_lun->options,
9890 			    "unmap_max_descr", NULL);
9891 			if (val != NULL)
9892 				ctl_expand_number(val, &ival);
9893 			scsi_ulto4b(ival, bl_ptr->max_unmap_blk_cnt);
9894 			if (lun->be_lun->ublockexp != 0) {
9895 				scsi_ulto4b((1 << lun->be_lun->ublockexp),
9896 				    bl_ptr->opt_unmap_grain);
9897 				scsi_ulto4b(0x80000000 | lun->be_lun->ublockoff,
9898 				    bl_ptr->unmap_grain_align);
9899 			}
9900 		}
9901 		scsi_ulto4b(lun->be_lun->atomicblock,
9902 		    bl_ptr->max_atomic_transfer_length);
9903 		scsi_ulto4b(0, bl_ptr->atomic_alignment);
9904 		scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
9905 		scsi_ulto4b(0, bl_ptr->max_atomic_transfer_length_with_atomic_boundary);
9906 		scsi_ulto4b(0, bl_ptr->max_atomic_boundary_size);
9907 		ival = UINT64_MAX;
9908 		val = dnvlist_get_string(lun->be_lun->options,
9909 		    "write_same_max_lba", NULL);
9910 		if (val != NULL)
9911 			ctl_expand_number(val, &ival);
9912 		scsi_u64to8b(ival, bl_ptr->max_write_same_length);
9913 		if (lun->be_lun->maxlba + 1 > ival)
9914 			bl_ptr->flags |= SVPD_BL_WSNZ;
9915 	}
9916 
9917 	ctl_set_success(ctsio);
9918 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9919 	ctsio->be_move_done = ctl_config_move_done;
9920 	ctl_datamove((union ctl_io *)ctsio);
9921 	return (CTL_RETVAL_COMPLETE);
9922 }
9923 
9924 static int
9925 ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
9926 {
9927 	struct ctl_lun *lun = CTL_LUN(ctsio);
9928 	struct scsi_vpd_block_device_characteristics *bdc_ptr;
9929 	const char *value;
9930 	u_int i;
9931 
9932 	ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
9933 	bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
9934 	ctsio->kern_sg_entries = 0;
9935 	ctsio->kern_rel_offset = 0;
9936 	ctsio->kern_data_len = min(sizeof(*bdc_ptr), alloc_len);
9937 	ctsio->kern_total_len = ctsio->kern_data_len;
9938 
9939 	/*
9940 	 * The control device is always connected.  The disk device, on the
9941 	 * other hand, may not be online all the time.  Need to change this
9942 	 * to figure out whether the disk device is actually online or not.
9943 	 */
9944 	if (lun != NULL)
9945 		bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9946 				  lun->be_lun->lun_type;
9947 	else
9948 		bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9949 	bdc_ptr->page_code = SVPD_BDC;
9950 	scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
9951 	if (lun != NULL &&
9952 	    (value = dnvlist_get_string(lun->be_lun->options, "rpm", NULL)) != NULL)
9953 		i = strtol(value, NULL, 0);
9954 	else
9955 		i = CTL_DEFAULT_ROTATION_RATE;
9956 	scsi_ulto2b(i, bdc_ptr->medium_rotation_rate);
9957 	if (lun != NULL &&
9958 	    (value = dnvlist_get_string(lun->be_lun->options, "formfactor", NULL)) != NULL)
9959 		i = strtol(value, NULL, 0);
9960 	else
9961 		i = 0;
9962 	bdc_ptr->wab_wac_ff = (i & 0x0f);
9963 	bdc_ptr->flags = SVPD_RBWZ | SVPD_FUAB | SVPD_VBULS;
9964 
9965 	ctl_set_success(ctsio);
9966 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9967 	ctsio->be_move_done = ctl_config_move_done;
9968 	ctl_datamove((union ctl_io *)ctsio);
9969 	return (CTL_RETVAL_COMPLETE);
9970 }
9971 
9972 static int
9973 ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
9974 {
9975 	struct ctl_lun *lun = CTL_LUN(ctsio);
9976 	struct scsi_vpd_logical_block_prov *lbp_ptr;
9977 	const char *value;
9978 
9979 	ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
9980 	lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
9981 	ctsio->kern_sg_entries = 0;
9982 	ctsio->kern_rel_offset = 0;
9983 	ctsio->kern_data_len = min(sizeof(*lbp_ptr), alloc_len);
9984 	ctsio->kern_total_len = ctsio->kern_data_len;
9985 
9986 	/*
9987 	 * The control device is always connected.  The disk device, on the
9988 	 * other hand, may not be online all the time.  Need to change this
9989 	 * to figure out whether the disk device is actually online or not.
9990 	 */
9991 	if (lun != NULL)
9992 		lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9993 				  lun->be_lun->lun_type;
9994 	else
9995 		lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9996 
9997 	lbp_ptr->page_code = SVPD_LBP;
9998 	scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
9999 	lbp_ptr->threshold_exponent = CTL_LBP_EXPONENT;
10000 	if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10001 		lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
10002 		    SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
10003 		value = dnvlist_get_string(lun->be_lun->options,
10004 		    "provisioning_type", NULL);
10005 		if (value != NULL) {
10006 			if (strcmp(value, "resource") == 0)
10007 				lbp_ptr->prov_type = SVPD_LBP_RESOURCE;
10008 			else if (strcmp(value, "thin") == 0)
10009 				lbp_ptr->prov_type = SVPD_LBP_THIN;
10010 		} else
10011 			lbp_ptr->prov_type = SVPD_LBP_THIN;
10012 	}
10013 
10014 	ctl_set_success(ctsio);
10015 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10016 	ctsio->be_move_done = ctl_config_move_done;
10017 	ctl_datamove((union ctl_io *)ctsio);
10018 	return (CTL_RETVAL_COMPLETE);
10019 }
10020 
10021 /*
10022  * INQUIRY with the EVPD bit set.
10023  */
10024 static int
10025 ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
10026 {
10027 	struct ctl_lun *lun = CTL_LUN(ctsio);
10028 	struct scsi_inquiry *cdb;
10029 	int alloc_len, retval;
10030 
10031 	cdb = (struct scsi_inquiry *)ctsio->cdb;
10032 	alloc_len = scsi_2btoul(cdb->length);
10033 
10034 	switch (cdb->page_code) {
10035 	case SVPD_SUPPORTED_PAGES:
10036 		retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
10037 		break;
10038 	case SVPD_UNIT_SERIAL_NUMBER:
10039 		retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
10040 		break;
10041 	case SVPD_DEVICE_ID:
10042 		retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
10043 		break;
10044 	case SVPD_EXTENDED_INQUIRY_DATA:
10045 		retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
10046 		break;
10047 	case SVPD_MODE_PAGE_POLICY:
10048 		retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
10049 		break;
10050 	case SVPD_SCSI_PORTS:
10051 		retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10052 		break;
10053 	case SVPD_SCSI_TPC:
10054 		retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
10055 		break;
10056 	case SVPD_SCSI_SFS:
10057 		retval = ctl_inquiry_evpd_sfs(ctsio, alloc_len);
10058 		break;
10059 	case SVPD_BLOCK_LIMITS:
10060 		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10061 			goto err;
10062 		retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10063 		break;
10064 	case SVPD_BDC:
10065 		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10066 			goto err;
10067 		retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
10068 		break;
10069 	case SVPD_LBP:
10070 		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10071 			goto err;
10072 		retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10073 		break;
10074 	default:
10075 err:
10076 		ctl_set_invalid_field(ctsio,
10077 				      /*sks_valid*/ 1,
10078 				      /*command*/ 1,
10079 				      /*field*/ 2,
10080 				      /*bit_valid*/ 0,
10081 				      /*bit*/ 0);
10082 		ctl_done((union ctl_io *)ctsio);
10083 		retval = CTL_RETVAL_COMPLETE;
10084 		break;
10085 	}
10086 
10087 	return (retval);
10088 }
10089 
10090 /*
10091  * Standard INQUIRY data.
10092  */
10093 static int
10094 ctl_inquiry_std(struct ctl_scsiio *ctsio)
10095 {
10096 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
10097 	struct ctl_port *port = CTL_PORT(ctsio);
10098 	struct ctl_lun *lun = CTL_LUN(ctsio);
10099 	struct scsi_inquiry_data *inq_ptr;
10100 	struct scsi_inquiry *cdb;
10101 	const char *val;
10102 	uint32_t alloc_len, data_len;
10103 	ctl_port_type port_type;
10104 
10105 	port_type = port->port_type;
10106 	if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10107 		port_type = CTL_PORT_SCSI;
10108 
10109 	cdb = (struct scsi_inquiry *)ctsio->cdb;
10110 	alloc_len = scsi_2btoul(cdb->length);
10111 
10112 	/*
10113 	 * We malloc the full inquiry data size here and fill it
10114 	 * in.  If the user only asks for less, we'll give him
10115 	 * that much.
10116 	 */
10117 	data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
10118 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10119 	inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10120 	ctsio->kern_sg_entries = 0;
10121 	ctsio->kern_rel_offset = 0;
10122 	ctsio->kern_data_len = min(data_len, alloc_len);
10123 	ctsio->kern_total_len = ctsio->kern_data_len;
10124 
10125 	if (lun != NULL) {
10126 		if ((lun->flags & CTL_LUN_PRIMARY_SC) ||
10127 		    softc->ha_link >= CTL_HA_LINK_UNKNOWN) {
10128 			inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10129 			    lun->be_lun->lun_type;
10130 		} else {
10131 			inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) |
10132 			    lun->be_lun->lun_type;
10133 		}
10134 		if (lun->flags & CTL_LUN_REMOVABLE)
10135 			inq_ptr->dev_qual2 |= SID_RMB;
10136 	} else
10137 		inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10138 
10139 	/* RMB in byte 2 is 0 */
10140 	inq_ptr->version = SCSI_REV_SPC5;
10141 
10142 	/*
10143 	 * According to SAM-3, even if a device only supports a single
10144 	 * level of LUN addressing, it should still set the HISUP bit:
10145 	 *
10146 	 * 4.9.1 Logical unit numbers overview
10147 	 *
10148 	 * All logical unit number formats described in this standard are
10149 	 * hierarchical in structure even when only a single level in that
10150 	 * hierarchy is used. The HISUP bit shall be set to one in the
10151 	 * standard INQUIRY data (see SPC-2) when any logical unit number
10152 	 * format described in this standard is used.  Non-hierarchical
10153 	 * formats are outside the scope of this standard.
10154 	 *
10155 	 * Therefore we set the HiSup bit here.
10156 	 *
10157 	 * The response format is 2, per SPC-3.
10158 	 */
10159 	inq_ptr->response_format = SID_HiSup | 2;
10160 
10161 	inq_ptr->additional_length = data_len -
10162 	    (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10163 	CTL_DEBUG_PRINT(("additional_length = %d\n",
10164 			 inq_ptr->additional_length));
10165 
10166 	inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10167 	if (port_type == CTL_PORT_SCSI)
10168 		inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10169 	inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10170 	inq_ptr->flags = SID_CmdQue;
10171 	if (port_type == CTL_PORT_SCSI)
10172 		inq_ptr->flags |= SID_WBus16 | SID_Sync;
10173 
10174 	/*
10175 	 * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10176 	 * We have 8 bytes for the vendor name, and 16 bytes for the device
10177 	 * name and 4 bytes for the revision.
10178 	 */
10179 	if (lun == NULL || (val = dnvlist_get_string(lun->be_lun->options,
10180 	    "vendor", NULL)) == NULL) {
10181 		strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10182 	} else {
10183 		memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10184 		strncpy(inq_ptr->vendor, val,
10185 		    min(sizeof(inq_ptr->vendor), strlen(val)));
10186 	}
10187 	if (lun == NULL) {
10188 		strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10189 		    sizeof(inq_ptr->product));
10190 	} else if ((val = dnvlist_get_string(lun->be_lun->options, "product",
10191 	    NULL)) == NULL) {
10192 		switch (lun->be_lun->lun_type) {
10193 		case T_DIRECT:
10194 			strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10195 			    sizeof(inq_ptr->product));
10196 			break;
10197 		case T_PROCESSOR:
10198 			strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10199 			    sizeof(inq_ptr->product));
10200 			break;
10201 		case T_CDROM:
10202 			strncpy(inq_ptr->product, CTL_CDROM_PRODUCT,
10203 			    sizeof(inq_ptr->product));
10204 			break;
10205 		default:
10206 			strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10207 			    sizeof(inq_ptr->product));
10208 			break;
10209 		}
10210 	} else {
10211 		memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10212 		strncpy(inq_ptr->product, val,
10213 		    min(sizeof(inq_ptr->product), strlen(val)));
10214 	}
10215 
10216 	/*
10217 	 * XXX make this a macro somewhere so it automatically gets
10218 	 * incremented when we make changes.
10219 	 */
10220 	if (lun == NULL || (val = dnvlist_get_string(lun->be_lun->options,
10221 	    "revision", NULL)) == NULL) {
10222 		strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10223 	} else {
10224 		memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10225 		strncpy(inq_ptr->revision, val,
10226 		    min(sizeof(inq_ptr->revision), strlen(val)));
10227 	}
10228 
10229 	/*
10230 	 * For parallel SCSI, we support double transition and single
10231 	 * transition clocking.  We also support QAS (Quick Arbitration
10232 	 * and Selection) and Information Unit transfers on both the
10233 	 * control and array devices.
10234 	 */
10235 	if (port_type == CTL_PORT_SCSI)
10236 		inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10237 				    SID_SPI_IUS;
10238 
10239 	/* SAM-6 (no version claimed) */
10240 	scsi_ulto2b(0x00C0, inq_ptr->version1);
10241 	/* SPC-5 (no version claimed) */
10242 	scsi_ulto2b(0x05C0, inq_ptr->version2);
10243 	if (port_type == CTL_PORT_FC) {
10244 		/* FCP-2 ANSI INCITS.350:2003 */
10245 		scsi_ulto2b(0x0917, inq_ptr->version3);
10246 	} else if (port_type == CTL_PORT_SCSI) {
10247 		/* SPI-4 ANSI INCITS.362:200x */
10248 		scsi_ulto2b(0x0B56, inq_ptr->version3);
10249 	} else if (port_type == CTL_PORT_ISCSI) {
10250 		/* iSCSI (no version claimed) */
10251 		scsi_ulto2b(0x0960, inq_ptr->version3);
10252 	} else if (port_type == CTL_PORT_SAS) {
10253 		/* SAS (no version claimed) */
10254 		scsi_ulto2b(0x0BE0, inq_ptr->version3);
10255 	} else if (port_type == CTL_PORT_UMASS) {
10256 		/* USB Mass Storage Class Bulk-Only Transport, Revision 1.0 */
10257 		scsi_ulto2b(0x1730, inq_ptr->version3);
10258 	}
10259 
10260 	if (lun == NULL) {
10261 		/* SBC-4 (no version claimed) */
10262 		scsi_ulto2b(0x0600, inq_ptr->version4);
10263 	} else {
10264 		switch (lun->be_lun->lun_type) {
10265 		case T_DIRECT:
10266 			/* SBC-4 (no version claimed) */
10267 			scsi_ulto2b(0x0600, inq_ptr->version4);
10268 			break;
10269 		case T_PROCESSOR:
10270 			break;
10271 		case T_CDROM:
10272 			/* MMC-6 (no version claimed) */
10273 			scsi_ulto2b(0x04E0, inq_ptr->version4);
10274 			break;
10275 		default:
10276 			break;
10277 		}
10278 	}
10279 
10280 	ctl_set_success(ctsio);
10281 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10282 	ctsio->be_move_done = ctl_config_move_done;
10283 	ctl_datamove((union ctl_io *)ctsio);
10284 	return (CTL_RETVAL_COMPLETE);
10285 }
10286 
10287 int
10288 ctl_inquiry(struct ctl_scsiio *ctsio)
10289 {
10290 	struct scsi_inquiry *cdb;
10291 	int retval;
10292 
10293 	CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10294 
10295 	cdb = (struct scsi_inquiry *)ctsio->cdb;
10296 	if (cdb->byte2 & SI_EVPD)
10297 		retval = ctl_inquiry_evpd(ctsio);
10298 	else if (cdb->page_code == 0)
10299 		retval = ctl_inquiry_std(ctsio);
10300 	else {
10301 		ctl_set_invalid_field(ctsio,
10302 				      /*sks_valid*/ 1,
10303 				      /*command*/ 1,
10304 				      /*field*/ 2,
10305 				      /*bit_valid*/ 0,
10306 				      /*bit*/ 0);
10307 		ctl_done((union ctl_io *)ctsio);
10308 		return (CTL_RETVAL_COMPLETE);
10309 	}
10310 
10311 	return (retval);
10312 }
10313 
10314 int
10315 ctl_get_config(struct ctl_scsiio *ctsio)
10316 {
10317 	struct ctl_lun *lun = CTL_LUN(ctsio);
10318 	struct scsi_get_config_header *hdr;
10319 	struct scsi_get_config_feature *feature;
10320 	struct scsi_get_config *cdb;
10321 	uint32_t alloc_len, data_len;
10322 	int rt, starting;
10323 
10324 	cdb = (struct scsi_get_config *)ctsio->cdb;
10325 	rt = (cdb->rt & SGC_RT_MASK);
10326 	starting = scsi_2btoul(cdb->starting_feature);
10327 	alloc_len = scsi_2btoul(cdb->length);
10328 
10329 	data_len = sizeof(struct scsi_get_config_header) +
10330 	    sizeof(struct scsi_get_config_feature) + 8 +
10331 	    sizeof(struct scsi_get_config_feature) + 8 +
10332 	    sizeof(struct scsi_get_config_feature) + 4 +
10333 	    sizeof(struct scsi_get_config_feature) + 4 +
10334 	    sizeof(struct scsi_get_config_feature) + 8 +
10335 	    sizeof(struct scsi_get_config_feature) +
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 	    sizeof(struct scsi_get_config_feature) + 4 +
10341 	    sizeof(struct scsi_get_config_feature) + 4;
10342 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10343 	ctsio->kern_sg_entries = 0;
10344 	ctsio->kern_rel_offset = 0;
10345 
10346 	hdr = (struct scsi_get_config_header *)ctsio->kern_data_ptr;
10347 	if (lun->flags & CTL_LUN_NO_MEDIA)
10348 		scsi_ulto2b(0x0000, hdr->current_profile);
10349 	else
10350 		scsi_ulto2b(0x0010, hdr->current_profile);
10351 	feature = (struct scsi_get_config_feature *)(hdr + 1);
10352 
10353 	if (starting > 0x003b)
10354 		goto done;
10355 	if (starting > 0x003a)
10356 		goto f3b;
10357 	if (starting > 0x002b)
10358 		goto f3a;
10359 	if (starting > 0x002a)
10360 		goto f2b;
10361 	if (starting > 0x001f)
10362 		goto f2a;
10363 	if (starting > 0x001e)
10364 		goto f1f;
10365 	if (starting > 0x001d)
10366 		goto f1e;
10367 	if (starting > 0x0010)
10368 		goto f1d;
10369 	if (starting > 0x0003)
10370 		goto f10;
10371 	if (starting > 0x0002)
10372 		goto f3;
10373 	if (starting > 0x0001)
10374 		goto f2;
10375 	if (starting > 0x0000)
10376 		goto f1;
10377 
10378 	/* Profile List */
10379 	scsi_ulto2b(0x0000, feature->feature_code);
10380 	feature->flags = SGC_F_PERSISTENT | SGC_F_CURRENT;
10381 	feature->add_length = 8;
10382 	scsi_ulto2b(0x0008, &feature->feature_data[0]);	/* CD-ROM */
10383 	feature->feature_data[2] = 0x00;
10384 	scsi_ulto2b(0x0010, &feature->feature_data[4]);	/* DVD-ROM */
10385 	feature->feature_data[6] = 0x01;
10386 	feature = (struct scsi_get_config_feature *)
10387 	    &feature->feature_data[feature->add_length];
10388 
10389 f1:	/* Core */
10390 	scsi_ulto2b(0x0001, feature->feature_code);
10391 	feature->flags = 0x08 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10392 	feature->add_length = 8;
10393 	scsi_ulto4b(0x00000000, &feature->feature_data[0]);
10394 	feature->feature_data[4] = 0x03;
10395 	feature = (struct scsi_get_config_feature *)
10396 	    &feature->feature_data[feature->add_length];
10397 
10398 f2:	/* Morphing */
10399 	scsi_ulto2b(0x0002, feature->feature_code);
10400 	feature->flags = 0x04 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10401 	feature->add_length = 4;
10402 	feature->feature_data[0] = 0x02;
10403 	feature = (struct scsi_get_config_feature *)
10404 	    &feature->feature_data[feature->add_length];
10405 
10406 f3:	/* Removable Medium */
10407 	scsi_ulto2b(0x0003, feature->feature_code);
10408 	feature->flags = 0x04 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10409 	feature->add_length = 4;
10410 	feature->feature_data[0] = 0x39;
10411 	feature = (struct scsi_get_config_feature *)
10412 	    &feature->feature_data[feature->add_length];
10413 
10414 	if (rt == SGC_RT_CURRENT && (lun->flags & CTL_LUN_NO_MEDIA))
10415 		goto done;
10416 
10417 f10:	/* Random Read */
10418 	scsi_ulto2b(0x0010, feature->feature_code);
10419 	feature->flags = 0x00;
10420 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10421 		feature->flags |= SGC_F_CURRENT;
10422 	feature->add_length = 8;
10423 	scsi_ulto4b(lun->be_lun->blocksize, &feature->feature_data[0]);
10424 	scsi_ulto2b(1, &feature->feature_data[4]);
10425 	feature->feature_data[6] = 0x00;
10426 	feature = (struct scsi_get_config_feature *)
10427 	    &feature->feature_data[feature->add_length];
10428 
10429 f1d:	/* Multi-Read */
10430 	scsi_ulto2b(0x001D, feature->feature_code);
10431 	feature->flags = 0x00;
10432 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10433 		feature->flags |= SGC_F_CURRENT;
10434 	feature->add_length = 0;
10435 	feature = (struct scsi_get_config_feature *)
10436 	    &feature->feature_data[feature->add_length];
10437 
10438 f1e:	/* CD Read */
10439 	scsi_ulto2b(0x001E, feature->feature_code);
10440 	feature->flags = 0x00;
10441 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10442 		feature->flags |= SGC_F_CURRENT;
10443 	feature->add_length = 4;
10444 	feature->feature_data[0] = 0x00;
10445 	feature = (struct scsi_get_config_feature *)
10446 	    &feature->feature_data[feature->add_length];
10447 
10448 f1f:	/* DVD Read */
10449 	scsi_ulto2b(0x001F, feature->feature_code);
10450 	feature->flags = 0x08;
10451 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10452 		feature->flags |= SGC_F_CURRENT;
10453 	feature->add_length = 4;
10454 	feature->feature_data[0] = 0x01;
10455 	feature->feature_data[2] = 0x03;
10456 	feature = (struct scsi_get_config_feature *)
10457 	    &feature->feature_data[feature->add_length];
10458 
10459 f2a:	/* DVD+RW */
10460 	scsi_ulto2b(0x002A, feature->feature_code);
10461 	feature->flags = 0x04;
10462 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10463 		feature->flags |= SGC_F_CURRENT;
10464 	feature->add_length = 4;
10465 	feature->feature_data[0] = 0x00;
10466 	feature->feature_data[1] = 0x00;
10467 	feature = (struct scsi_get_config_feature *)
10468 	    &feature->feature_data[feature->add_length];
10469 
10470 f2b:	/* DVD+R */
10471 	scsi_ulto2b(0x002B, feature->feature_code);
10472 	feature->flags = 0x00;
10473 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10474 		feature->flags |= SGC_F_CURRENT;
10475 	feature->add_length = 4;
10476 	feature->feature_data[0] = 0x00;
10477 	feature = (struct scsi_get_config_feature *)
10478 	    &feature->feature_data[feature->add_length];
10479 
10480 f3a:	/* DVD+RW Dual Layer */
10481 	scsi_ulto2b(0x003A, feature->feature_code);
10482 	feature->flags = 0x00;
10483 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10484 		feature->flags |= SGC_F_CURRENT;
10485 	feature->add_length = 4;
10486 	feature->feature_data[0] = 0x00;
10487 	feature->feature_data[1] = 0x00;
10488 	feature = (struct scsi_get_config_feature *)
10489 	    &feature->feature_data[feature->add_length];
10490 
10491 f3b:	/* DVD+R Dual Layer */
10492 	scsi_ulto2b(0x003B, feature->feature_code);
10493 	feature->flags = 0x00;
10494 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10495 		feature->flags |= SGC_F_CURRENT;
10496 	feature->add_length = 4;
10497 	feature->feature_data[0] = 0x00;
10498 	feature = (struct scsi_get_config_feature *)
10499 	    &feature->feature_data[feature->add_length];
10500 
10501 done:
10502 	data_len = (uint8_t *)feature - (uint8_t *)hdr;
10503 	if (rt == SGC_RT_SPECIFIC && data_len > 4) {
10504 		feature = (struct scsi_get_config_feature *)(hdr + 1);
10505 		if (scsi_2btoul(feature->feature_code) == starting)
10506 			feature = (struct scsi_get_config_feature *)
10507 			    &feature->feature_data[feature->add_length];
10508 		data_len = (uint8_t *)feature - (uint8_t *)hdr;
10509 	}
10510 	scsi_ulto4b(data_len - 4, hdr->data_length);
10511 	ctsio->kern_data_len = min(data_len, alloc_len);
10512 	ctsio->kern_total_len = ctsio->kern_data_len;
10513 
10514 	ctl_set_success(ctsio);
10515 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10516 	ctsio->be_move_done = ctl_config_move_done;
10517 	ctl_datamove((union ctl_io *)ctsio);
10518 	return (CTL_RETVAL_COMPLETE);
10519 }
10520 
10521 int
10522 ctl_get_event_status(struct ctl_scsiio *ctsio)
10523 {
10524 	struct scsi_get_event_status_header *hdr;
10525 	struct scsi_get_event_status *cdb;
10526 	uint32_t alloc_len, data_len;
10527 
10528 	cdb = (struct scsi_get_event_status *)ctsio->cdb;
10529 	if ((cdb->byte2 & SGESN_POLLED) == 0) {
10530 		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1, /*command*/ 1,
10531 		    /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
10532 		ctl_done((union ctl_io *)ctsio);
10533 		return (CTL_RETVAL_COMPLETE);
10534 	}
10535 	alloc_len = scsi_2btoul(cdb->length);
10536 
10537 	data_len = sizeof(struct scsi_get_event_status_header);
10538 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10539 	ctsio->kern_sg_entries = 0;
10540 	ctsio->kern_rel_offset = 0;
10541 	ctsio->kern_data_len = min(data_len, alloc_len);
10542 	ctsio->kern_total_len = ctsio->kern_data_len;
10543 
10544 	hdr = (struct scsi_get_event_status_header *)ctsio->kern_data_ptr;
10545 	scsi_ulto2b(0, hdr->descr_length);
10546 	hdr->nea_class = SGESN_NEA;
10547 	hdr->supported_class = 0;
10548 
10549 	ctl_set_success(ctsio);
10550 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10551 	ctsio->be_move_done = ctl_config_move_done;
10552 	ctl_datamove((union ctl_io *)ctsio);
10553 	return (CTL_RETVAL_COMPLETE);
10554 }
10555 
10556 int
10557 ctl_mechanism_status(struct ctl_scsiio *ctsio)
10558 {
10559 	struct scsi_mechanism_status_header *hdr;
10560 	struct scsi_mechanism_status *cdb;
10561 	uint32_t alloc_len, data_len;
10562 
10563 	cdb = (struct scsi_mechanism_status *)ctsio->cdb;
10564 	alloc_len = scsi_2btoul(cdb->length);
10565 
10566 	data_len = sizeof(struct scsi_mechanism_status_header);
10567 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10568 	ctsio->kern_sg_entries = 0;
10569 	ctsio->kern_rel_offset = 0;
10570 	ctsio->kern_data_len = min(data_len, alloc_len);
10571 	ctsio->kern_total_len = ctsio->kern_data_len;
10572 
10573 	hdr = (struct scsi_mechanism_status_header *)ctsio->kern_data_ptr;
10574 	hdr->state1 = 0x00;
10575 	hdr->state2 = 0xe0;
10576 	scsi_ulto3b(0, hdr->lba);
10577 	hdr->slots_num = 0;
10578 	scsi_ulto2b(0, hdr->slots_length);
10579 
10580 	ctl_set_success(ctsio);
10581 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10582 	ctsio->be_move_done = ctl_config_move_done;
10583 	ctl_datamove((union ctl_io *)ctsio);
10584 	return (CTL_RETVAL_COMPLETE);
10585 }
10586 
10587 static void
10588 ctl_ultomsf(uint32_t lba, uint8_t *buf)
10589 {
10590 
10591 	lba += 150;
10592 	buf[0] = 0;
10593 	buf[1] = bin2bcd((lba / 75) / 60);
10594 	buf[2] = bin2bcd((lba / 75) % 60);
10595 	buf[3] = bin2bcd(lba % 75);
10596 }
10597 
10598 int
10599 ctl_read_toc(struct ctl_scsiio *ctsio)
10600 {
10601 	struct ctl_lun *lun = CTL_LUN(ctsio);
10602 	struct scsi_read_toc_hdr *hdr;
10603 	struct scsi_read_toc_type01_descr *descr;
10604 	struct scsi_read_toc *cdb;
10605 	uint32_t alloc_len, data_len;
10606 	int format, msf;
10607 
10608 	cdb = (struct scsi_read_toc *)ctsio->cdb;
10609 	msf = (cdb->byte2 & CD_MSF) != 0;
10610 	format = cdb->format;
10611 	alloc_len = scsi_2btoul(cdb->data_len);
10612 
10613 	data_len = sizeof(struct scsi_read_toc_hdr);
10614 	if (format == 0)
10615 		data_len += 2 * sizeof(struct scsi_read_toc_type01_descr);
10616 	else
10617 		data_len += sizeof(struct scsi_read_toc_type01_descr);
10618 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10619 	ctsio->kern_sg_entries = 0;
10620 	ctsio->kern_rel_offset = 0;
10621 	ctsio->kern_data_len = min(data_len, alloc_len);
10622 	ctsio->kern_total_len = ctsio->kern_data_len;
10623 
10624 	hdr = (struct scsi_read_toc_hdr *)ctsio->kern_data_ptr;
10625 	if (format == 0) {
10626 		scsi_ulto2b(0x12, hdr->data_length);
10627 		hdr->first = 1;
10628 		hdr->last = 1;
10629 		descr = (struct scsi_read_toc_type01_descr *)(hdr + 1);
10630 		descr->addr_ctl = 0x14;
10631 		descr->track_number = 1;
10632 		if (msf)
10633 			ctl_ultomsf(0, descr->track_start);
10634 		else
10635 			scsi_ulto4b(0, descr->track_start);
10636 		descr++;
10637 		descr->addr_ctl = 0x14;
10638 		descr->track_number = 0xaa;
10639 		if (msf)
10640 			ctl_ultomsf(lun->be_lun->maxlba+1, descr->track_start);
10641 		else
10642 			scsi_ulto4b(lun->be_lun->maxlba+1, descr->track_start);
10643 	} else {
10644 		scsi_ulto2b(0x0a, hdr->data_length);
10645 		hdr->first = 1;
10646 		hdr->last = 1;
10647 		descr = (struct scsi_read_toc_type01_descr *)(hdr + 1);
10648 		descr->addr_ctl = 0x14;
10649 		descr->track_number = 1;
10650 		if (msf)
10651 			ctl_ultomsf(0, descr->track_start);
10652 		else
10653 			scsi_ulto4b(0, descr->track_start);
10654 	}
10655 
10656 	ctl_set_success(ctsio);
10657 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10658 	ctsio->be_move_done = ctl_config_move_done;
10659 	ctl_datamove((union ctl_io *)ctsio);
10660 	return (CTL_RETVAL_COMPLETE);
10661 }
10662 
10663 /*
10664  * For known CDB types, parse the LBA and length.
10665  */
10666 static int
10667 ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10668 {
10669 	if (io->io_hdr.io_type != CTL_IO_SCSI)
10670 		return (1);
10671 
10672 	switch (io->scsiio.cdb[0]) {
10673 	case COMPARE_AND_WRITE: {
10674 		struct scsi_compare_and_write *cdb;
10675 
10676 		cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10677 
10678 		*lba = scsi_8btou64(cdb->addr);
10679 		*len = cdb->length;
10680 		break;
10681 	}
10682 	case READ_6:
10683 	case WRITE_6: {
10684 		struct scsi_rw_6 *cdb;
10685 
10686 		cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10687 
10688 		*lba = scsi_3btoul(cdb->addr);
10689 		/* only 5 bits are valid in the most significant address byte */
10690 		*lba &= 0x1fffff;
10691 		*len = cdb->length;
10692 		break;
10693 	}
10694 	case READ_10:
10695 	case WRITE_10: {
10696 		struct scsi_rw_10 *cdb;
10697 
10698 		cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10699 
10700 		*lba = scsi_4btoul(cdb->addr);
10701 		*len = scsi_2btoul(cdb->length);
10702 		break;
10703 	}
10704 	case WRITE_VERIFY_10: {
10705 		struct scsi_write_verify_10 *cdb;
10706 
10707 		cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10708 
10709 		*lba = scsi_4btoul(cdb->addr);
10710 		*len = scsi_2btoul(cdb->length);
10711 		break;
10712 	}
10713 	case READ_12:
10714 	case WRITE_12: {
10715 		struct scsi_rw_12 *cdb;
10716 
10717 		cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10718 
10719 		*lba = scsi_4btoul(cdb->addr);
10720 		*len = scsi_4btoul(cdb->length);
10721 		break;
10722 	}
10723 	case WRITE_VERIFY_12: {
10724 		struct scsi_write_verify_12 *cdb;
10725 
10726 		cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10727 
10728 		*lba = scsi_4btoul(cdb->addr);
10729 		*len = scsi_4btoul(cdb->length);
10730 		break;
10731 	}
10732 	case READ_16:
10733 	case WRITE_16: {
10734 		struct scsi_rw_16 *cdb;
10735 
10736 		cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10737 
10738 		*lba = scsi_8btou64(cdb->addr);
10739 		*len = scsi_4btoul(cdb->length);
10740 		break;
10741 	}
10742 	case WRITE_ATOMIC_16: {
10743 		struct scsi_write_atomic_16 *cdb;
10744 
10745 		cdb = (struct scsi_write_atomic_16 *)io->scsiio.cdb;
10746 
10747 		*lba = scsi_8btou64(cdb->addr);
10748 		*len = scsi_2btoul(cdb->length);
10749 		break;
10750 	}
10751 	case WRITE_VERIFY_16: {
10752 		struct scsi_write_verify_16 *cdb;
10753 
10754 		cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10755 
10756 		*lba = scsi_8btou64(cdb->addr);
10757 		*len = scsi_4btoul(cdb->length);
10758 		break;
10759 	}
10760 	case WRITE_SAME_10: {
10761 		struct scsi_write_same_10 *cdb;
10762 
10763 		cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10764 
10765 		*lba = scsi_4btoul(cdb->addr);
10766 		*len = scsi_2btoul(cdb->length);
10767 		break;
10768 	}
10769 	case WRITE_SAME_16: {
10770 		struct scsi_write_same_16 *cdb;
10771 
10772 		cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10773 
10774 		*lba = scsi_8btou64(cdb->addr);
10775 		*len = scsi_4btoul(cdb->length);
10776 		break;
10777 	}
10778 	case VERIFY_10: {
10779 		struct scsi_verify_10 *cdb;
10780 
10781 		cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10782 
10783 		*lba = scsi_4btoul(cdb->addr);
10784 		*len = scsi_2btoul(cdb->length);
10785 		break;
10786 	}
10787 	case VERIFY_12: {
10788 		struct scsi_verify_12 *cdb;
10789 
10790 		cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10791 
10792 		*lba = scsi_4btoul(cdb->addr);
10793 		*len = scsi_4btoul(cdb->length);
10794 		break;
10795 	}
10796 	case VERIFY_16: {
10797 		struct scsi_verify_16 *cdb;
10798 
10799 		cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10800 
10801 		*lba = scsi_8btou64(cdb->addr);
10802 		*len = scsi_4btoul(cdb->length);
10803 		break;
10804 	}
10805 	case UNMAP: {
10806 		*lba = 0;
10807 		*len = UINT64_MAX;
10808 		break;
10809 	}
10810 	case SERVICE_ACTION_IN: {	/* GET LBA STATUS */
10811 		struct scsi_get_lba_status *cdb;
10812 
10813 		cdb = (struct scsi_get_lba_status *)io->scsiio.cdb;
10814 		*lba = scsi_8btou64(cdb->addr);
10815 		*len = UINT32_MAX;
10816 		break;
10817 	}
10818 	default:
10819 		return (1);
10820 		break; /* NOTREACHED */
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 	/* If not UNMAP -- go other way. */
10850 	if (io->io_hdr.io_type != CTL_IO_SCSI ||
10851 	    io->scsiio.cdb[0] != UNMAP)
10852 		return (CTL_ACTION_ERROR);
10853 
10854 	/* If UNMAP without data -- block and wait for data. */
10855 	ptrlen = (struct ctl_ptr_len_flags *)
10856 	    &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10857 	if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
10858 	    ptrlen->ptr == NULL)
10859 		return (CTL_ACTION_BLOCK);
10860 
10861 	/* UNMAP with data -- check for collision. */
10862 	buf = (struct scsi_unmap_desc *)ptrlen->ptr;
10863 	end = buf + ptrlen->len / sizeof(*buf);
10864 	for (range = buf; range < end; range++) {
10865 		lba = scsi_8btou64(range->lba);
10866 		len = scsi_4btoul(range->length);
10867 		if ((lba < lba2 + len2) && (lba + len > lba2))
10868 			return (CTL_ACTION_BLOCK);
10869 	}
10870 	return (CTL_ACTION_PASS);
10871 }
10872 
10873 static ctl_action
10874 ctl_extent_check(union ctl_io *io1, union ctl_io *io2, bool seq)
10875 {
10876 	uint64_t lba1, lba2;
10877 	uint64_t len1, len2;
10878 	int retval;
10879 
10880 	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10881 		return (CTL_ACTION_ERROR);
10882 
10883 	retval = ctl_extent_check_unmap(io1, lba2, len2);
10884 	if (retval != CTL_ACTION_ERROR)
10885 		return (retval);
10886 
10887 	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10888 		return (CTL_ACTION_ERROR);
10889 
10890 	if (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE)
10891 		seq = FALSE;
10892 	return (ctl_extent_check_lba(lba1, len1, lba2, len2, seq));
10893 }
10894 
10895 static ctl_action
10896 ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2)
10897 {
10898 	uint64_t lba1, lba2;
10899 	uint64_t len1, len2;
10900 
10901 	if (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE)
10902 		return (CTL_ACTION_PASS);
10903 	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10904 		return (CTL_ACTION_ERROR);
10905 	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10906 		return (CTL_ACTION_ERROR);
10907 
10908 	if (lba1 + len1 == lba2)
10909 		return (CTL_ACTION_BLOCK);
10910 	return (CTL_ACTION_PASS);
10911 }
10912 
10913 static ctl_action
10914 ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
10915     union ctl_io *ooa_io)
10916 {
10917 	const struct ctl_cmd_entry *pending_entry, *ooa_entry;
10918 	const ctl_serialize_action *serialize_row;
10919 
10920 	/*
10921 	 * Aborted commands are not going to be executed and may even
10922 	 * not report completion, so we don't care about their order.
10923 	 * Let them complete ASAP to clean the OOA queue.
10924 	 */
10925 	if (pending_io->io_hdr.flags & CTL_FLAG_ABORT)
10926 		return (CTL_ACTION_SKIP);
10927 
10928 	/*
10929 	 * The initiator attempted multiple untagged commands at the same
10930 	 * time.  Can't do that.
10931 	 */
10932 	if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10933 	 && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10934 	 && ((pending_io->io_hdr.nexus.targ_port ==
10935 	      ooa_io->io_hdr.nexus.targ_port)
10936 	  && (pending_io->io_hdr.nexus.initid ==
10937 	      ooa_io->io_hdr.nexus.initid))
10938 	 && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
10939 	      CTL_FLAG_STATUS_SENT)) == 0))
10940 		return (CTL_ACTION_OVERLAP);
10941 
10942 	/*
10943 	 * The initiator attempted to send multiple tagged commands with
10944 	 * the same ID.  (It's fine if different initiators have the same
10945 	 * tag ID.)
10946 	 *
10947 	 * Even if all of those conditions are true, we don't kill the I/O
10948 	 * if the command ahead of us has been aborted.  We won't end up
10949 	 * sending it to the FETD, and it's perfectly legal to resend a
10950 	 * command with the same tag number as long as the previous
10951 	 * instance of this tag number has been aborted somehow.
10952 	 */
10953 	if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10954 	 && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10955 	 && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
10956 	 && ((pending_io->io_hdr.nexus.targ_port ==
10957 	      ooa_io->io_hdr.nexus.targ_port)
10958 	  && (pending_io->io_hdr.nexus.initid ==
10959 	      ooa_io->io_hdr.nexus.initid))
10960 	 && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
10961 	      CTL_FLAG_STATUS_SENT)) == 0))
10962 		return (CTL_ACTION_OVERLAP_TAG);
10963 
10964 	/*
10965 	 * If we get a head of queue tag, SAM-3 says that we should
10966 	 * immediately execute it.
10967 	 *
10968 	 * What happens if this command would normally block for some other
10969 	 * reason?  e.g. a request sense with a head of queue tag
10970 	 * immediately after a write.  Normally that would block, but this
10971 	 * will result in its getting executed immediately...
10972 	 *
10973 	 * We currently return "pass" instead of "skip", so we'll end up
10974 	 * going through the rest of the queue to check for overlapped tags.
10975 	 *
10976 	 * XXX KDM check for other types of blockage first??
10977 	 */
10978 	if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10979 		return (CTL_ACTION_PASS);
10980 
10981 	/*
10982 	 * Ordered tags have to block until all items ahead of them
10983 	 * have completed.  If we get called with an ordered tag, we always
10984 	 * block, if something else is ahead of us in the queue.
10985 	 */
10986 	if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
10987 		return (CTL_ACTION_BLOCK);
10988 
10989 	/*
10990 	 * Simple tags get blocked until all head of queue and ordered tags
10991 	 * ahead of them have completed.  I'm lumping untagged commands in
10992 	 * with simple tags here.  XXX KDM is that the right thing to do?
10993 	 */
10994 	if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10995 	  || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
10996 	 && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10997 	  || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
10998 		return (CTL_ACTION_BLOCK);
10999 
11000 	pending_entry = ctl_get_cmd_entry(&pending_io->scsiio, NULL);
11001 	KASSERT(pending_entry->seridx < CTL_SERIDX_COUNT,
11002 	    ("%s: Invalid seridx %d for pending CDB %02x %02x @ %p",
11003 	     __func__, pending_entry->seridx, pending_io->scsiio.cdb[0],
11004 	     pending_io->scsiio.cdb[1], pending_io));
11005 	ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio, NULL);
11006 	if (ooa_entry->seridx == CTL_SERIDX_INVLD)
11007 		return (CTL_ACTION_PASS); /* Unsupported command in OOA queue */
11008 	KASSERT(ooa_entry->seridx < CTL_SERIDX_COUNT,
11009 	    ("%s: Invalid seridx %d for ooa CDB %02x %02x @ %p",
11010 	     __func__, ooa_entry->seridx, ooa_io->scsiio.cdb[0],
11011 	     ooa_io->scsiio.cdb[1], ooa_io));
11012 
11013 	serialize_row = ctl_serialize_table[ooa_entry->seridx];
11014 
11015 	switch (serialize_row[pending_entry->seridx]) {
11016 	case CTL_SER_BLOCK:
11017 		return (CTL_ACTION_BLOCK);
11018 	case CTL_SER_EXTENT:
11019 		return (ctl_extent_check(ooa_io, pending_io,
11020 		    (lun->be_lun && lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
11021 	case CTL_SER_EXTENTOPT:
11022 		if ((lun->MODE_CTRL.queue_flags & SCP_QUEUE_ALG_MASK) !=
11023 		    SCP_QUEUE_ALG_UNRESTRICTED)
11024 			return (ctl_extent_check(ooa_io, pending_io,
11025 			    (lun->be_lun &&
11026 			     lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
11027 		return (CTL_ACTION_PASS);
11028 	case CTL_SER_EXTENTSEQ:
11029 		if (lun->be_lun && lun->be_lun->serseq != CTL_LUN_SERSEQ_OFF)
11030 			return (ctl_extent_check_seq(ooa_io, pending_io));
11031 		return (CTL_ACTION_PASS);
11032 	case CTL_SER_PASS:
11033 		return (CTL_ACTION_PASS);
11034 	case CTL_SER_BLOCKOPT:
11035 		if ((lun->MODE_CTRL.queue_flags & SCP_QUEUE_ALG_MASK) !=
11036 		    SCP_QUEUE_ALG_UNRESTRICTED)
11037 			return (CTL_ACTION_BLOCK);
11038 		return (CTL_ACTION_PASS);
11039 	case CTL_SER_SKIP:
11040 		return (CTL_ACTION_SKIP);
11041 	default:
11042 		panic("%s: Invalid serialization value %d for %d => %d",
11043 		    __func__, serialize_row[pending_entry->seridx],
11044 		    pending_entry->seridx, ooa_entry->seridx);
11045 	}
11046 
11047 	return (CTL_ACTION_ERROR);
11048 }
11049 
11050 /*
11051  * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
11052  * Assumptions:
11053  * - pending_io is generally either incoming, or on the blocked queue
11054  * - starting I/O is the I/O we want to start the check with.
11055  */
11056 static ctl_action
11057 ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
11058 	      union ctl_io **starting_io)
11059 {
11060 	union ctl_io *ooa_io;
11061 	ctl_action action;
11062 
11063 	mtx_assert(&lun->lun_lock, MA_OWNED);
11064 
11065 	/*
11066 	 * Run back along the OOA queue, starting with the current
11067 	 * blocked I/O and going through every I/O before it on the
11068 	 * queue.  If starting_io is NULL, we'll just end up returning
11069 	 * CTL_ACTION_PASS.
11070 	 */
11071 	for (ooa_io = *starting_io; ooa_io != NULL;
11072 	     ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
11073 	     ooa_links)){
11074 		action = ctl_check_for_blockage(lun, pending_io, ooa_io);
11075 		if (action != CTL_ACTION_PASS) {
11076 			*starting_io = ooa_io;
11077 			return (action);
11078 		}
11079 	}
11080 
11081 	*starting_io = NULL;
11082 	return (CTL_ACTION_PASS);
11083 }
11084 
11085 /*
11086  * Try to unblock the specified I/O.
11087  *
11088  * skip parameter allows explicitly skip present blocker of the I/O,
11089  * starting from the previous one on OOA queue.  It can be used when
11090  * we know for sure that the blocker I/O does no longer count.
11091  */
11092 static void
11093 ctl_try_unblock_io(struct ctl_lun *lun, union ctl_io *io, bool skip)
11094 {
11095 	struct ctl_softc *softc = lun->ctl_softc;
11096 	union ctl_io *bio, *obio;
11097 	const struct ctl_cmd_entry *entry;
11098 	union ctl_ha_msg msg_info;
11099 	ctl_action action;
11100 
11101 	mtx_assert(&lun->lun_lock, MA_OWNED);
11102 
11103 	if (io->io_hdr.blocker == NULL)
11104 		return;
11105 
11106 	obio = bio = io->io_hdr.blocker;
11107 	if (skip)
11108 		bio = (union ctl_io *)TAILQ_PREV(&bio->io_hdr, ctl_ooaq,
11109 		    ooa_links);
11110 	action = ctl_check_ooa(lun, io, &bio);
11111 	if (action == CTL_ACTION_BLOCK) {
11112 		/* Still blocked, but may be by different I/O now. */
11113 		if (bio != obio) {
11114 			TAILQ_REMOVE(&obio->io_hdr.blocked_queue,
11115 			    &io->io_hdr, blocked_links);
11116 			TAILQ_INSERT_TAIL(&bio->io_hdr.blocked_queue,
11117 			    &io->io_hdr, blocked_links);
11118 			io->io_hdr.blocker = bio;
11119 		}
11120 		return;
11121 	}
11122 
11123 	/* No longer blocked, one way or another. */
11124 	TAILQ_REMOVE(&obio->io_hdr.blocked_queue, &io->io_hdr, blocked_links);
11125 	io->io_hdr.blocker = NULL;
11126 
11127 	switch (action) {
11128 	case CTL_ACTION_OVERLAP:
11129 		ctl_set_overlapped_cmd(&io->scsiio);
11130 		goto error;
11131 	case CTL_ACTION_OVERLAP_TAG:
11132 		ctl_set_overlapped_tag(&io->scsiio,
11133 		    io->scsiio.tag_num & 0xff);
11134 		goto error;
11135 	case CTL_ACTION_PASS:
11136 	case CTL_ACTION_SKIP:
11137 
11138 		/* Serializing commands from the other SC retire there. */
11139 		if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) &&
11140 		    (softc->ha_mode != CTL_HA_MODE_XFER)) {
11141 			io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11142 			msg_info.hdr.original_sc = io->io_hdr.remote_io;
11143 			msg_info.hdr.serializing_sc = io;
11144 			msg_info.hdr.msg_type = CTL_MSG_R2R;
11145 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11146 			    sizeof(msg_info.hdr), M_NOWAIT);
11147 			break;
11148 		}
11149 
11150 		/*
11151 		 * Check this I/O for LUN state changes that may have happened
11152 		 * while this command was blocked. The LUN state may have been
11153 		 * changed by a command ahead of us in the queue.
11154 		 */
11155 		entry = ctl_get_cmd_entry(&io->scsiio, NULL);
11156 		if (ctl_scsiio_lun_check(lun, entry, &io->scsiio) != 0) {
11157 			ctl_done(io);
11158 			break;
11159 		}
11160 
11161 		io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11162 		ctl_enqueue_rtr(io);
11163 		break;
11164 	case CTL_ACTION_ERROR:
11165 	default:
11166 		ctl_set_internal_failure(&io->scsiio,
11167 					 /*sks_valid*/ 0,
11168 					 /*retry_count*/ 0);
11169 
11170 error:
11171 		/* Serializing commands from the other SC are done here. */
11172 		if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) &&
11173 		    (softc->ha_mode != CTL_HA_MODE_XFER)) {
11174 			ctl_try_unblock_others(lun, io, TRUE);
11175 			TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
11176 
11177 			ctl_copy_sense_data_back(io, &msg_info);
11178 			msg_info.hdr.original_sc = io->io_hdr.remote_io;
11179 			msg_info.hdr.serializing_sc = NULL;
11180 			msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
11181 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11182 			    sizeof(msg_info.scsi), M_WAITOK);
11183 			ctl_free_io(io);
11184 			break;
11185 		}
11186 
11187 		ctl_done(io);
11188 		break;
11189 	}
11190 }
11191 
11192 /*
11193  * Try to unblock I/Os blocked by the specified I/O.
11194  *
11195  * skip parameter allows explicitly skip the specified I/O as blocker,
11196  * starting from the previous one on the OOA queue.  It can be used when
11197  * we know for sure that the specified I/O does no longer count (done).
11198  * It has to be still on OOA queue though so that we know where to start.
11199  */
11200 static void
11201 ctl_try_unblock_others(struct ctl_lun *lun, union ctl_io *bio, bool skip)
11202 {
11203 	union ctl_io *io, *next_io;
11204 
11205 	mtx_assert(&lun->lun_lock, MA_OWNED);
11206 
11207 	for (io = (union ctl_io *)TAILQ_FIRST(&bio->io_hdr.blocked_queue);
11208 	     io != NULL; io = next_io) {
11209 		next_io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr, blocked_links);
11210 
11211 		KASSERT(io->io_hdr.blocker != NULL,
11212 		    ("I/O %p on blocked list without blocker", io));
11213 		ctl_try_unblock_io(lun, io, skip);
11214 	}
11215 	KASSERT(!skip || TAILQ_EMPTY(&bio->io_hdr.blocked_queue),
11216 	    ("blocked_queue is not empty after skipping %p", bio));
11217 }
11218 
11219 /*
11220  * This routine (with one exception) checks LUN flags that can be set by
11221  * commands ahead of us in the OOA queue.  These flags have to be checked
11222  * when a command initially comes in, and when we pull a command off the
11223  * blocked queue and are preparing to execute it.  The reason we have to
11224  * check these flags for commands on the blocked queue is that the LUN
11225  * state may have been changed by a command ahead of us while we're on the
11226  * blocked queue.
11227  *
11228  * Ordering is somewhat important with these checks, so please pay
11229  * careful attention to the placement of any new checks.
11230  */
11231 static int
11232 ctl_scsiio_lun_check(struct ctl_lun *lun,
11233     const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11234 {
11235 	struct ctl_softc *softc = lun->ctl_softc;
11236 	int retval;
11237 	uint32_t residx;
11238 
11239 	retval = 0;
11240 
11241 	mtx_assert(&lun->lun_lock, MA_OWNED);
11242 
11243 	/*
11244 	 * If this shelf is a secondary shelf controller, we may have to
11245 	 * reject some commands disallowed by HA mode and link state.
11246 	 */
11247 	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11248 		if (softc->ha_link == CTL_HA_LINK_OFFLINE &&
11249 		    (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11250 			ctl_set_lun_unavail(ctsio);
11251 			retval = 1;
11252 			goto bailout;
11253 		}
11254 		if ((lun->flags & CTL_LUN_PEER_SC_PRIMARY) == 0 &&
11255 		    (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11256 			ctl_set_lun_transit(ctsio);
11257 			retval = 1;
11258 			goto bailout;
11259 		}
11260 		if (softc->ha_mode == CTL_HA_MODE_ACT_STBY &&
11261 		    (entry->flags & CTL_CMD_FLAG_OK_ON_STANDBY) == 0) {
11262 			ctl_set_lun_standby(ctsio);
11263 			retval = 1;
11264 			goto bailout;
11265 		}
11266 
11267 		/* The rest of checks are only done on executing side */
11268 		if (softc->ha_mode == CTL_HA_MODE_XFER)
11269 			goto bailout;
11270 	}
11271 
11272 	if (entry->pattern & CTL_LUN_PAT_WRITE) {
11273 		if (lun->be_lun &&
11274 		    lun->be_lun->flags & CTL_LUN_FLAG_READONLY) {
11275 			ctl_set_hw_write_protected(ctsio);
11276 			retval = 1;
11277 			goto bailout;
11278 		}
11279 		if ((lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0) {
11280 			ctl_set_sense(ctsio, /*current_error*/ 1,
11281 			    /*sense_key*/ SSD_KEY_DATA_PROTECT,
11282 			    /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
11283 			retval = 1;
11284 			goto bailout;
11285 		}
11286 	}
11287 
11288 	/*
11289 	 * Check for a reservation conflict.  If this command isn't allowed
11290 	 * even on reserved LUNs, and if this initiator isn't the one who
11291 	 * reserved us, reject the command with a reservation conflict.
11292 	 */
11293 	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11294 	if ((lun->flags & CTL_LUN_RESERVED)
11295 	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11296 		if (lun->res_idx != residx) {
11297 			ctl_set_reservation_conflict(ctsio);
11298 			retval = 1;
11299 			goto bailout;
11300 		}
11301 	}
11302 
11303 	if ((lun->flags & CTL_LUN_PR_RESERVED) == 0 ||
11304 	    (entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV)) {
11305 		/* No reservation or command is allowed. */;
11306 	} else if ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_WRESV) &&
11307 	    (lun->pr_res_type == SPR_TYPE_WR_EX ||
11308 	     lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
11309 	     lun->pr_res_type == SPR_TYPE_WR_EX_AR)) {
11310 		/* The command is allowed for Write Exclusive resv. */;
11311 	} else {
11312 		/*
11313 		 * if we aren't registered or it's a res holder type
11314 		 * reservation and this isn't the res holder then set a
11315 		 * conflict.
11316 		 */
11317 		if (ctl_get_prkey(lun, residx) == 0 ||
11318 		    (residx != lun->pr_res_idx && lun->pr_res_type < 4)) {
11319 			ctl_set_reservation_conflict(ctsio);
11320 			retval = 1;
11321 			goto bailout;
11322 		}
11323 	}
11324 
11325 	if ((entry->flags & CTL_CMD_FLAG_OK_ON_NO_MEDIA) == 0) {
11326 		if (lun->flags & CTL_LUN_EJECTED)
11327 			ctl_set_lun_ejected(ctsio);
11328 		else if (lun->flags & CTL_LUN_NO_MEDIA) {
11329 			if (lun->flags & CTL_LUN_REMOVABLE)
11330 				ctl_set_lun_no_media(ctsio);
11331 			else
11332 				ctl_set_lun_int_reqd(ctsio);
11333 		} else if (lun->flags & CTL_LUN_STOPPED)
11334 			ctl_set_lun_stopped(ctsio);
11335 		else
11336 			goto bailout;
11337 		retval = 1;
11338 		goto bailout;
11339 	}
11340 
11341 bailout:
11342 	return (retval);
11343 }
11344 
11345 static void
11346 ctl_failover_io(union ctl_io *io, int have_lock)
11347 {
11348 	ctl_set_busy(&io->scsiio);
11349 	ctl_done(io);
11350 }
11351 
11352 static void
11353 ctl_failover_lun(union ctl_io *rio)
11354 {
11355 	struct ctl_softc *softc = CTL_SOFTC(rio);
11356 	struct ctl_lun *lun;
11357 	struct ctl_io_hdr *io, *next_io;
11358 	uint32_t targ_lun;
11359 
11360 	targ_lun = rio->io_hdr.nexus.targ_mapped_lun;
11361 	CTL_DEBUG_PRINT(("FAILOVER for lun %u\n", targ_lun));
11362 
11363 	/* Find and lock the LUN. */
11364 	mtx_lock(&softc->ctl_lock);
11365 	if (targ_lun > ctl_max_luns ||
11366 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11367 		mtx_unlock(&softc->ctl_lock);
11368 		return;
11369 	}
11370 	mtx_lock(&lun->lun_lock);
11371 	mtx_unlock(&softc->ctl_lock);
11372 	if (lun->flags & CTL_LUN_DISABLED) {
11373 		mtx_unlock(&lun->lun_lock);
11374 		return;
11375 	}
11376 
11377 	if (softc->ha_mode == CTL_HA_MODE_XFER) {
11378 		TAILQ_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11379 			/* We are master */
11380 			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11381 				if (io->flags & CTL_FLAG_IO_ACTIVE) {
11382 					io->flags |= CTL_FLAG_ABORT;
11383 					io->flags |= CTL_FLAG_FAILOVER;
11384 					ctl_try_unblock_io(lun,
11385 					    (union ctl_io *)io, FALSE);
11386 				} else { /* This can be only due to DATAMOVE */
11387 					io->msg_type = CTL_MSG_DATAMOVE_DONE;
11388 					io->flags &= ~CTL_FLAG_DMA_INPROG;
11389 					io->flags |= CTL_FLAG_IO_ACTIVE;
11390 					io->port_status = 31340;
11391 					ctl_enqueue_isc((union ctl_io *)io);
11392 				}
11393 			} else
11394 			/* We are slave */
11395 			if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11396 				io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11397 				if (io->flags & CTL_FLAG_IO_ACTIVE) {
11398 					io->flags |= CTL_FLAG_FAILOVER;
11399 				} else {
11400 					ctl_set_busy(&((union ctl_io *)io)->
11401 					    scsiio);
11402 					ctl_done((union ctl_io *)io);
11403 				}
11404 			}
11405 		}
11406 	} else { /* SERIALIZE modes */
11407 		TAILQ_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11408 			/* We are master */
11409 			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11410 				if (io->blocker != NULL) {
11411 					TAILQ_REMOVE(&io->blocker->io_hdr.blocked_queue,
11412 					    io, blocked_links);
11413 					io->blocker = NULL;
11414 				}
11415 				ctl_try_unblock_others(lun, (union ctl_io *)io,
11416 				    TRUE);
11417 				TAILQ_REMOVE(&lun->ooa_queue, io, ooa_links);
11418 				ctl_free_io((union ctl_io *)io);
11419 			} else
11420 			/* We are slave */
11421 			if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11422 				io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11423 				if (!(io->flags & CTL_FLAG_IO_ACTIVE)) {
11424 					ctl_set_busy(&((union ctl_io *)io)->
11425 					    scsiio);
11426 					ctl_done((union ctl_io *)io);
11427 				}
11428 			}
11429 		}
11430 	}
11431 	mtx_unlock(&lun->lun_lock);
11432 }
11433 
11434 static int
11435 ctl_scsiio_precheck(struct ctl_softc *softc, struct ctl_scsiio *ctsio)
11436 {
11437 	struct ctl_lun *lun;
11438 	const struct ctl_cmd_entry *entry;
11439 	union ctl_io *bio;
11440 	uint32_t initidx, targ_lun;
11441 	int retval = 0;
11442 
11443 	lun = NULL;
11444 	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11445 	if (targ_lun < ctl_max_luns)
11446 		lun = softc->ctl_luns[targ_lun];
11447 	if (lun) {
11448 		/*
11449 		 * If the LUN is invalid, pretend that it doesn't exist.
11450 		 * It will go away as soon as all pending I/O has been
11451 		 * completed.
11452 		 */
11453 		mtx_lock(&lun->lun_lock);
11454 		if (lun->flags & CTL_LUN_DISABLED) {
11455 			mtx_unlock(&lun->lun_lock);
11456 			lun = NULL;
11457 		}
11458 	}
11459 	CTL_LUN(ctsio) = lun;
11460 	if (lun) {
11461 		CTL_BACKEND_LUN(ctsio) = lun->be_lun;
11462 
11463 		/*
11464 		 * Every I/O goes into the OOA queue for a particular LUN,
11465 		 * and stays there until completion.
11466 		 */
11467 #ifdef CTL_TIME_IO
11468 		if (TAILQ_EMPTY(&lun->ooa_queue))
11469 			lun->idle_time += getsbinuptime() - lun->last_busy;
11470 #endif
11471 		TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
11472 	}
11473 
11474 	/* Get command entry and return error if it is unsuppotyed. */
11475 	entry = ctl_validate_command(ctsio);
11476 	if (entry == NULL) {
11477 		if (lun)
11478 			mtx_unlock(&lun->lun_lock);
11479 		return (retval);
11480 	}
11481 
11482 	ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11483 	ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11484 
11485 	/*
11486 	 * Check to see whether we can send this command to LUNs that don't
11487 	 * exist.  This should pretty much only be the case for inquiry
11488 	 * and request sense.  Further checks, below, really require having
11489 	 * a LUN, so we can't really check the command anymore.  Just put
11490 	 * it on the rtr queue.
11491 	 */
11492 	if (lun == NULL) {
11493 		if (entry->flags & CTL_CMD_FLAG_OK_ON_NO_LUN) {
11494 			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11495 			ctl_enqueue_rtr((union ctl_io *)ctsio);
11496 			return (retval);
11497 		}
11498 
11499 		ctl_set_unsupported_lun(ctsio);
11500 		ctl_done((union ctl_io *)ctsio);
11501 		CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11502 		return (retval);
11503 	} else {
11504 		/*
11505 		 * Make sure we support this particular command on this LUN.
11506 		 * e.g., we don't support writes to the control LUN.
11507 		 */
11508 		if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11509 			mtx_unlock(&lun->lun_lock);
11510 			ctl_set_invalid_opcode(ctsio);
11511 			ctl_done((union ctl_io *)ctsio);
11512 			return (retval);
11513 		}
11514 	}
11515 
11516 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11517 
11518 	/*
11519 	 * If we've got a request sense, it'll clear the contingent
11520 	 * allegiance condition.  Otherwise, if we have a CA condition for
11521 	 * this initiator, clear it, because it sent down a command other
11522 	 * than request sense.
11523 	 */
11524 	if (ctsio->cdb[0] != REQUEST_SENSE) {
11525 		struct scsi_sense_data *ps;
11526 
11527 		ps = lun->pending_sense[initidx / CTL_MAX_INIT_PER_PORT];
11528 		if (ps != NULL)
11529 			ps[initidx % CTL_MAX_INIT_PER_PORT].error_code = 0;
11530 	}
11531 
11532 	/*
11533 	 * If the command has this flag set, it handles its own unit
11534 	 * attention reporting, we shouldn't do anything.  Otherwise we
11535 	 * check for any pending unit attentions, and send them back to the
11536 	 * initiator.  We only do this when a command initially comes in,
11537 	 * not when we pull it off the blocked queue.
11538 	 *
11539 	 * According to SAM-3, section 5.3.2, the order that things get
11540 	 * presented back to the host is basically unit attentions caused
11541 	 * by some sort of reset event, busy status, reservation conflicts
11542 	 * or task set full, and finally any other status.
11543 	 *
11544 	 * One issue here is that some of the unit attentions we report
11545 	 * don't fall into the "reset" category (e.g. "reported luns data
11546 	 * has changed").  So reporting it here, before the reservation
11547 	 * check, may be technically wrong.  I guess the only thing to do
11548 	 * would be to check for and report the reset events here, and then
11549 	 * check for the other unit attention types after we check for a
11550 	 * reservation conflict.
11551 	 *
11552 	 * XXX KDM need to fix this
11553 	 */
11554 	if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11555 		ctl_ua_type ua_type;
11556 		u_int sense_len = 0;
11557 
11558 		ua_type = ctl_build_ua(lun, initidx, &ctsio->sense_data,
11559 		    &sense_len, SSD_TYPE_NONE);
11560 		if (ua_type != CTL_UA_NONE) {
11561 			mtx_unlock(&lun->lun_lock);
11562 			ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11563 			ctsio->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
11564 			ctsio->sense_len = sense_len;
11565 			ctl_done((union ctl_io *)ctsio);
11566 			return (retval);
11567 		}
11568 	}
11569 
11570 
11571 	if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
11572 		mtx_unlock(&lun->lun_lock);
11573 		ctl_done((union ctl_io *)ctsio);
11574 		return (retval);
11575 	}
11576 
11577 	/*
11578 	 * XXX CHD this is where we want to send IO to other side if
11579 	 * this LUN is secondary on this SC. We will need to make a copy
11580 	 * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11581 	 * the copy we send as FROM_OTHER.
11582 	 * We also need to stuff the address of the original IO so we can
11583 	 * find it easily. Something similar will need be done on the other
11584 	 * side so when we are done we can find the copy.
11585 	 */
11586 	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
11587 	    (lun->flags & CTL_LUN_PEER_SC_PRIMARY) != 0 &&
11588 	    (entry->flags & CTL_CMD_FLAG_RUN_HERE) == 0) {
11589 		union ctl_ha_msg msg_info;
11590 		int isc_retval;
11591 
11592 		ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11593 		ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11594 		mtx_unlock(&lun->lun_lock);
11595 
11596 		msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11597 		msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11598 		msg_info.hdr.serializing_sc = NULL;
11599 		msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11600 		msg_info.scsi.tag_num = ctsio->tag_num;
11601 		msg_info.scsi.tag_type = ctsio->tag_type;
11602 		msg_info.scsi.cdb_len = ctsio->cdb_len;
11603 		memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11604 
11605 		if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11606 		    sizeof(msg_info.scsi) - sizeof(msg_info.scsi.sense_data),
11607 		    M_WAITOK)) > CTL_HA_STATUS_SUCCESS) {
11608 			ctl_set_busy(ctsio);
11609 			ctl_done((union ctl_io *)ctsio);
11610 			return (retval);
11611 		}
11612 		return (retval);
11613 	}
11614 
11615 	bio = (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq, ooa_links);
11616 	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio, &bio)) {
11617 	case CTL_ACTION_BLOCK:
11618 		ctsio->io_hdr.blocker = bio;
11619 		TAILQ_INSERT_TAIL(&bio->io_hdr.blocked_queue, &ctsio->io_hdr,
11620 				  blocked_links);
11621 		mtx_unlock(&lun->lun_lock);
11622 		return (retval);
11623 	case CTL_ACTION_PASS:
11624 	case CTL_ACTION_SKIP:
11625 		ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11626 		mtx_unlock(&lun->lun_lock);
11627 		ctl_enqueue_rtr((union ctl_io *)ctsio);
11628 		break;
11629 	case CTL_ACTION_OVERLAP:
11630 		mtx_unlock(&lun->lun_lock);
11631 		ctl_set_overlapped_cmd(ctsio);
11632 		ctl_done((union ctl_io *)ctsio);
11633 		break;
11634 	case CTL_ACTION_OVERLAP_TAG:
11635 		mtx_unlock(&lun->lun_lock);
11636 		ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11637 		ctl_done((union ctl_io *)ctsio);
11638 		break;
11639 	case CTL_ACTION_ERROR:
11640 	default:
11641 		mtx_unlock(&lun->lun_lock);
11642 		ctl_set_internal_failure(ctsio,
11643 					 /*sks_valid*/ 0,
11644 					 /*retry_count*/ 0);
11645 		ctl_done((union ctl_io *)ctsio);
11646 		break;
11647 	}
11648 	return (retval);
11649 }
11650 
11651 const struct ctl_cmd_entry *
11652 ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11653 {
11654 	const struct ctl_cmd_entry *entry;
11655 	int service_action;
11656 
11657 	entry = &ctl_cmd_table[ctsio->cdb[0]];
11658 	if (sa)
11659 		*sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11660 	if (entry->flags & CTL_CMD_FLAG_SA5) {
11661 		service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11662 		entry = &((const struct ctl_cmd_entry *)
11663 		    entry->execute)[service_action];
11664 	}
11665 	return (entry);
11666 }
11667 
11668 const struct ctl_cmd_entry *
11669 ctl_validate_command(struct ctl_scsiio *ctsio)
11670 {
11671 	const struct ctl_cmd_entry *entry;
11672 	int i, sa;
11673 	uint8_t diff;
11674 
11675 	entry = ctl_get_cmd_entry(ctsio, &sa);
11676 	if (entry->execute == NULL) {
11677 		if (sa)
11678 			ctl_set_invalid_field(ctsio,
11679 					      /*sks_valid*/ 1,
11680 					      /*command*/ 1,
11681 					      /*field*/ 1,
11682 					      /*bit_valid*/ 1,
11683 					      /*bit*/ 4);
11684 		else
11685 			ctl_set_invalid_opcode(ctsio);
11686 		ctl_done((union ctl_io *)ctsio);
11687 		return (NULL);
11688 	}
11689 	KASSERT(entry->length > 0,
11690 	    ("Not defined length for command 0x%02x/0x%02x",
11691 	     ctsio->cdb[0], ctsio->cdb[1]));
11692 	for (i = 1; i < entry->length; i++) {
11693 		diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11694 		if (diff == 0)
11695 			continue;
11696 		ctl_set_invalid_field(ctsio,
11697 				      /*sks_valid*/ 1,
11698 				      /*command*/ 1,
11699 				      /*field*/ i,
11700 				      /*bit_valid*/ 1,
11701 				      /*bit*/ fls(diff) - 1);
11702 		ctl_done((union ctl_io *)ctsio);
11703 		return (NULL);
11704 	}
11705 	return (entry);
11706 }
11707 
11708 static int
11709 ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11710 {
11711 
11712 	switch (lun_type) {
11713 	case T_DIRECT:
11714 		if ((entry->flags & CTL_CMD_FLAG_OK_ON_DIRECT) == 0)
11715 			return (0);
11716 		break;
11717 	case T_PROCESSOR:
11718 		if ((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0)
11719 			return (0);
11720 		break;
11721 	case T_CDROM:
11722 		if ((entry->flags & CTL_CMD_FLAG_OK_ON_CDROM) == 0)
11723 			return (0);
11724 		break;
11725 	default:
11726 		return (0);
11727 	}
11728 	return (1);
11729 }
11730 
11731 static int
11732 ctl_scsiio(struct ctl_scsiio *ctsio)
11733 {
11734 	int retval;
11735 	const struct ctl_cmd_entry *entry;
11736 
11737 	retval = CTL_RETVAL_COMPLETE;
11738 
11739 	CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11740 
11741 	entry = ctl_get_cmd_entry(ctsio, NULL);
11742 
11743 	/*
11744 	 * If this I/O has been aborted, just send it straight to
11745 	 * ctl_done() without executing it.
11746 	 */
11747 	if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11748 		ctl_done((union ctl_io *)ctsio);
11749 		goto bailout;
11750 	}
11751 
11752 	/*
11753 	 * All the checks should have been handled by ctl_scsiio_precheck().
11754 	 * We should be clear now to just execute the I/O.
11755 	 */
11756 	retval = entry->execute(ctsio);
11757 
11758 bailout:
11759 	return (retval);
11760 }
11761 
11762 static int
11763 ctl_target_reset(union ctl_io *io)
11764 {
11765 	struct ctl_softc *softc = CTL_SOFTC(io);
11766 	struct ctl_port *port = CTL_PORT(io);
11767 	struct ctl_lun *lun;
11768 	uint32_t initidx;
11769 	ctl_ua_type ua_type;
11770 
11771 	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11772 		union ctl_ha_msg msg_info;
11773 
11774 		msg_info.hdr.nexus = io->io_hdr.nexus;
11775 		msg_info.task.task_action = io->taskio.task_action;
11776 		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11777 		msg_info.hdr.original_sc = NULL;
11778 		msg_info.hdr.serializing_sc = NULL;
11779 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11780 		    sizeof(msg_info.task), M_WAITOK);
11781 	}
11782 
11783 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
11784 	if (io->taskio.task_action == CTL_TASK_TARGET_RESET)
11785 		ua_type = CTL_UA_TARG_RESET;
11786 	else
11787 		ua_type = CTL_UA_BUS_RESET;
11788 	mtx_lock(&softc->ctl_lock);
11789 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
11790 		if (port != NULL &&
11791 		    ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
11792 			continue;
11793 		ctl_do_lun_reset(lun, initidx, ua_type);
11794 	}
11795 	mtx_unlock(&softc->ctl_lock);
11796 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11797 	return (0);
11798 }
11799 
11800 /*
11801  * The LUN should always be set.  The I/O is optional, and is used to
11802  * distinguish between I/Os sent by this initiator, and by other
11803  * initiators.  We set unit attention for initiators other than this one.
11804  * SAM-3 is vague on this point.  It does say that a unit attention should
11805  * be established for other initiators when a LUN is reset (see section
11806  * 5.7.3), but it doesn't specifically say that the unit attention should
11807  * be established for this particular initiator when a LUN is reset.  Here
11808  * is the relevant text, from SAM-3 rev 8:
11809  *
11810  * 5.7.2 When a SCSI initiator port aborts its own tasks
11811  *
11812  * When a SCSI initiator port causes its own task(s) to be aborted, no
11813  * notification that the task(s) have been aborted shall be returned to
11814  * the SCSI initiator port other than the completion response for the
11815  * command or task management function action that caused the task(s) to
11816  * be aborted and notification(s) associated with related effects of the
11817  * action (e.g., a reset unit attention condition).
11818  *
11819  * XXX KDM for now, we're setting unit attention for all initiators.
11820  */
11821 static void
11822 ctl_do_lun_reset(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua_type)
11823 {
11824 	union ctl_io *xio;
11825 	int i;
11826 
11827 	mtx_lock(&lun->lun_lock);
11828 	/* Abort tasks. */
11829 	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11830 	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11831 		xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
11832 		ctl_try_unblock_io(lun, xio, FALSE);
11833 	}
11834 	/* Clear CA. */
11835 	for (i = 0; i < ctl_max_ports; i++) {
11836 		free(lun->pending_sense[i], M_CTL);
11837 		lun->pending_sense[i] = NULL;
11838 	}
11839 	/* Clear reservation. */
11840 	lun->flags &= ~CTL_LUN_RESERVED;
11841 	/* Clear prevent media removal. */
11842 	if (lun->prevent) {
11843 		for (i = 0; i < CTL_MAX_INITIATORS; i++)
11844 			ctl_clear_mask(lun->prevent, i);
11845 		lun->prevent_count = 0;
11846 	}
11847 	/* Clear TPC status */
11848 	ctl_tpc_lun_clear(lun, -1);
11849 	/* Establish UA. */
11850 #if 0
11851 	ctl_est_ua_all(lun, initidx, ua_type);
11852 #else
11853 	ctl_est_ua_all(lun, -1, ua_type);
11854 #endif
11855 	mtx_unlock(&lun->lun_lock);
11856 }
11857 
11858 static int
11859 ctl_lun_reset(union ctl_io *io)
11860 {
11861 	struct ctl_softc *softc = CTL_SOFTC(io);
11862 	struct ctl_lun *lun;
11863 	uint32_t targ_lun, initidx;
11864 
11865 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11866 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
11867 	mtx_lock(&softc->ctl_lock);
11868 	if (targ_lun >= ctl_max_luns ||
11869 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11870 		mtx_unlock(&softc->ctl_lock);
11871 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11872 		return (1);
11873 	}
11874 	ctl_do_lun_reset(lun, initidx, CTL_UA_LUN_RESET);
11875 	mtx_unlock(&softc->ctl_lock);
11876 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11877 
11878 	if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0) {
11879 		union ctl_ha_msg msg_info;
11880 
11881 		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11882 		msg_info.hdr.nexus = io->io_hdr.nexus;
11883 		msg_info.task.task_action = CTL_TASK_LUN_RESET;
11884 		msg_info.hdr.original_sc = NULL;
11885 		msg_info.hdr.serializing_sc = NULL;
11886 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11887 		    sizeof(msg_info.task), M_WAITOK);
11888 	}
11889 	return (0);
11890 }
11891 
11892 static void
11893 ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
11894     int other_sc)
11895 {
11896 	union ctl_io *xio;
11897 
11898 	mtx_assert(&lun->lun_lock, MA_OWNED);
11899 
11900 	/*
11901 	 * Run through the OOA queue and attempt to find the given I/O.
11902 	 * The target port, initiator ID, tag type and tag number have to
11903 	 * match the values that we got from the initiator.  If we have an
11904 	 * untagged command to abort, simply abort the first untagged command
11905 	 * we come to.  We only allow one untagged command at a time of course.
11906 	 */
11907 	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11908 	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11909 
11910 		if ((targ_port == UINT32_MAX ||
11911 		     targ_port == xio->io_hdr.nexus.targ_port) &&
11912 		    (init_id == UINT32_MAX ||
11913 		     init_id == xio->io_hdr.nexus.initid)) {
11914 			if (targ_port != xio->io_hdr.nexus.targ_port ||
11915 			    init_id != xio->io_hdr.nexus.initid)
11916 				xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
11917 			xio->io_hdr.flags |= CTL_FLAG_ABORT;
11918 			if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11919 				union ctl_ha_msg msg_info;
11920 
11921 				msg_info.hdr.nexus = xio->io_hdr.nexus;
11922 				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
11923 				msg_info.task.tag_num = xio->scsiio.tag_num;
11924 				msg_info.task.tag_type = xio->scsiio.tag_type;
11925 				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11926 				msg_info.hdr.original_sc = NULL;
11927 				msg_info.hdr.serializing_sc = NULL;
11928 				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11929 				    sizeof(msg_info.task), M_NOWAIT);
11930 			}
11931 			ctl_try_unblock_io(lun, xio, FALSE);
11932 		}
11933 	}
11934 }
11935 
11936 static int
11937 ctl_abort_task_set(union ctl_io *io)
11938 {
11939 	struct ctl_softc *softc = CTL_SOFTC(io);
11940 	struct ctl_lun *lun;
11941 	uint32_t targ_lun;
11942 
11943 	/*
11944 	 * Look up the LUN.
11945 	 */
11946 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11947 	mtx_lock(&softc->ctl_lock);
11948 	if (targ_lun >= ctl_max_luns ||
11949 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11950 		mtx_unlock(&softc->ctl_lock);
11951 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11952 		return (1);
11953 	}
11954 
11955 	mtx_lock(&lun->lun_lock);
11956 	mtx_unlock(&softc->ctl_lock);
11957 	if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
11958 		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
11959 		    io->io_hdr.nexus.initid,
11960 		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11961 	} else { /* CTL_TASK_CLEAR_TASK_SET */
11962 		ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
11963 		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11964 	}
11965 	mtx_unlock(&lun->lun_lock);
11966 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11967 	return (0);
11968 }
11969 
11970 static void
11971 ctl_i_t_nexus_loss(struct ctl_softc *softc, uint32_t initidx,
11972     ctl_ua_type ua_type)
11973 {
11974 	struct ctl_lun *lun;
11975 	struct scsi_sense_data *ps;
11976 	uint32_t p, i;
11977 
11978 	p = initidx / CTL_MAX_INIT_PER_PORT;
11979 	i = initidx % CTL_MAX_INIT_PER_PORT;
11980 	mtx_lock(&softc->ctl_lock);
11981 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
11982 		mtx_lock(&lun->lun_lock);
11983 		/* Abort tasks. */
11984 		ctl_abort_tasks_lun(lun, p, i, 1);
11985 		/* Clear CA. */
11986 		ps = lun->pending_sense[p];
11987 		if (ps != NULL)
11988 			ps[i].error_code = 0;
11989 		/* Clear reservation. */
11990 		if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == initidx))
11991 			lun->flags &= ~CTL_LUN_RESERVED;
11992 		/* Clear prevent media removal. */
11993 		if (lun->prevent && ctl_is_set(lun->prevent, initidx)) {
11994 			ctl_clear_mask(lun->prevent, initidx);
11995 			lun->prevent_count--;
11996 		}
11997 		/* Clear TPC status */
11998 		ctl_tpc_lun_clear(lun, initidx);
11999 		/* Establish UA. */
12000 		ctl_est_ua(lun, initidx, ua_type);
12001 		mtx_unlock(&lun->lun_lock);
12002 	}
12003 	mtx_unlock(&softc->ctl_lock);
12004 }
12005 
12006 static int
12007 ctl_i_t_nexus_reset(union ctl_io *io)
12008 {
12009 	struct ctl_softc *softc = CTL_SOFTC(io);
12010 	uint32_t initidx;
12011 
12012 	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12013 		union ctl_ha_msg msg_info;
12014 
12015 		msg_info.hdr.nexus = io->io_hdr.nexus;
12016 		msg_info.task.task_action = CTL_TASK_I_T_NEXUS_RESET;
12017 		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12018 		msg_info.hdr.original_sc = NULL;
12019 		msg_info.hdr.serializing_sc = NULL;
12020 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12021 		    sizeof(msg_info.task), M_WAITOK);
12022 	}
12023 
12024 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
12025 	ctl_i_t_nexus_loss(softc, initidx, CTL_UA_I_T_NEXUS_LOSS);
12026 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12027 	return (0);
12028 }
12029 
12030 static int
12031 ctl_abort_task(union ctl_io *io)
12032 {
12033 	struct ctl_softc *softc = CTL_SOFTC(io);
12034 	union ctl_io *xio;
12035 	struct ctl_lun *lun;
12036 	uint32_t targ_lun;
12037 
12038 	/*
12039 	 * Look up the LUN.
12040 	 */
12041 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12042 	mtx_lock(&softc->ctl_lock);
12043 	if (targ_lun >= ctl_max_luns ||
12044 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12045 		mtx_unlock(&softc->ctl_lock);
12046 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12047 		return (1);
12048 	}
12049 
12050 	mtx_lock(&lun->lun_lock);
12051 	mtx_unlock(&softc->ctl_lock);
12052 	/*
12053 	 * Run through the OOA queue and attempt to find the given I/O.
12054 	 * The target port, initiator ID, tag type and tag number have to
12055 	 * match the values that we got from the initiator.  If we have an
12056 	 * untagged command to abort, simply abort the first untagged command
12057 	 * we come to.  We only allow one untagged command at a time of course.
12058 	 */
12059 	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12060 	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12061 
12062 		if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
12063 		 || (xio->io_hdr.nexus.initid != io->io_hdr.nexus.initid)
12064 		 || (xio->io_hdr.flags & CTL_FLAG_ABORT))
12065 			continue;
12066 
12067 		/*
12068 		 * If the abort says that the task is untagged, the
12069 		 * task in the queue must be untagged.  Otherwise,
12070 		 * we just check to see whether the tag numbers
12071 		 * match.  This is because the QLogic firmware
12072 		 * doesn't pass back the tag type in an abort
12073 		 * request.
12074 		 */
12075 #if 0
12076 		if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
12077 		  && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
12078 		 || (xio->scsiio.tag_num == io->taskio.tag_num)) {
12079 #else
12080 		/*
12081 		 * XXX KDM we've got problems with FC, because it
12082 		 * doesn't send down a tag type with aborts.  So we
12083 		 * can only really go by the tag number...
12084 		 * This may cause problems with parallel SCSI.
12085 		 * Need to figure that out!!
12086 		 */
12087 		if (xio->scsiio.tag_num == io->taskio.tag_num) {
12088 #endif
12089 			xio->io_hdr.flags |= CTL_FLAG_ABORT;
12090 			if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0 &&
12091 			    !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12092 				union ctl_ha_msg msg_info;
12093 
12094 				msg_info.hdr.nexus = io->io_hdr.nexus;
12095 				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
12096 				msg_info.task.tag_num = io->taskio.tag_num;
12097 				msg_info.task.tag_type = io->taskio.tag_type;
12098 				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12099 				msg_info.hdr.original_sc = NULL;
12100 				msg_info.hdr.serializing_sc = NULL;
12101 				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12102 				    sizeof(msg_info.task), M_NOWAIT);
12103 			}
12104 			ctl_try_unblock_io(lun, xio, FALSE);
12105 		}
12106 	}
12107 	mtx_unlock(&lun->lun_lock);
12108 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12109 	return (0);
12110 }
12111 
12112 static int
12113 ctl_query_task(union ctl_io *io, int task_set)
12114 {
12115 	struct ctl_softc *softc = CTL_SOFTC(io);
12116 	union ctl_io *xio;
12117 	struct ctl_lun *lun;
12118 	int found = 0;
12119 	uint32_t targ_lun;
12120 
12121 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12122 	mtx_lock(&softc->ctl_lock);
12123 	if (targ_lun >= ctl_max_luns ||
12124 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12125 		mtx_unlock(&softc->ctl_lock);
12126 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12127 		return (1);
12128 	}
12129 	mtx_lock(&lun->lun_lock);
12130 	mtx_unlock(&softc->ctl_lock);
12131 	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12132 	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12133 
12134 		if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
12135 		 || (xio->io_hdr.nexus.initid != io->io_hdr.nexus.initid)
12136 		 || (xio->io_hdr.flags & CTL_FLAG_ABORT))
12137 			continue;
12138 
12139 		if (task_set || xio->scsiio.tag_num == io->taskio.tag_num) {
12140 			found = 1;
12141 			break;
12142 		}
12143 	}
12144 	mtx_unlock(&lun->lun_lock);
12145 	if (found)
12146 		io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12147 	else
12148 		io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12149 	return (0);
12150 }
12151 
12152 static int
12153 ctl_query_async_event(union ctl_io *io)
12154 {
12155 	struct ctl_softc *softc = CTL_SOFTC(io);
12156 	struct ctl_lun *lun;
12157 	ctl_ua_type ua;
12158 	uint32_t targ_lun, initidx;
12159 
12160 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12161 	mtx_lock(&softc->ctl_lock);
12162 	if (targ_lun >= ctl_max_luns ||
12163 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12164 		mtx_unlock(&softc->ctl_lock);
12165 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12166 		return (1);
12167 	}
12168 	mtx_lock(&lun->lun_lock);
12169 	mtx_unlock(&softc->ctl_lock);
12170 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
12171 	ua = ctl_build_qae(lun, initidx, io->taskio.task_resp);
12172 	mtx_unlock(&lun->lun_lock);
12173 	if (ua != CTL_UA_NONE)
12174 		io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12175 	else
12176 		io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12177 	return (0);
12178 }
12179 
12180 static void
12181 ctl_run_task(union ctl_io *io)
12182 {
12183 	int retval = 1;
12184 
12185 	CTL_DEBUG_PRINT(("ctl_run_task\n"));
12186 	KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12187 	    ("ctl_run_task: Unextected io_type %d\n", io->io_hdr.io_type));
12188 	io->taskio.task_status = CTL_TASK_FUNCTION_NOT_SUPPORTED;
12189 	bzero(io->taskio.task_resp, sizeof(io->taskio.task_resp));
12190 	switch (io->taskio.task_action) {
12191 	case CTL_TASK_ABORT_TASK:
12192 		retval = ctl_abort_task(io);
12193 		break;
12194 	case CTL_TASK_ABORT_TASK_SET:
12195 	case CTL_TASK_CLEAR_TASK_SET:
12196 		retval = ctl_abort_task_set(io);
12197 		break;
12198 	case CTL_TASK_CLEAR_ACA:
12199 		break;
12200 	case CTL_TASK_I_T_NEXUS_RESET:
12201 		retval = ctl_i_t_nexus_reset(io);
12202 		break;
12203 	case CTL_TASK_LUN_RESET:
12204 		retval = ctl_lun_reset(io);
12205 		break;
12206 	case CTL_TASK_TARGET_RESET:
12207 	case CTL_TASK_BUS_RESET:
12208 		retval = ctl_target_reset(io);
12209 		break;
12210 	case CTL_TASK_PORT_LOGIN:
12211 		break;
12212 	case CTL_TASK_PORT_LOGOUT:
12213 		break;
12214 	case CTL_TASK_QUERY_TASK:
12215 		retval = ctl_query_task(io, 0);
12216 		break;
12217 	case CTL_TASK_QUERY_TASK_SET:
12218 		retval = ctl_query_task(io, 1);
12219 		break;
12220 	case CTL_TASK_QUERY_ASYNC_EVENT:
12221 		retval = ctl_query_async_event(io);
12222 		break;
12223 	default:
12224 		printf("%s: got unknown task management event %d\n",
12225 		       __func__, io->taskio.task_action);
12226 		break;
12227 	}
12228 	if (retval == 0)
12229 		io->io_hdr.status = CTL_SUCCESS;
12230 	else
12231 		io->io_hdr.status = CTL_ERROR;
12232 	ctl_done(io);
12233 }
12234 
12235 /*
12236  * For HA operation.  Handle commands that come in from the other
12237  * controller.
12238  */
12239 static void
12240 ctl_handle_isc(union ctl_io *io)
12241 {
12242 	struct ctl_softc *softc = CTL_SOFTC(io);
12243 	struct ctl_lun *lun;
12244 	const struct ctl_cmd_entry *entry;
12245 	uint32_t targ_lun;
12246 
12247 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12248 	switch (io->io_hdr.msg_type) {
12249 	case CTL_MSG_SERIALIZE:
12250 		ctl_serialize_other_sc_cmd(&io->scsiio);
12251 		break;
12252 	case CTL_MSG_R2R:		/* Only used in SER_ONLY mode. */
12253 		entry = ctl_get_cmd_entry(&io->scsiio, NULL);
12254 		if (targ_lun >= ctl_max_luns ||
12255 		    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12256 			ctl_done(io);
12257 			break;
12258 		}
12259 		mtx_lock(&lun->lun_lock);
12260 		if (ctl_scsiio_lun_check(lun, entry, &io->scsiio) != 0) {
12261 			mtx_unlock(&lun->lun_lock);
12262 			ctl_done(io);
12263 			break;
12264 		}
12265 		io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12266 		mtx_unlock(&lun->lun_lock);
12267 		ctl_enqueue_rtr(io);
12268 		break;
12269 	case CTL_MSG_FINISH_IO:
12270 		if (softc->ha_mode == CTL_HA_MODE_XFER) {
12271 			ctl_done(io);
12272 			break;
12273 		}
12274 		if (targ_lun >= ctl_max_luns ||
12275 		    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12276 			ctl_free_io(io);
12277 			break;
12278 		}
12279 		mtx_lock(&lun->lun_lock);
12280 		ctl_try_unblock_others(lun, io, TRUE);
12281 		TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
12282 		mtx_unlock(&lun->lun_lock);
12283 		ctl_free_io(io);
12284 		break;
12285 	case CTL_MSG_PERS_ACTION:
12286 		ctl_hndl_per_res_out_on_other_sc(io);
12287 		ctl_free_io(io);
12288 		break;
12289 	case CTL_MSG_BAD_JUJU:
12290 		ctl_done(io);
12291 		break;
12292 	case CTL_MSG_DATAMOVE:		/* Only used in XFER mode */
12293 		ctl_datamove_remote(io);
12294 		break;
12295 	case CTL_MSG_DATAMOVE_DONE:	/* Only used in XFER mode */
12296 		io->scsiio.be_move_done(io);
12297 		break;
12298 	case CTL_MSG_FAILOVER:
12299 		ctl_failover_lun(io);
12300 		ctl_free_io(io);
12301 		break;
12302 	default:
12303 		printf("%s: Invalid message type %d\n",
12304 		       __func__, io->io_hdr.msg_type);
12305 		ctl_free_io(io);
12306 		break;
12307 	}
12308 
12309 }
12310 
12311 
12312 /*
12313  * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12314  * there is no match.
12315  */
12316 static ctl_lun_error_pattern
12317 ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12318 {
12319 	const struct ctl_cmd_entry *entry;
12320 	ctl_lun_error_pattern filtered_pattern, pattern;
12321 
12322 	pattern = desc->error_pattern;
12323 
12324 	/*
12325 	 * XXX KDM we need more data passed into this function to match a
12326 	 * custom pattern, and we actually need to implement custom pattern
12327 	 * matching.
12328 	 */
12329 	if (pattern & CTL_LUN_PAT_CMD)
12330 		return (CTL_LUN_PAT_CMD);
12331 
12332 	if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12333 		return (CTL_LUN_PAT_ANY);
12334 
12335 	entry = ctl_get_cmd_entry(ctsio, NULL);
12336 
12337 	filtered_pattern = entry->pattern & pattern;
12338 
12339 	/*
12340 	 * If the user requested specific flags in the pattern (e.g.
12341 	 * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12342 	 * flags.
12343 	 *
12344 	 * If the user did not specify any flags, it doesn't matter whether
12345 	 * or not the command supports the flags.
12346 	 */
12347 	if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12348 	     (pattern & ~CTL_LUN_PAT_MASK))
12349 		return (CTL_LUN_PAT_NONE);
12350 
12351 	/*
12352 	 * If the user asked for a range check, see if the requested LBA
12353 	 * range overlaps with this command's LBA range.
12354 	 */
12355 	if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12356 		uint64_t lba1;
12357 		uint64_t len1;
12358 		ctl_action action;
12359 		int retval;
12360 
12361 		retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12362 		if (retval != 0)
12363 			return (CTL_LUN_PAT_NONE);
12364 
12365 		action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12366 					      desc->lba_range.len, FALSE);
12367 		/*
12368 		 * A "pass" means that the LBA ranges don't overlap, so
12369 		 * this doesn't match the user's range criteria.
12370 		 */
12371 		if (action == CTL_ACTION_PASS)
12372 			return (CTL_LUN_PAT_NONE);
12373 	}
12374 
12375 	return (filtered_pattern);
12376 }
12377 
12378 static void
12379 ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12380 {
12381 	struct ctl_error_desc *desc, *desc2;
12382 
12383 	mtx_assert(&lun->lun_lock, MA_OWNED);
12384 
12385 	STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12386 		ctl_lun_error_pattern pattern;
12387 		/*
12388 		 * Check to see whether this particular command matches
12389 		 * the pattern in the descriptor.
12390 		 */
12391 		pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12392 		if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12393 			continue;
12394 
12395 		switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12396 		case CTL_LUN_INJ_ABORTED:
12397 			ctl_set_aborted(&io->scsiio);
12398 			break;
12399 		case CTL_LUN_INJ_MEDIUM_ERR:
12400 			ctl_set_medium_error(&io->scsiio,
12401 			    (io->io_hdr.flags & CTL_FLAG_DATA_MASK) !=
12402 			     CTL_FLAG_DATA_OUT);
12403 			break;
12404 		case CTL_LUN_INJ_UA:
12405 			/* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12406 			 * OCCURRED */
12407 			ctl_set_ua(&io->scsiio, 0x29, 0x00);
12408 			break;
12409 		case CTL_LUN_INJ_CUSTOM:
12410 			/*
12411 			 * We're assuming the user knows what he is doing.
12412 			 * Just copy the sense information without doing
12413 			 * checks.
12414 			 */
12415 			bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12416 			      MIN(sizeof(desc->custom_sense),
12417 				  sizeof(io->scsiio.sense_data)));
12418 			io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12419 			io->scsiio.sense_len = SSD_FULL_SIZE;
12420 			io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12421 			break;
12422 		case CTL_LUN_INJ_NONE:
12423 		default:
12424 			/*
12425 			 * If this is an error injection type we don't know
12426 			 * about, clear the continuous flag (if it is set)
12427 			 * so it will get deleted below.
12428 			 */
12429 			desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12430 			break;
12431 		}
12432 		/*
12433 		 * By default, each error injection action is a one-shot
12434 		 */
12435 		if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12436 			continue;
12437 
12438 		STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12439 
12440 		free(desc, M_CTL);
12441 	}
12442 }
12443 
12444 #ifdef CTL_IO_DELAY
12445 static void
12446 ctl_datamove_timer_wakeup(void *arg)
12447 {
12448 	union ctl_io *io;
12449 
12450 	io = (union ctl_io *)arg;
12451 
12452 	ctl_datamove(io);
12453 }
12454 #endif /* CTL_IO_DELAY */
12455 
12456 void
12457 ctl_datamove(union ctl_io *io)
12458 {
12459 	void (*fe_datamove)(union ctl_io *io);
12460 
12461 	mtx_assert(&((struct ctl_softc *)CTL_SOFTC(io))->ctl_lock, MA_NOTOWNED);
12462 
12463 	CTL_DEBUG_PRINT(("ctl_datamove\n"));
12464 
12465 	/* No data transferred yet.  Frontend must update this when done. */
12466 	io->scsiio.kern_data_resid = io->scsiio.kern_data_len;
12467 
12468 #ifdef CTL_TIME_IO
12469 	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12470 		char str[256];
12471 		char path_str[64];
12472 		struct sbuf sb;
12473 
12474 		ctl_scsi_path_string(io, path_str, sizeof(path_str));
12475 		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12476 
12477 		sbuf_cat(&sb, path_str);
12478 		switch (io->io_hdr.io_type) {
12479 		case CTL_IO_SCSI:
12480 			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12481 			sbuf_printf(&sb, "\n");
12482 			sbuf_cat(&sb, path_str);
12483 			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12484 				    io->scsiio.tag_num, io->scsiio.tag_type);
12485 			break;
12486 		case CTL_IO_TASK:
12487 			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12488 				    "Tag Type: %d\n", io->taskio.task_action,
12489 				    io->taskio.tag_num, io->taskio.tag_type);
12490 			break;
12491 		default:
12492 			panic("%s: Invalid CTL I/O type %d\n",
12493 			    __func__, io->io_hdr.io_type);
12494 		}
12495 		sbuf_cat(&sb, path_str);
12496 		sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12497 			    (intmax_t)time_uptime - io->io_hdr.start_time);
12498 		sbuf_finish(&sb);
12499 		printf("%s", sbuf_data(&sb));
12500 	}
12501 #endif /* CTL_TIME_IO */
12502 
12503 #ifdef CTL_IO_DELAY
12504 	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12505 		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12506 	} else {
12507 		struct ctl_lun *lun;
12508 
12509 		lun = CTL_LUN(io);
12510 		if ((lun != NULL)
12511 		 && (lun->delay_info.datamove_delay > 0)) {
12512 
12513 			callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
12514 			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12515 			callout_reset(&io->io_hdr.delay_callout,
12516 				      lun->delay_info.datamove_delay * hz,
12517 				      ctl_datamove_timer_wakeup, io);
12518 			if (lun->delay_info.datamove_type ==
12519 			    CTL_DELAY_TYPE_ONESHOT)
12520 				lun->delay_info.datamove_delay = 0;
12521 			return;
12522 		}
12523 	}
12524 #endif
12525 
12526 	/*
12527 	 * This command has been aborted.  Set the port status, so we fail
12528 	 * the data move.
12529 	 */
12530 	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12531 		printf("ctl_datamove: tag 0x%04x on (%u:%u:%u) aborted\n",
12532 		       io->scsiio.tag_num, io->io_hdr.nexus.initid,
12533 		       io->io_hdr.nexus.targ_port,
12534 		       io->io_hdr.nexus.targ_lun);
12535 		io->io_hdr.port_status = 31337;
12536 		/*
12537 		 * Note that the backend, in this case, will get the
12538 		 * callback in its context.  In other cases it may get
12539 		 * called in the frontend's interrupt thread context.
12540 		 */
12541 		io->scsiio.be_move_done(io);
12542 		return;
12543 	}
12544 
12545 	/* Don't confuse frontend with zero length data move. */
12546 	if (io->scsiio.kern_data_len == 0) {
12547 		io->scsiio.be_move_done(io);
12548 		return;
12549 	}
12550 
12551 	fe_datamove = CTL_PORT(io)->fe_datamove;
12552 	fe_datamove(io);
12553 }
12554 
12555 static void
12556 ctl_send_datamove_done(union ctl_io *io, int have_lock)
12557 {
12558 	union ctl_ha_msg msg;
12559 #ifdef CTL_TIME_IO
12560 	struct bintime cur_bt;
12561 #endif
12562 
12563 	memset(&msg, 0, sizeof(msg));
12564 	msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12565 	msg.hdr.original_sc = io;
12566 	msg.hdr.serializing_sc = io->io_hdr.remote_io;
12567 	msg.hdr.nexus = io->io_hdr.nexus;
12568 	msg.hdr.status = io->io_hdr.status;
12569 	msg.scsi.kern_data_resid = io->scsiio.kern_data_resid;
12570 	msg.scsi.tag_num = io->scsiio.tag_num;
12571 	msg.scsi.tag_type = io->scsiio.tag_type;
12572 	msg.scsi.scsi_status = io->scsiio.scsi_status;
12573 	memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12574 	       io->scsiio.sense_len);
12575 	msg.scsi.sense_len = io->scsiio.sense_len;
12576 	msg.scsi.port_status = io->io_hdr.port_status;
12577 	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12578 	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12579 		ctl_failover_io(io, /*have_lock*/ have_lock);
12580 		return;
12581 	}
12582 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12583 	    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
12584 	    msg.scsi.sense_len, M_WAITOK);
12585 
12586 #ifdef CTL_TIME_IO
12587 	getbinuptime(&cur_bt);
12588 	bintime_sub(&cur_bt, &io->io_hdr.dma_start_bt);
12589 	bintime_add(&io->io_hdr.dma_bt, &cur_bt);
12590 #endif
12591 	io->io_hdr.num_dmas++;
12592 }
12593 
12594 /*
12595  * The DMA to the remote side is done, now we need to tell the other side
12596  * we're done so it can continue with its data movement.
12597  */
12598 static void
12599 ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12600 {
12601 	union ctl_io *io;
12602 	uint32_t i;
12603 
12604 	io = rq->context;
12605 
12606 	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12607 		printf("%s: ISC DMA write failed with error %d", __func__,
12608 		       rq->ret);
12609 		ctl_set_internal_failure(&io->scsiio,
12610 					 /*sks_valid*/ 1,
12611 					 /*retry_count*/ rq->ret);
12612 	}
12613 
12614 	ctl_dt_req_free(rq);
12615 
12616 	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12617 		free(CTL_LSGLT(io)[i].addr, M_CTL);
12618 	free(CTL_RSGL(io), M_CTL);
12619 	CTL_RSGL(io) = NULL;
12620 	CTL_LSGL(io) = NULL;
12621 
12622 	/*
12623 	 * The data is in local and remote memory, so now we need to send
12624 	 * status (good or back) back to the other side.
12625 	 */
12626 	ctl_send_datamove_done(io, /*have_lock*/ 0);
12627 }
12628 
12629 /*
12630  * We've moved the data from the host/controller into local memory.  Now we
12631  * need to push it over to the remote controller's memory.
12632  */
12633 static int
12634 ctl_datamove_remote_dm_write_cb(union ctl_io *io)
12635 {
12636 	int retval;
12637 
12638 	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
12639 					  ctl_datamove_remote_write_cb);
12640 	return (retval);
12641 }
12642 
12643 static void
12644 ctl_datamove_remote_write(union ctl_io *io)
12645 {
12646 	int retval;
12647 	void (*fe_datamove)(union ctl_io *io);
12648 
12649 	/*
12650 	 * - Get the data from the host/HBA into local memory.
12651 	 * - DMA memory from the local controller to the remote controller.
12652 	 * - Send status back to the remote controller.
12653 	 */
12654 
12655 	retval = ctl_datamove_remote_sgl_setup(io);
12656 	if (retval != 0)
12657 		return;
12658 
12659 	/* Switch the pointer over so the FETD knows what to do */
12660 	io->scsiio.kern_data_ptr = (uint8_t *)CTL_LSGL(io);
12661 
12662 	/*
12663 	 * Use a custom move done callback, since we need to send completion
12664 	 * back to the other controller, not to the backend on this side.
12665 	 */
12666 	io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
12667 
12668 	fe_datamove = CTL_PORT(io)->fe_datamove;
12669 	fe_datamove(io);
12670 }
12671 
12672 static int
12673 ctl_datamove_remote_dm_read_cb(union ctl_io *io)
12674 {
12675 	uint32_t i;
12676 
12677 	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12678 		free(CTL_LSGLT(io)[i].addr, M_CTL);
12679 	free(CTL_RSGL(io), M_CTL);
12680 	CTL_RSGL(io) = NULL;
12681 	CTL_LSGL(io) = NULL;
12682 
12683 	/*
12684 	 * The read is done, now we need to send status (good or bad) back
12685 	 * to the other side.
12686 	 */
12687 	ctl_send_datamove_done(io, /*have_lock*/ 0);
12688 
12689 	return (0);
12690 }
12691 
12692 static void
12693 ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
12694 {
12695 	union ctl_io *io;
12696 	void (*fe_datamove)(union ctl_io *io);
12697 
12698 	io = rq->context;
12699 
12700 	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12701 		printf("%s: ISC DMA read failed with error %d\n", __func__,
12702 		       rq->ret);
12703 		ctl_set_internal_failure(&io->scsiio,
12704 					 /*sks_valid*/ 1,
12705 					 /*retry_count*/ rq->ret);
12706 	}
12707 
12708 	ctl_dt_req_free(rq);
12709 
12710 	/* Switch the pointer over so the FETD knows what to do */
12711 	io->scsiio.kern_data_ptr = (uint8_t *)CTL_LSGL(io);
12712 
12713 	/*
12714 	 * Use a custom move done callback, since we need to send completion
12715 	 * back to the other controller, not to the backend on this side.
12716 	 */
12717 	io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
12718 
12719 	/* XXX KDM add checks like the ones in ctl_datamove? */
12720 
12721 	fe_datamove = CTL_PORT(io)->fe_datamove;
12722 	fe_datamove(io);
12723 }
12724 
12725 static int
12726 ctl_datamove_remote_sgl_setup(union ctl_io *io)
12727 {
12728 	struct ctl_sg_entry *local_sglist;
12729 	uint32_t len_to_go;
12730 	int retval;
12731 	int i;
12732 
12733 	retval = 0;
12734 	local_sglist = CTL_LSGL(io);
12735 	len_to_go = io->scsiio.kern_data_len;
12736 
12737 	/*
12738 	 * The difficult thing here is that the size of the various
12739 	 * S/G segments may be different than the size from the
12740 	 * remote controller.  That'll make it harder when DMAing
12741 	 * the data back to the other side.
12742 	 */
12743 	for (i = 0; len_to_go > 0; i++) {
12744 		local_sglist[i].len = MIN(len_to_go, CTL_HA_DATAMOVE_SEGMENT);
12745 		local_sglist[i].addr =
12746 		    malloc(local_sglist[i].len, M_CTL, M_WAITOK);
12747 
12748 		len_to_go -= local_sglist[i].len;
12749 	}
12750 	/*
12751 	 * Reset the number of S/G entries accordingly.  The original
12752 	 * number of S/G entries is available in rem_sg_entries.
12753 	 */
12754 	io->scsiio.kern_sg_entries = i;
12755 
12756 	return (retval);
12757 }
12758 
12759 static int
12760 ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
12761 			 ctl_ha_dt_cb callback)
12762 {
12763 	struct ctl_ha_dt_req *rq;
12764 	struct ctl_sg_entry *remote_sglist, *local_sglist;
12765 	uint32_t local_used, remote_used, total_used;
12766 	int i, j, isc_ret;
12767 
12768 	rq = ctl_dt_req_alloc();
12769 
12770 	/*
12771 	 * If we failed to allocate the request, and if the DMA didn't fail
12772 	 * anyway, set busy status.  This is just a resource allocation
12773 	 * failure.
12774 	 */
12775 	if ((rq == NULL)
12776 	 && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12777 	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS))
12778 		ctl_set_busy(&io->scsiio);
12779 
12780 	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12781 	    (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) {
12782 
12783 		if (rq != NULL)
12784 			ctl_dt_req_free(rq);
12785 
12786 		/*
12787 		 * The data move failed.  We need to return status back
12788 		 * to the other controller.  No point in trying to DMA
12789 		 * data to the remote controller.
12790 		 */
12791 
12792 		ctl_send_datamove_done(io, /*have_lock*/ 0);
12793 
12794 		return (1);
12795 	}
12796 
12797 	local_sglist = CTL_LSGL(io);
12798 	remote_sglist = CTL_RSGL(io);
12799 	local_used = 0;
12800 	remote_used = 0;
12801 	total_used = 0;
12802 
12803 	/*
12804 	 * Pull/push the data over the wire from/to the other controller.
12805 	 * This takes into account the possibility that the local and
12806 	 * remote sglists may not be identical in terms of the size of
12807 	 * the elements and the number of elements.
12808 	 *
12809 	 * One fundamental assumption here is that the length allocated for
12810 	 * both the local and remote sglists is identical.  Otherwise, we've
12811 	 * essentially got a coding error of some sort.
12812 	 */
12813 	isc_ret = CTL_HA_STATUS_SUCCESS;
12814 	for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
12815 		uint32_t cur_len;
12816 		uint8_t *tmp_ptr;
12817 
12818 		rq->command = command;
12819 		rq->context = io;
12820 
12821 		/*
12822 		 * Both pointers should be aligned.  But it is possible
12823 		 * that the allocation length is not.  They should both
12824 		 * also have enough slack left over at the end, though,
12825 		 * to round up to the next 8 byte boundary.
12826 		 */
12827 		cur_len = MIN(local_sglist[i].len - local_used,
12828 			      remote_sglist[j].len - remote_used);
12829 		rq->size = cur_len;
12830 
12831 		tmp_ptr = (uint8_t *)local_sglist[i].addr;
12832 		tmp_ptr += local_used;
12833 
12834 #if 0
12835 		/* Use physical addresses when talking to ISC hardware */
12836 		if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
12837 			/* XXX KDM use busdma */
12838 			rq->local = vtophys(tmp_ptr);
12839 		} else
12840 			rq->local = tmp_ptr;
12841 #else
12842 		KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
12843 		    ("HA does not support BUS_ADDR"));
12844 		rq->local = tmp_ptr;
12845 #endif
12846 
12847 		tmp_ptr = (uint8_t *)remote_sglist[j].addr;
12848 		tmp_ptr += remote_used;
12849 		rq->remote = tmp_ptr;
12850 
12851 		rq->callback = NULL;
12852 
12853 		local_used += cur_len;
12854 		if (local_used >= local_sglist[i].len) {
12855 			i++;
12856 			local_used = 0;
12857 		}
12858 
12859 		remote_used += cur_len;
12860 		if (remote_used >= remote_sglist[j].len) {
12861 			j++;
12862 			remote_used = 0;
12863 		}
12864 		total_used += cur_len;
12865 
12866 		if (total_used >= io->scsiio.kern_data_len)
12867 			rq->callback = callback;
12868 
12869 		isc_ret = ctl_dt_single(rq);
12870 		if (isc_ret > CTL_HA_STATUS_SUCCESS)
12871 			break;
12872 	}
12873 	if (isc_ret != CTL_HA_STATUS_WAIT) {
12874 		rq->ret = isc_ret;
12875 		callback(rq);
12876 	}
12877 
12878 	return (0);
12879 }
12880 
12881 static void
12882 ctl_datamove_remote_read(union ctl_io *io)
12883 {
12884 	int retval;
12885 	uint32_t i;
12886 
12887 	/*
12888 	 * This will send an error to the other controller in the case of a
12889 	 * failure.
12890 	 */
12891 	retval = ctl_datamove_remote_sgl_setup(io);
12892 	if (retval != 0)
12893 		return;
12894 
12895 	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
12896 					  ctl_datamove_remote_read_cb);
12897 	if (retval != 0) {
12898 		/*
12899 		 * Make sure we free memory if there was an error..  The
12900 		 * ctl_datamove_remote_xfer() function will send the
12901 		 * datamove done message, or call the callback with an
12902 		 * error if there is a problem.
12903 		 */
12904 		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12905 			free(CTL_LSGLT(io)[i].addr, M_CTL);
12906 		free(CTL_RSGL(io), M_CTL);
12907 		CTL_RSGL(io) = NULL;
12908 		CTL_LSGL(io) = NULL;
12909 	}
12910 }
12911 
12912 /*
12913  * Process a datamove request from the other controller.  This is used for
12914  * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
12915  * first.  Once that is complete, the data gets DMAed into the remote
12916  * controller's memory.  For reads, we DMA from the remote controller's
12917  * memory into our memory first, and then move it out to the FETD.
12918  */
12919 static void
12920 ctl_datamove_remote(union ctl_io *io)
12921 {
12922 
12923 	mtx_assert(&((struct ctl_softc *)CTL_SOFTC(io))->ctl_lock, MA_NOTOWNED);
12924 
12925 	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12926 		ctl_failover_io(io, /*have_lock*/ 0);
12927 		return;
12928 	}
12929 
12930 	/*
12931 	 * Note that we look for an aborted I/O here, but don't do some of
12932 	 * the other checks that ctl_datamove() normally does.
12933 	 * We don't need to run the datamove delay code, since that should
12934 	 * have been done if need be on the other controller.
12935 	 */
12936 	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12937 		printf("%s: tag 0x%04x on (%u:%u:%u) aborted\n", __func__,
12938 		       io->scsiio.tag_num, io->io_hdr.nexus.initid,
12939 		       io->io_hdr.nexus.targ_port,
12940 		       io->io_hdr.nexus.targ_lun);
12941 		io->io_hdr.port_status = 31338;
12942 		ctl_send_datamove_done(io, /*have_lock*/ 0);
12943 		return;
12944 	}
12945 
12946 	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT)
12947 		ctl_datamove_remote_write(io);
12948 	else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
12949 		ctl_datamove_remote_read(io);
12950 	else {
12951 		io->io_hdr.port_status = 31339;
12952 		ctl_send_datamove_done(io, /*have_lock*/ 0);
12953 	}
12954 }
12955 
12956 static void
12957 ctl_process_done(union ctl_io *io)
12958 {
12959 	struct ctl_softc *softc = CTL_SOFTC(io);
12960 	struct ctl_port *port = CTL_PORT(io);
12961 	struct ctl_lun *lun = CTL_LUN(io);
12962 	void (*fe_done)(union ctl_io *io);
12963 	union ctl_ha_msg msg;
12964 
12965 	CTL_DEBUG_PRINT(("ctl_process_done\n"));
12966 	fe_done = port->fe_done;
12967 
12968 #ifdef CTL_TIME_IO
12969 	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12970 		char str[256];
12971 		char path_str[64];
12972 		struct sbuf sb;
12973 
12974 		ctl_scsi_path_string(io, path_str, sizeof(path_str));
12975 		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12976 
12977 		sbuf_cat(&sb, path_str);
12978 		switch (io->io_hdr.io_type) {
12979 		case CTL_IO_SCSI:
12980 			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12981 			sbuf_printf(&sb, "\n");
12982 			sbuf_cat(&sb, path_str);
12983 			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12984 				    io->scsiio.tag_num, io->scsiio.tag_type);
12985 			break;
12986 		case CTL_IO_TASK:
12987 			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12988 				    "Tag Type: %d\n", io->taskio.task_action,
12989 				    io->taskio.tag_num, io->taskio.tag_type);
12990 			break;
12991 		default:
12992 			panic("%s: Invalid CTL I/O type %d\n",
12993 			    __func__, io->io_hdr.io_type);
12994 		}
12995 		sbuf_cat(&sb, path_str);
12996 		sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
12997 			    (intmax_t)time_uptime - io->io_hdr.start_time);
12998 		sbuf_finish(&sb);
12999 		printf("%s", sbuf_data(&sb));
13000 	}
13001 #endif /* CTL_TIME_IO */
13002 
13003 	switch (io->io_hdr.io_type) {
13004 	case CTL_IO_SCSI:
13005 		break;
13006 	case CTL_IO_TASK:
13007 		if (ctl_debug & CTL_DEBUG_INFO)
13008 			ctl_io_error_print(io, NULL);
13009 		fe_done(io);
13010 		return;
13011 	default:
13012 		panic("%s: Invalid CTL I/O type %d\n",
13013 		    __func__, io->io_hdr.io_type);
13014 	}
13015 
13016 	if (lun == NULL) {
13017 		CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13018 				 io->io_hdr.nexus.targ_mapped_lun));
13019 		goto bailout;
13020 	}
13021 
13022 	mtx_lock(&lun->lun_lock);
13023 
13024 	/*
13025 	 * Check to see if we have any informational exception and status
13026 	 * of this command can be modified to report it in form of either
13027 	 * RECOVERED ERROR or NO SENSE, depending on MRIE mode page field.
13028 	 */
13029 	if (lun->ie_reported == 0 && lun->ie_asc != 0 &&
13030 	    io->io_hdr.status == CTL_SUCCESS &&
13031 	    (io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0) {
13032 		uint8_t mrie = lun->MODE_IE.mrie;
13033 		uint8_t per = ((lun->MODE_RWER.byte3 & SMS_RWER_PER) ||
13034 		    (lun->MODE_VER.byte3 & SMS_VER_PER));
13035 		if (((mrie == SIEP_MRIE_REC_COND && per) ||
13036 		     mrie == SIEP_MRIE_REC_UNCOND ||
13037 		     mrie == SIEP_MRIE_NO_SENSE) &&
13038 		    (ctl_get_cmd_entry(&io->scsiio, NULL)->flags &
13039 		     CTL_CMD_FLAG_NO_SENSE) == 0) {
13040 			ctl_set_sense(&io->scsiio,
13041 			      /*current_error*/ 1,
13042 			      /*sense_key*/ (mrie == SIEP_MRIE_NO_SENSE) ?
13043 			        SSD_KEY_NO_SENSE : SSD_KEY_RECOVERED_ERROR,
13044 			      /*asc*/ lun->ie_asc,
13045 			      /*ascq*/ lun->ie_ascq,
13046 			      SSD_ELEM_NONE);
13047 			lun->ie_reported = 1;
13048 		}
13049 	} else if (lun->ie_reported < 0)
13050 		lun->ie_reported = 0;
13051 
13052 	/*
13053 	 * Check to see if we have any errors to inject here.  We only
13054 	 * inject errors for commands that don't already have errors set.
13055 	 */
13056 	if (!STAILQ_EMPTY(&lun->error_list) &&
13057 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS) &&
13058 	    ((io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0))
13059 		ctl_inject_error(lun, io);
13060 
13061 	/*
13062 	 * XXX KDM how do we treat commands that aren't completed
13063 	 * successfully?
13064 	 *
13065 	 * XXX KDM should we also track I/O latency?
13066 	 */
13067 	if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13068 	    io->io_hdr.io_type == CTL_IO_SCSI) {
13069 		int type;
13070 #ifdef CTL_TIME_IO
13071 		struct bintime bt;
13072 
13073 		getbinuptime(&bt);
13074 		bintime_sub(&bt, &io->io_hdr.start_bt);
13075 #endif
13076 		if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13077 		    CTL_FLAG_DATA_IN)
13078 			type = CTL_STATS_READ;
13079 		else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13080 		    CTL_FLAG_DATA_OUT)
13081 			type = CTL_STATS_WRITE;
13082 		else
13083 			type = CTL_STATS_NO_IO;
13084 
13085 		lun->stats.bytes[type] += io->scsiio.kern_total_len;
13086 		lun->stats.operations[type] ++;
13087 		lun->stats.dmas[type] += io->io_hdr.num_dmas;
13088 #ifdef CTL_TIME_IO
13089 		bintime_add(&lun->stats.dma_time[type], &io->io_hdr.dma_bt);
13090 		bintime_add(&lun->stats.time[type], &bt);
13091 #endif
13092 
13093 		mtx_lock(&port->port_lock);
13094 		port->stats.bytes[type] += io->scsiio.kern_total_len;
13095 		port->stats.operations[type] ++;
13096 		port->stats.dmas[type] += io->io_hdr.num_dmas;
13097 #ifdef CTL_TIME_IO
13098 		bintime_add(&port->stats.dma_time[type], &io->io_hdr.dma_bt);
13099 		bintime_add(&port->stats.time[type], &bt);
13100 #endif
13101 		mtx_unlock(&port->port_lock);
13102 	}
13103 
13104 	/*
13105 	 * Run through the blocked queue of this I/O and see if anything
13106 	 * can be unblocked, now that this I/O is done and will be removed.
13107 	 * We need to do it before removal to have OOA position to start.
13108 	 */
13109 	ctl_try_unblock_others(lun, io, TRUE);
13110 
13111 	/*
13112 	 * Remove this from the OOA queue.
13113 	 */
13114 	TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13115 #ifdef CTL_TIME_IO
13116 	if (TAILQ_EMPTY(&lun->ooa_queue))
13117 		lun->last_busy = getsbinuptime();
13118 #endif
13119 
13120 	/*
13121 	 * If the LUN has been invalidated, free it if there is nothing
13122 	 * left on its OOA queue.
13123 	 */
13124 	if ((lun->flags & CTL_LUN_INVALID)
13125 	 && TAILQ_EMPTY(&lun->ooa_queue)) {
13126 		mtx_unlock(&lun->lun_lock);
13127 		ctl_free_lun(lun);
13128 	} else
13129 		mtx_unlock(&lun->lun_lock);
13130 
13131 bailout:
13132 
13133 	/*
13134 	 * If this command has been aborted, make sure we set the status
13135 	 * properly.  The FETD is responsible for freeing the I/O and doing
13136 	 * whatever it needs to do to clean up its state.
13137 	 */
13138 	if (io->io_hdr.flags & CTL_FLAG_ABORT)
13139 		ctl_set_task_aborted(&io->scsiio);
13140 
13141 	/*
13142 	 * If enabled, print command error status.
13143 	 */
13144 	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS &&
13145 	    (ctl_debug & CTL_DEBUG_INFO) != 0)
13146 		ctl_io_error_print(io, NULL);
13147 
13148 	/*
13149 	 * Tell the FETD or the other shelf controller we're done with this
13150 	 * command.  Note that only SCSI commands get to this point.  Task
13151 	 * management commands are completed above.
13152 	 */
13153 	if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
13154 	    (io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)) {
13155 		memset(&msg, 0, sizeof(msg));
13156 		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13157 		msg.hdr.serializing_sc = io->io_hdr.remote_io;
13158 		msg.hdr.nexus = io->io_hdr.nexus;
13159 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13160 		    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data),
13161 		    M_WAITOK);
13162 	}
13163 
13164 	fe_done(io);
13165 }
13166 
13167 /*
13168  * Front end should call this if it doesn't do autosense.  When the request
13169  * sense comes back in from the initiator, we'll dequeue this and send it.
13170  */
13171 int
13172 ctl_queue_sense(union ctl_io *io)
13173 {
13174 	struct ctl_softc *softc = CTL_SOFTC(io);
13175 	struct ctl_port *port = CTL_PORT(io);
13176 	struct ctl_lun *lun;
13177 	struct scsi_sense_data *ps;
13178 	uint32_t initidx, p, targ_lun;
13179 
13180 	CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13181 
13182 	targ_lun = ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13183 
13184 	/*
13185 	 * LUN lookup will likely move to the ctl_work_thread() once we
13186 	 * have our new queueing infrastructure (that doesn't put things on
13187 	 * a per-LUN queue initially).  That is so that we can handle
13188 	 * things like an INQUIRY to a LUN that we don't have enabled.  We
13189 	 * can't deal with that right now.
13190 	 * If we don't have a LUN for this, just toss the sense information.
13191 	 */
13192 	mtx_lock(&softc->ctl_lock);
13193 	if (targ_lun >= ctl_max_luns ||
13194 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
13195 		mtx_unlock(&softc->ctl_lock);
13196 		goto bailout;
13197 	}
13198 	mtx_lock(&lun->lun_lock);
13199 	mtx_unlock(&softc->ctl_lock);
13200 
13201 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
13202 	p = initidx / CTL_MAX_INIT_PER_PORT;
13203 	if (lun->pending_sense[p] == NULL) {
13204 		lun->pending_sense[p] = malloc(sizeof(*ps) * CTL_MAX_INIT_PER_PORT,
13205 		    M_CTL, M_NOWAIT | M_ZERO);
13206 	}
13207 	if ((ps = lun->pending_sense[p]) != NULL) {
13208 		ps += initidx % CTL_MAX_INIT_PER_PORT;
13209 		memset(ps, 0, sizeof(*ps));
13210 		memcpy(ps, &io->scsiio.sense_data, io->scsiio.sense_len);
13211 	}
13212 	mtx_unlock(&lun->lun_lock);
13213 
13214 bailout:
13215 	ctl_free_io(io);
13216 	return (CTL_RETVAL_COMPLETE);
13217 }
13218 
13219 /*
13220  * Primary command inlet from frontend ports.  All SCSI and task I/O
13221  * requests must go through this function.
13222  */
13223 int
13224 ctl_queue(union ctl_io *io)
13225 {
13226 	struct ctl_port *port = CTL_PORT(io);
13227 
13228 	CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13229 
13230 #ifdef CTL_TIME_IO
13231 	io->io_hdr.start_time = time_uptime;
13232 	getbinuptime(&io->io_hdr.start_bt);
13233 #endif /* CTL_TIME_IO */
13234 
13235 	/* Map FE-specific LUN ID into global one. */
13236 	io->io_hdr.nexus.targ_mapped_lun =
13237 	    ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13238 
13239 	switch (io->io_hdr.io_type) {
13240 	case CTL_IO_SCSI:
13241 	case CTL_IO_TASK:
13242 		if (ctl_debug & CTL_DEBUG_CDB)
13243 			ctl_io_print(io);
13244 		ctl_enqueue_incoming(io);
13245 		break;
13246 	default:
13247 		printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13248 		return (EINVAL);
13249 	}
13250 
13251 	return (CTL_RETVAL_COMPLETE);
13252 }
13253 
13254 #ifdef CTL_IO_DELAY
13255 static void
13256 ctl_done_timer_wakeup(void *arg)
13257 {
13258 	union ctl_io *io;
13259 
13260 	io = (union ctl_io *)arg;
13261 	ctl_done(io);
13262 }
13263 #endif /* CTL_IO_DELAY */
13264 
13265 void
13266 ctl_serseq_done(union ctl_io *io)
13267 {
13268 	struct ctl_lun *lun = CTL_LUN(io);
13269 
13270 	if (lun->be_lun == NULL ||
13271 	    lun->be_lun->serseq == CTL_LUN_SERSEQ_OFF)
13272 		return;
13273 	mtx_lock(&lun->lun_lock);
13274 	io->io_hdr.flags |= CTL_FLAG_SERSEQ_DONE;
13275 	ctl_try_unblock_others(lun, io, FALSE);
13276 	mtx_unlock(&lun->lun_lock);
13277 }
13278 
13279 void
13280 ctl_done(union ctl_io *io)
13281 {
13282 
13283 	/*
13284 	 * Enable this to catch duplicate completion issues.
13285 	 */
13286 #if 0
13287 	if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13288 		printf("%s: type %d msg %d cdb %x iptl: "
13289 		       "%u:%u:%u tag 0x%04x "
13290 		       "flag %#x status %x\n",
13291 			__func__,
13292 			io->io_hdr.io_type,
13293 			io->io_hdr.msg_type,
13294 			io->scsiio.cdb[0],
13295 			io->io_hdr.nexus.initid,
13296 			io->io_hdr.nexus.targ_port,
13297 			io->io_hdr.nexus.targ_lun,
13298 			(io->io_hdr.io_type ==
13299 			CTL_IO_TASK) ?
13300 			io->taskio.tag_num :
13301 			io->scsiio.tag_num,
13302 		        io->io_hdr.flags,
13303 			io->io_hdr.status);
13304 	} else
13305 		io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13306 #endif
13307 
13308 	/*
13309 	 * This is an internal copy of an I/O, and should not go through
13310 	 * the normal done processing logic.
13311 	 */
13312 	if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13313 		return;
13314 
13315 #ifdef CTL_IO_DELAY
13316 	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13317 		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13318 	} else {
13319 		struct ctl_lun *lun = CTL_LUN(io);
13320 
13321 		if ((lun != NULL)
13322 		 && (lun->delay_info.done_delay > 0)) {
13323 
13324 			callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
13325 			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
13326 			callout_reset(&io->io_hdr.delay_callout,
13327 				      lun->delay_info.done_delay * hz,
13328 				      ctl_done_timer_wakeup, io);
13329 			if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
13330 				lun->delay_info.done_delay = 0;
13331 			return;
13332 		}
13333 	}
13334 #endif /* CTL_IO_DELAY */
13335 
13336 	ctl_enqueue_done(io);
13337 }
13338 
13339 static void
13340 ctl_work_thread(void *arg)
13341 {
13342 	struct ctl_thread *thr = (struct ctl_thread *)arg;
13343 	struct ctl_softc *softc = thr->ctl_softc;
13344 	union ctl_io *io;
13345 	int retval;
13346 
13347 	CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
13348 	thread_lock(curthread);
13349 	sched_prio(curthread, PUSER - 1);
13350 	thread_unlock(curthread);
13351 
13352 	while (!softc->shutdown) {
13353 		/*
13354 		 * We handle the queues in this order:
13355 		 * - ISC
13356 		 * - done queue (to free up resources, unblock other commands)
13357 		 * - incoming queue
13358 		 * - RtR queue
13359 		 *
13360 		 * If those queues are empty, we break out of the loop and
13361 		 * go to sleep.
13362 		 */
13363 		mtx_lock(&thr->queue_lock);
13364 		io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
13365 		if (io != NULL) {
13366 			STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
13367 			mtx_unlock(&thr->queue_lock);
13368 			ctl_handle_isc(io);
13369 			continue;
13370 		}
13371 		io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
13372 		if (io != NULL) {
13373 			STAILQ_REMOVE_HEAD(&thr->done_queue, links);
13374 			/* clear any blocked commands, call fe_done */
13375 			mtx_unlock(&thr->queue_lock);
13376 			ctl_process_done(io);
13377 			continue;
13378 		}
13379 		io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
13380 		if (io != NULL) {
13381 			STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
13382 			mtx_unlock(&thr->queue_lock);
13383 			if (io->io_hdr.io_type == CTL_IO_TASK)
13384 				ctl_run_task(io);
13385 			else
13386 				ctl_scsiio_precheck(softc, &io->scsiio);
13387 			continue;
13388 		}
13389 		io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
13390 		if (io != NULL) {
13391 			STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
13392 			mtx_unlock(&thr->queue_lock);
13393 			retval = ctl_scsiio(&io->scsiio);
13394 			if (retval != CTL_RETVAL_COMPLETE)
13395 				CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
13396 			continue;
13397 		}
13398 
13399 		/* Sleep until we have something to do. */
13400 		mtx_sleep(thr, &thr->queue_lock, PDROP, "-", 0);
13401 	}
13402 	thr->thread = NULL;
13403 	kthread_exit();
13404 }
13405 
13406 static void
13407 ctl_lun_thread(void *arg)
13408 {
13409 	struct ctl_softc *softc = (struct ctl_softc *)arg;
13410 	struct ctl_be_lun *be_lun;
13411 
13412 	CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
13413 	thread_lock(curthread);
13414 	sched_prio(curthread, PUSER - 1);
13415 	thread_unlock(curthread);
13416 
13417 	while (!softc->shutdown) {
13418 		mtx_lock(&softc->ctl_lock);
13419 		be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
13420 		if (be_lun != NULL) {
13421 			STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
13422 			mtx_unlock(&softc->ctl_lock);
13423 			ctl_create_lun(be_lun);
13424 			continue;
13425 		}
13426 
13427 		/* Sleep until we have something to do. */
13428 		mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
13429 		    PDROP, "-", 0);
13430 	}
13431 	softc->lun_thread = NULL;
13432 	kthread_exit();
13433 }
13434 
13435 static void
13436 ctl_thresh_thread(void *arg)
13437 {
13438 	struct ctl_softc *softc = (struct ctl_softc *)arg;
13439 	struct ctl_lun *lun;
13440 	struct ctl_logical_block_provisioning_page *page;
13441 	const char *attr;
13442 	union ctl_ha_msg msg;
13443 	uint64_t thres, val;
13444 	int i, e, set;
13445 
13446 	CTL_DEBUG_PRINT(("ctl_thresh_thread starting\n"));
13447 	thread_lock(curthread);
13448 	sched_prio(curthread, PUSER - 1);
13449 	thread_unlock(curthread);
13450 
13451 	while (!softc->shutdown) {
13452 		mtx_lock(&softc->ctl_lock);
13453 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
13454 			if ((lun->flags & CTL_LUN_DISABLED) ||
13455 			    (lun->flags & CTL_LUN_NO_MEDIA) ||
13456 			    lun->backend->lun_attr == NULL)
13457 				continue;
13458 			if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
13459 			    softc->ha_mode == CTL_HA_MODE_XFER)
13460 				continue;
13461 			if ((lun->MODE_RWER.byte8 & SMS_RWER_LBPERE) == 0)
13462 				continue;
13463 			e = 0;
13464 			page = &lun->MODE_LBP;
13465 			for (i = 0; i < CTL_NUM_LBP_THRESH; i++) {
13466 				if ((page->descr[i].flags & SLBPPD_ENABLED) == 0)
13467 					continue;
13468 				thres = scsi_4btoul(page->descr[i].count);
13469 				thres <<= CTL_LBP_EXPONENT;
13470 				switch (page->descr[i].resource) {
13471 				case 0x01:
13472 					attr = "blocksavail";
13473 					break;
13474 				case 0x02:
13475 					attr = "blocksused";
13476 					break;
13477 				case 0xf1:
13478 					attr = "poolblocksavail";
13479 					break;
13480 				case 0xf2:
13481 					attr = "poolblocksused";
13482 					break;
13483 				default:
13484 					continue;
13485 				}
13486 				mtx_unlock(&softc->ctl_lock); // XXX
13487 				val = lun->backend->lun_attr(
13488 				    lun->be_lun->be_lun, attr);
13489 				mtx_lock(&softc->ctl_lock);
13490 				if (val == UINT64_MAX)
13491 					continue;
13492 				if ((page->descr[i].flags & SLBPPD_ARMING_MASK)
13493 				    == SLBPPD_ARMING_INC)
13494 					e = (val >= thres);
13495 				else
13496 					e = (val <= thres);
13497 				if (e)
13498 					break;
13499 			}
13500 			mtx_lock(&lun->lun_lock);
13501 			if (e) {
13502 				scsi_u64to8b((uint8_t *)&page->descr[i] -
13503 				    (uint8_t *)page, lun->ua_tpt_info);
13504 				if (lun->lasttpt == 0 ||
13505 				    time_uptime - lun->lasttpt >= CTL_LBP_UA_PERIOD) {
13506 					lun->lasttpt = time_uptime;
13507 					ctl_est_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13508 					set = 1;
13509 				} else
13510 					set = 0;
13511 			} else {
13512 				lun->lasttpt = 0;
13513 				ctl_clr_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13514 				set = -1;
13515 			}
13516 			mtx_unlock(&lun->lun_lock);
13517 			if (set != 0 &&
13518 			    lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
13519 				/* Send msg to other side. */
13520 				bzero(&msg.ua, sizeof(msg.ua));
13521 				msg.hdr.msg_type = CTL_MSG_UA;
13522 				msg.hdr.nexus.initid = -1;
13523 				msg.hdr.nexus.targ_port = -1;
13524 				msg.hdr.nexus.targ_lun = lun->lun;
13525 				msg.hdr.nexus.targ_mapped_lun = lun->lun;
13526 				msg.ua.ua_all = 1;
13527 				msg.ua.ua_set = (set > 0);
13528 				msg.ua.ua_type = CTL_UA_THIN_PROV_THRES;
13529 				memcpy(msg.ua.ua_info, lun->ua_tpt_info, 8);
13530 				mtx_unlock(&softc->ctl_lock); // XXX
13531 				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13532 				    sizeof(msg.ua), M_WAITOK);
13533 				mtx_lock(&softc->ctl_lock);
13534 			}
13535 		}
13536 		mtx_sleep(&softc->thresh_thread, &softc->ctl_lock,
13537 		    PDROP, "-", CTL_LBP_PERIOD * hz);
13538 	}
13539 	softc->thresh_thread = NULL;
13540 	kthread_exit();
13541 }
13542 
13543 static void
13544 ctl_enqueue_incoming(union ctl_io *io)
13545 {
13546 	struct ctl_softc *softc = CTL_SOFTC(io);
13547 	struct ctl_thread *thr;
13548 	u_int idx;
13549 
13550 	idx = (io->io_hdr.nexus.targ_port * 127 +
13551 	       io->io_hdr.nexus.initid) % worker_threads;
13552 	thr = &softc->threads[idx];
13553 	mtx_lock(&thr->queue_lock);
13554 	STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
13555 	mtx_unlock(&thr->queue_lock);
13556 	wakeup(thr);
13557 }
13558 
13559 static void
13560 ctl_enqueue_rtr(union ctl_io *io)
13561 {
13562 	struct ctl_softc *softc = CTL_SOFTC(io);
13563 	struct ctl_thread *thr;
13564 
13565 	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13566 	mtx_lock(&thr->queue_lock);
13567 	STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
13568 	mtx_unlock(&thr->queue_lock);
13569 	wakeup(thr);
13570 }
13571 
13572 static void
13573 ctl_enqueue_done(union ctl_io *io)
13574 {
13575 	struct ctl_softc *softc = CTL_SOFTC(io);
13576 	struct ctl_thread *thr;
13577 
13578 	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13579 	mtx_lock(&thr->queue_lock);
13580 	STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
13581 	mtx_unlock(&thr->queue_lock);
13582 	wakeup(thr);
13583 }
13584 
13585 static void
13586 ctl_enqueue_isc(union ctl_io *io)
13587 {
13588 	struct ctl_softc *softc = CTL_SOFTC(io);
13589 	struct ctl_thread *thr;
13590 
13591 	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13592 	mtx_lock(&thr->queue_lock);
13593 	STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
13594 	mtx_unlock(&thr->queue_lock);
13595 	wakeup(thr);
13596 }
13597 
13598 /*
13599  *  vim: ts=8
13600  */
13601