xref: /freebsd/sys/cam/ctl/ctl.c (revision 5ac01ce026aa871e24065f931b5b5c36024c96f9)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2003-2009 Silicon Graphics International Corp.
5  * Copyright (c) 2012 The FreeBSD Foundation
6  * Copyright (c) 2014-2017 Alexander Motin <mav@FreeBSD.org>
7  * Copyright (c) 2017 Jakub Wojciech Klama <jceel@FreeBSD.org>
8  * Copyright (c) 2018 Marcelo Araujo <araujo@FreeBSD.org>
9  * All rights reserved.
10  *
11  * Portions of this software were developed by Edward Tomasz Napierala
12  * under sponsorship from the FreeBSD Foundation.
13  *
14  * Redistribution and use in source and binary forms, with or without
15  * modification, are permitted provided that the following conditions
16  * are met:
17  * 1. Redistributions of source code must retain the above copyright
18  *    notice, this list of conditions, and the following disclaimer,
19  *    without modification.
20  * 2. Redistributions in binary form must reproduce at minimum a disclaimer
21  *    substantially similar to the "NO WARRANTY" disclaimer below
22  *    ("Disclaimer") and any redistribution must be conditioned upon
23  *    including a substantially similar Disclaimer requirement for further
24  *    binary redistribution.
25  *
26  * NO WARRANTY
27  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
28  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
29  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
30  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
31  * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
32  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
33  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
34  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
35  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
36  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
37  * POSSIBILITY OF SUCH DAMAGES.
38  *
39  * $Id$
40  */
41 /*
42  * CAM Target Layer, a SCSI device emulation subsystem.
43  *
44  * Author: Ken Merry <ken@FreeBSD.org>
45  */
46 
47 #include <sys/cdefs.h>
48 __FBSDID("$FreeBSD$");
49 
50 #include <sys/param.h>
51 #include <sys/systm.h>
52 #include <sys/ctype.h>
53 #include <sys/kernel.h>
54 #include <sys/types.h>
55 #include <sys/kthread.h>
56 #include <sys/bio.h>
57 #include <sys/fcntl.h>
58 #include <sys/lock.h>
59 #include <sys/module.h>
60 #include <sys/mutex.h>
61 #include <sys/condvar.h>
62 #include <sys/malloc.h>
63 #include <sys/conf.h>
64 #include <sys/ioccom.h>
65 #include <sys/queue.h>
66 #include <sys/sbuf.h>
67 #include <sys/smp.h>
68 #include <sys/endian.h>
69 #include <sys/proc.h>
70 #include <sys/sched.h>
71 #include <sys/sysctl.h>
72 #include <sys/nv.h>
73 #include <sys/dnv.h>
74 #include <vm/uma.h>
75 
76 #include <cam/cam.h>
77 #include <cam/scsi/scsi_all.h>
78 #include <cam/scsi/scsi_cd.h>
79 #include <cam/scsi/scsi_da.h>
80 #include <cam/ctl/ctl_io.h>
81 #include <cam/ctl/ctl.h>
82 #include <cam/ctl/ctl_frontend.h>
83 #include <cam/ctl/ctl_util.h>
84 #include <cam/ctl/ctl_backend.h>
85 #include <cam/ctl/ctl_ioctl.h>
86 #include <cam/ctl/ctl_ha.h>
87 #include <cam/ctl/ctl_private.h>
88 #include <cam/ctl/ctl_debug.h>
89 #include <cam/ctl/ctl_scsi_all.h>
90 #include <cam/ctl/ctl_error.h>
91 
92 struct ctl_softc *control_softc = NULL;
93 
94 /*
95  * Template mode pages.
96  */
97 
98 /*
99  * Note that these are default values only.  The actual values will be
100  * filled in when the user does a mode sense.
101  */
102 const static struct scsi_da_rw_recovery_page rw_er_page_default = {
103 	/*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
104 	/*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
105 	/*byte3*/SMS_RWER_AWRE|SMS_RWER_ARRE,
106 	/*read_retry_count*/0,
107 	/*correction_span*/0,
108 	/*head_offset_count*/0,
109 	/*data_strobe_offset_cnt*/0,
110 	/*byte8*/SMS_RWER_LBPERE,
111 	/*write_retry_count*/0,
112 	/*reserved2*/0,
113 	/*recovery_time_limit*/{0, 0},
114 };
115 
116 const static struct scsi_da_rw_recovery_page rw_er_page_changeable = {
117 	/*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
118 	/*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
119 	/*byte3*/SMS_RWER_PER,
120 	/*read_retry_count*/0,
121 	/*correction_span*/0,
122 	/*head_offset_count*/0,
123 	/*data_strobe_offset_cnt*/0,
124 	/*byte8*/SMS_RWER_LBPERE,
125 	/*write_retry_count*/0,
126 	/*reserved2*/0,
127 	/*recovery_time_limit*/{0, 0},
128 };
129 
130 const static struct scsi_format_page format_page_default = {
131 	/*page_code*/SMS_FORMAT_DEVICE_PAGE,
132 	/*page_length*/sizeof(struct scsi_format_page) - 2,
133 	/*tracks_per_zone*/ {0, 0},
134 	/*alt_sectors_per_zone*/ {0, 0},
135 	/*alt_tracks_per_zone*/ {0, 0},
136 	/*alt_tracks_per_lun*/ {0, 0},
137 	/*sectors_per_track*/ {(CTL_DEFAULT_SECTORS_PER_TRACK >> 8) & 0xff,
138 			        CTL_DEFAULT_SECTORS_PER_TRACK & 0xff},
139 	/*bytes_per_sector*/ {0, 0},
140 	/*interleave*/ {0, 0},
141 	/*track_skew*/ {0, 0},
142 	/*cylinder_skew*/ {0, 0},
143 	/*flags*/ SFP_HSEC,
144 	/*reserved*/ {0, 0, 0}
145 };
146 
147 const static struct scsi_format_page format_page_changeable = {
148 	/*page_code*/SMS_FORMAT_DEVICE_PAGE,
149 	/*page_length*/sizeof(struct scsi_format_page) - 2,
150 	/*tracks_per_zone*/ {0, 0},
151 	/*alt_sectors_per_zone*/ {0, 0},
152 	/*alt_tracks_per_zone*/ {0, 0},
153 	/*alt_tracks_per_lun*/ {0, 0},
154 	/*sectors_per_track*/ {0, 0},
155 	/*bytes_per_sector*/ {0, 0},
156 	/*interleave*/ {0, 0},
157 	/*track_skew*/ {0, 0},
158 	/*cylinder_skew*/ {0, 0},
159 	/*flags*/ 0,
160 	/*reserved*/ {0, 0, 0}
161 };
162 
163 const static struct scsi_rigid_disk_page rigid_disk_page_default = {
164 	/*page_code*/SMS_RIGID_DISK_PAGE,
165 	/*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
166 	/*cylinders*/ {0, 0, 0},
167 	/*heads*/ CTL_DEFAULT_HEADS,
168 	/*start_write_precomp*/ {0, 0, 0},
169 	/*start_reduced_current*/ {0, 0, 0},
170 	/*step_rate*/ {0, 0},
171 	/*landing_zone_cylinder*/ {0, 0, 0},
172 	/*rpl*/ SRDP_RPL_DISABLED,
173 	/*rotational_offset*/ 0,
174 	/*reserved1*/ 0,
175 	/*rotation_rate*/ {(CTL_DEFAULT_ROTATION_RATE >> 8) & 0xff,
176 			   CTL_DEFAULT_ROTATION_RATE & 0xff},
177 	/*reserved2*/ {0, 0}
178 };
179 
180 const static struct scsi_rigid_disk_page rigid_disk_page_changeable = {
181 	/*page_code*/SMS_RIGID_DISK_PAGE,
182 	/*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
183 	/*cylinders*/ {0, 0, 0},
184 	/*heads*/ 0,
185 	/*start_write_precomp*/ {0, 0, 0},
186 	/*start_reduced_current*/ {0, 0, 0},
187 	/*step_rate*/ {0, 0},
188 	/*landing_zone_cylinder*/ {0, 0, 0},
189 	/*rpl*/ 0,
190 	/*rotational_offset*/ 0,
191 	/*reserved1*/ 0,
192 	/*rotation_rate*/ {0, 0},
193 	/*reserved2*/ {0, 0}
194 };
195 
196 const static struct scsi_da_verify_recovery_page verify_er_page_default = {
197 	/*page_code*/SMS_VERIFY_ERROR_RECOVERY_PAGE,
198 	/*page_length*/sizeof(struct scsi_da_verify_recovery_page) - 2,
199 	/*byte3*/0,
200 	/*read_retry_count*/0,
201 	/*reserved*/{ 0, 0, 0, 0, 0, 0 },
202 	/*recovery_time_limit*/{0, 0},
203 };
204 
205 const static struct scsi_da_verify_recovery_page verify_er_page_changeable = {
206 	/*page_code*/SMS_VERIFY_ERROR_RECOVERY_PAGE,
207 	/*page_length*/sizeof(struct scsi_da_verify_recovery_page) - 2,
208 	/*byte3*/SMS_VER_PER,
209 	/*read_retry_count*/0,
210 	/*reserved*/{ 0, 0, 0, 0, 0, 0 },
211 	/*recovery_time_limit*/{0, 0},
212 };
213 
214 const static struct scsi_caching_page caching_page_default = {
215 	/*page_code*/SMS_CACHING_PAGE,
216 	/*page_length*/sizeof(struct scsi_caching_page) - 2,
217 	/*flags1*/ SCP_DISC | SCP_WCE,
218 	/*ret_priority*/ 0,
219 	/*disable_pf_transfer_len*/ {0xff, 0xff},
220 	/*min_prefetch*/ {0, 0},
221 	/*max_prefetch*/ {0xff, 0xff},
222 	/*max_pf_ceiling*/ {0xff, 0xff},
223 	/*flags2*/ 0,
224 	/*cache_segments*/ 0,
225 	/*cache_seg_size*/ {0, 0},
226 	/*reserved*/ 0,
227 	/*non_cache_seg_size*/ {0, 0, 0}
228 };
229 
230 const static struct scsi_caching_page caching_page_changeable = {
231 	/*page_code*/SMS_CACHING_PAGE,
232 	/*page_length*/sizeof(struct scsi_caching_page) - 2,
233 	/*flags1*/ SCP_WCE | SCP_RCD,
234 	/*ret_priority*/ 0,
235 	/*disable_pf_transfer_len*/ {0, 0},
236 	/*min_prefetch*/ {0, 0},
237 	/*max_prefetch*/ {0, 0},
238 	/*max_pf_ceiling*/ {0, 0},
239 	/*flags2*/ 0,
240 	/*cache_segments*/ 0,
241 	/*cache_seg_size*/ {0, 0},
242 	/*reserved*/ 0,
243 	/*non_cache_seg_size*/ {0, 0, 0}
244 };
245 
246 const static struct scsi_control_page control_page_default = {
247 	/*page_code*/SMS_CONTROL_MODE_PAGE,
248 	/*page_length*/sizeof(struct scsi_control_page) - 2,
249 	/*rlec*/0,
250 	/*queue_flags*/SCP_QUEUE_ALG_RESTRICTED,
251 	/*eca_and_aen*/0,
252 	/*flags4*/SCP_TAS,
253 	/*aen_holdoff_period*/{0, 0},
254 	/*busy_timeout_period*/{0, 0},
255 	/*extended_selftest_completion_time*/{0, 0}
256 };
257 
258 const static struct scsi_control_page control_page_changeable = {
259 	/*page_code*/SMS_CONTROL_MODE_PAGE,
260 	/*page_length*/sizeof(struct scsi_control_page) - 2,
261 	/*rlec*/SCP_DSENSE,
262 	/*queue_flags*/SCP_QUEUE_ALG_MASK | SCP_NUAR,
263 	/*eca_and_aen*/SCP_SWP,
264 	/*flags4*/0,
265 	/*aen_holdoff_period*/{0, 0},
266 	/*busy_timeout_period*/{0, 0},
267 	/*extended_selftest_completion_time*/{0, 0}
268 };
269 
270 #define CTL_CEM_LEN	(sizeof(struct scsi_control_ext_page) - 4)
271 
272 const static struct scsi_control_ext_page control_ext_page_default = {
273 	/*page_code*/SMS_CONTROL_MODE_PAGE | SMPH_SPF,
274 	/*subpage_code*/0x01,
275 	/*page_length*/{CTL_CEM_LEN >> 8, CTL_CEM_LEN},
276 	/*flags*/0,
277 	/*prio*/0,
278 	/*max_sense*/0
279 };
280 
281 const static struct scsi_control_ext_page control_ext_page_changeable = {
282 	/*page_code*/SMS_CONTROL_MODE_PAGE | SMPH_SPF,
283 	/*subpage_code*/0x01,
284 	/*page_length*/{CTL_CEM_LEN >> 8, CTL_CEM_LEN},
285 	/*flags*/0,
286 	/*prio*/0,
287 	/*max_sense*/0xff
288 };
289 
290 const static struct scsi_info_exceptions_page ie_page_default = {
291 	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
292 	/*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
293 	/*info_flags*/SIEP_FLAGS_EWASC,
294 	/*mrie*/SIEP_MRIE_NO,
295 	/*interval_timer*/{0, 0, 0, 0},
296 	/*report_count*/{0, 0, 0, 1}
297 };
298 
299 const static struct scsi_info_exceptions_page ie_page_changeable = {
300 	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
301 	/*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
302 	/*info_flags*/SIEP_FLAGS_EWASC | SIEP_FLAGS_DEXCPT | SIEP_FLAGS_TEST |
303 	    SIEP_FLAGS_LOGERR,
304 	/*mrie*/0x0f,
305 	/*interval_timer*/{0xff, 0xff, 0xff, 0xff},
306 	/*report_count*/{0xff, 0xff, 0xff, 0xff}
307 };
308 
309 #define CTL_LBPM_LEN	(sizeof(struct ctl_logical_block_provisioning_page) - 4)
310 
311 const static struct ctl_logical_block_provisioning_page lbp_page_default = {{
312 	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
313 	/*subpage_code*/0x02,
314 	/*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
315 	/*flags*/0,
316 	/*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
317 	/*descr*/{}},
318 	{{/*flags*/0,
319 	  /*resource*/0x01,
320 	  /*reserved*/{0, 0},
321 	  /*count*/{0, 0, 0, 0}},
322 	 {/*flags*/0,
323 	  /*resource*/0x02,
324 	  /*reserved*/{0, 0},
325 	  /*count*/{0, 0, 0, 0}},
326 	 {/*flags*/0,
327 	  /*resource*/0xf1,
328 	  /*reserved*/{0, 0},
329 	  /*count*/{0, 0, 0, 0}},
330 	 {/*flags*/0,
331 	  /*resource*/0xf2,
332 	  /*reserved*/{0, 0},
333 	  /*count*/{0, 0, 0, 0}}
334 	}
335 };
336 
337 const static struct ctl_logical_block_provisioning_page lbp_page_changeable = {{
338 	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
339 	/*subpage_code*/0x02,
340 	/*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
341 	/*flags*/SLBPP_SITUA,
342 	/*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
343 	/*descr*/{}},
344 	{{/*flags*/0,
345 	  /*resource*/0,
346 	  /*reserved*/{0, 0},
347 	  /*count*/{0, 0, 0, 0}},
348 	 {/*flags*/0,
349 	  /*resource*/0,
350 	  /*reserved*/{0, 0},
351 	  /*count*/{0, 0, 0, 0}},
352 	 {/*flags*/0,
353 	  /*resource*/0,
354 	  /*reserved*/{0, 0},
355 	  /*count*/{0, 0, 0, 0}},
356 	 {/*flags*/0,
357 	  /*resource*/0,
358 	  /*reserved*/{0, 0},
359 	  /*count*/{0, 0, 0, 0}}
360 	}
361 };
362 
363 const static struct scsi_cddvd_capabilities_page cddvd_page_default = {
364 	/*page_code*/SMS_CDDVD_CAPS_PAGE,
365 	/*page_length*/sizeof(struct scsi_cddvd_capabilities_page) - 2,
366 	/*caps1*/0x3f,
367 	/*caps2*/0x00,
368 	/*caps3*/0xf0,
369 	/*caps4*/0x00,
370 	/*caps5*/0x29,
371 	/*caps6*/0x00,
372 	/*obsolete*/{0, 0},
373 	/*nvol_levels*/{0, 0},
374 	/*buffer_size*/{8, 0},
375 	/*obsolete2*/{0, 0},
376 	/*reserved*/0,
377 	/*digital*/0,
378 	/*obsolete3*/0,
379 	/*copy_management*/0,
380 	/*reserved2*/0,
381 	/*rotation_control*/0,
382 	/*cur_write_speed*/0,
383 	/*num_speed_descr*/0,
384 };
385 
386 const static struct scsi_cddvd_capabilities_page cddvd_page_changeable = {
387 	/*page_code*/SMS_CDDVD_CAPS_PAGE,
388 	/*page_length*/sizeof(struct scsi_cddvd_capabilities_page) - 2,
389 	/*caps1*/0,
390 	/*caps2*/0,
391 	/*caps3*/0,
392 	/*caps4*/0,
393 	/*caps5*/0,
394 	/*caps6*/0,
395 	/*obsolete*/{0, 0},
396 	/*nvol_levels*/{0, 0},
397 	/*buffer_size*/{0, 0},
398 	/*obsolete2*/{0, 0},
399 	/*reserved*/0,
400 	/*digital*/0,
401 	/*obsolete3*/0,
402 	/*copy_management*/0,
403 	/*reserved2*/0,
404 	/*rotation_control*/0,
405 	/*cur_write_speed*/0,
406 	/*num_speed_descr*/0,
407 };
408 
409 SYSCTL_NODE(_kern_cam, OID_AUTO, ctl, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
410     "CAM Target Layer");
411 static int worker_threads = -1;
412 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, worker_threads, CTLFLAG_RDTUN,
413     &worker_threads, 1, "Number of worker threads");
414 static int ctl_debug = CTL_DEBUG_NONE;
415 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, debug, CTLFLAG_RWTUN,
416     &ctl_debug, 0, "Enabled debug flags");
417 static int ctl_lun_map_size = 1024;
418 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, lun_map_size, CTLFLAG_RWTUN,
419     &ctl_lun_map_size, 0, "Size of per-port LUN map (max LUN + 1)");
420 #ifdef  CTL_TIME_IO
421 static int ctl_time_io_secs = CTL_TIME_IO_DEFAULT_SECS;
422 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, time_io_secs, CTLFLAG_RWTUN,
423     &ctl_time_io_secs, 0, "Log requests taking more seconds");
424 #endif
425 
426 /*
427  * Maximum number of LUNs we support.  MUST be a power of 2.
428  */
429 #define	CTL_DEFAULT_MAX_LUNS	1024
430 static int ctl_max_luns = CTL_DEFAULT_MAX_LUNS;
431 TUNABLE_INT("kern.cam.ctl.max_luns", &ctl_max_luns);
432 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, max_luns, CTLFLAG_RDTUN,
433     &ctl_max_luns, CTL_DEFAULT_MAX_LUNS, "Maximum number of LUNs");
434 
435 /*
436  * Maximum number of ports registered at one time.
437  */
438 #define	CTL_DEFAULT_MAX_PORTS		256
439 static int ctl_max_ports = CTL_DEFAULT_MAX_PORTS;
440 TUNABLE_INT("kern.cam.ctl.max_ports", &ctl_max_ports);
441 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, max_ports, CTLFLAG_RDTUN,
442     &ctl_max_ports, CTL_DEFAULT_MAX_LUNS, "Maximum number of ports");
443 
444 /*
445  * Maximum number of initiators we support.
446  */
447 #define	CTL_MAX_INITIATORS	(CTL_MAX_INIT_PER_PORT * ctl_max_ports)
448 
449 /*
450  * Supported pages (0x00), Serial number (0x80), Device ID (0x83),
451  * Extended INQUIRY Data (0x86), Mode Page Policy (0x87),
452  * SCSI Ports (0x88), Third-party Copy (0x8F), SCSI Feature Sets (0x92),
453  * Block limits (0xB0), Block Device Characteristics (0xB1) and
454  * Logical Block Provisioning (0xB2)
455  */
456 #define SCSI_EVPD_NUM_SUPPORTED_PAGES	11
457 
458 static void ctl_isc_event_handler(ctl_ha_channel chanel, ctl_ha_event event,
459 				  int param);
460 static void ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest);
461 static void ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest);
462 static int ctl_init(void);
463 static int ctl_shutdown(void);
464 static int ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td);
465 static int ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td);
466 static void ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio);
467 static void ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
468 			      struct ctl_ooa *ooa_hdr,
469 			      struct ctl_ooa_entry *kern_entries);
470 static int ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
471 		     struct thread *td);
472 static int ctl_enable_lun(struct ctl_lun *lun);
473 static int ctl_disable_lun(struct ctl_lun *lun);
474 static int ctl_free_lun(struct ctl_lun *lun);
475 
476 static int ctl_do_mode_select(union ctl_io *io);
477 static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
478 			   uint64_t res_key, uint64_t sa_res_key,
479 			   uint8_t type, uint32_t residx,
480 			   struct ctl_scsiio *ctsio,
481 			   struct scsi_per_res_out *cdb,
482 			   struct scsi_per_res_out_parms* param);
483 static void ctl_pro_preempt_other(struct ctl_lun *lun,
484 				  union ctl_ha_msg *msg);
485 static void ctl_hndl_per_res_out_on_other_sc(union ctl_io *io);
486 static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
487 static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
488 static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
489 static int ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len);
490 static int ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len);
491 static int ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio,
492 					 int alloc_len);
493 static int ctl_inquiry_evpd_sfs(struct ctl_scsiio *ctsio, int alloc_len);
494 static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
495 					 int alloc_len);
496 static int ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len);
497 static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
498 static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
499 static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
500 static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len);
501 static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2,
502     bool seq);
503 static ctl_action ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2);
504 static ctl_action ctl_check_for_blockage(struct ctl_lun *lun,
505     union ctl_io *pending_io, union ctl_io *ooa_io);
506 static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
507 				union ctl_io **starting_io);
508 static void ctl_try_unblock_io(struct ctl_lun *lun, union ctl_io *io,
509     bool skip);
510 static void ctl_try_unblock_others(struct ctl_lun *lun, union ctl_io *io,
511     bool skip);
512 static int ctl_scsiio_lun_check(struct ctl_lun *lun,
513 				const struct ctl_cmd_entry *entry,
514 				struct ctl_scsiio *ctsio);
515 static void ctl_failover_lun(union ctl_io *io);
516 static int ctl_scsiio_precheck(struct ctl_softc *ctl_softc,
517 			       struct ctl_scsiio *ctsio);
518 static int ctl_scsiio(struct ctl_scsiio *ctsio);
519 
520 static int ctl_target_reset(union ctl_io *io);
521 static void ctl_do_lun_reset(struct ctl_lun *lun, uint32_t initidx,
522 			 ctl_ua_type ua_type);
523 static int ctl_lun_reset(union ctl_io *io);
524 static int ctl_abort_task(union ctl_io *io);
525 static int ctl_abort_task_set(union ctl_io *io);
526 static int ctl_query_task(union ctl_io *io, int task_set);
527 static void ctl_i_t_nexus_loss(struct ctl_softc *softc, uint32_t initidx,
528 			      ctl_ua_type ua_type);
529 static int ctl_i_t_nexus_reset(union ctl_io *io);
530 static int ctl_query_async_event(union ctl_io *io);
531 static void ctl_run_task(union ctl_io *io);
532 #ifdef CTL_IO_DELAY
533 static void ctl_datamove_timer_wakeup(void *arg);
534 static void ctl_done_timer_wakeup(void *arg);
535 #endif /* CTL_IO_DELAY */
536 
537 static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
538 static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
539 static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
540 static void ctl_datamove_remote_write(union ctl_io *io);
541 static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
542 static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
543 static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
544 static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
545 				    ctl_ha_dt_cb callback);
546 static void ctl_datamove_remote_read(union ctl_io *io);
547 static void ctl_datamove_remote(union ctl_io *io);
548 static void ctl_process_done(union ctl_io *io);
549 static void ctl_thresh_thread(void *arg);
550 static void ctl_work_thread(void *arg);
551 static void ctl_enqueue_incoming(union ctl_io *io);
552 static void ctl_enqueue_rtr(union ctl_io *io);
553 static void ctl_enqueue_done(union ctl_io *io);
554 static void ctl_enqueue_isc(union ctl_io *io);
555 static const struct ctl_cmd_entry *
556     ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa);
557 static const struct ctl_cmd_entry *
558     ctl_validate_command(struct ctl_scsiio *ctsio);
559 static int ctl_cmd_applicable(uint8_t lun_type,
560     const struct ctl_cmd_entry *entry);
561 static int ctl_ha_init(void);
562 static int ctl_ha_shutdown(void);
563 
564 static uint64_t ctl_get_prkey(struct ctl_lun *lun, uint32_t residx);
565 static void ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx);
566 static void ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx);
567 static void ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key);
568 
569 /*
570  * Load the serialization table.  This isn't very pretty, but is probably
571  * the easiest way to do it.
572  */
573 #include "ctl_ser_table.c"
574 
575 /*
576  * We only need to define open, close and ioctl routines for this driver.
577  */
578 static struct cdevsw ctl_cdevsw = {
579 	.d_version =	D_VERSION,
580 	.d_flags =	0,
581 	.d_open =	ctl_open,
582 	.d_close =	ctl_close,
583 	.d_ioctl =	ctl_ioctl,
584 	.d_name =	"ctl",
585 };
586 
587 
588 MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
589 
590 static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
591 
592 static moduledata_t ctl_moduledata = {
593 	"ctl",
594 	ctl_module_event_handler,
595 	NULL
596 };
597 
598 DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
599 MODULE_VERSION(ctl, 1);
600 
601 static struct ctl_frontend ha_frontend =
602 {
603 	.name = "ha",
604 	.init = ctl_ha_init,
605 	.shutdown = ctl_ha_shutdown,
606 };
607 
608 static int
609 ctl_ha_init(void)
610 {
611 	struct ctl_softc *softc = control_softc;
612 
613 	if (ctl_pool_create(softc, "othersc", CTL_POOL_ENTRIES_OTHER_SC,
614 	                    &softc->othersc_pool) != 0)
615 		return (ENOMEM);
616 	if (ctl_ha_msg_init(softc) != CTL_HA_STATUS_SUCCESS) {
617 		ctl_pool_free(softc->othersc_pool);
618 		return (EIO);
619 	}
620 	if (ctl_ha_msg_register(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
621 	    != CTL_HA_STATUS_SUCCESS) {
622 		ctl_ha_msg_destroy(softc);
623 		ctl_pool_free(softc->othersc_pool);
624 		return (EIO);
625 	}
626 	return (0);
627 };
628 
629 static int
630 ctl_ha_shutdown(void)
631 {
632 	struct ctl_softc *softc = control_softc;
633 	struct ctl_port *port;
634 
635 	ctl_ha_msg_shutdown(softc);
636 	if (ctl_ha_msg_deregister(CTL_HA_CHAN_CTL) != CTL_HA_STATUS_SUCCESS)
637 		return (EIO);
638 	if (ctl_ha_msg_destroy(softc) != CTL_HA_STATUS_SUCCESS)
639 		return (EIO);
640 	ctl_pool_free(softc->othersc_pool);
641 	while ((port = STAILQ_FIRST(&ha_frontend.port_list)) != NULL) {
642 		ctl_port_deregister(port);
643 		free(port->port_name, M_CTL);
644 		free(port, M_CTL);
645 	}
646 	return (0);
647 };
648 
649 static void
650 ctl_ha_datamove(union ctl_io *io)
651 {
652 	struct ctl_lun *lun = CTL_LUN(io);
653 	struct ctl_sg_entry *sgl;
654 	union ctl_ha_msg msg;
655 	uint32_t sg_entries_sent;
656 	int do_sg_copy, i, j;
657 
658 	memset(&msg.dt, 0, sizeof(msg.dt));
659 	msg.hdr.msg_type = CTL_MSG_DATAMOVE;
660 	msg.hdr.original_sc = io->io_hdr.remote_io;
661 	msg.hdr.serializing_sc = io;
662 	msg.hdr.nexus = io->io_hdr.nexus;
663 	msg.hdr.status = io->io_hdr.status;
664 	msg.dt.flags = io->io_hdr.flags;
665 
666 	/*
667 	 * We convert everything into a S/G list here.  We can't
668 	 * pass by reference, only by value between controllers.
669 	 * So we can't pass a pointer to the S/G list, only as many
670 	 * S/G entries as we can fit in here.  If it's possible for
671 	 * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
672 	 * then we need to break this up into multiple transfers.
673 	 */
674 	if (io->scsiio.kern_sg_entries == 0) {
675 		msg.dt.kern_sg_entries = 1;
676 #if 0
677 		if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
678 			msg.dt.sg_list[0].addr = io->scsiio.kern_data_ptr;
679 		} else {
680 			/* XXX KDM use busdma here! */
681 			msg.dt.sg_list[0].addr =
682 			    (void *)vtophys(io->scsiio.kern_data_ptr);
683 		}
684 #else
685 		KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
686 		    ("HA does not support BUS_ADDR"));
687 		msg.dt.sg_list[0].addr = io->scsiio.kern_data_ptr;
688 #endif
689 		msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
690 		do_sg_copy = 0;
691 	} else {
692 		msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
693 		do_sg_copy = 1;
694 	}
695 
696 	msg.dt.kern_data_len = io->scsiio.kern_data_len;
697 	msg.dt.kern_total_len = io->scsiio.kern_total_len;
698 	msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
699 	msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
700 	msg.dt.sg_sequence = 0;
701 
702 	/*
703 	 * Loop until we've sent all of the S/G entries.  On the
704 	 * other end, we'll recompose these S/G entries into one
705 	 * contiguous list before processing.
706 	 */
707 	for (sg_entries_sent = 0; sg_entries_sent < msg.dt.kern_sg_entries;
708 	    msg.dt.sg_sequence++) {
709 		msg.dt.cur_sg_entries = MIN((sizeof(msg.dt.sg_list) /
710 		    sizeof(msg.dt.sg_list[0])),
711 		    msg.dt.kern_sg_entries - sg_entries_sent);
712 		if (do_sg_copy != 0) {
713 			sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
714 			for (i = sg_entries_sent, j = 0;
715 			     i < msg.dt.cur_sg_entries; i++, j++) {
716 #if 0
717 				if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
718 					msg.dt.sg_list[j].addr = sgl[i].addr;
719 				} else {
720 					/* XXX KDM use busdma here! */
721 					msg.dt.sg_list[j].addr =
722 					    (void *)vtophys(sgl[i].addr);
723 				}
724 #else
725 				KASSERT((io->io_hdr.flags &
726 				    CTL_FLAG_BUS_ADDR) == 0,
727 				    ("HA does not support BUS_ADDR"));
728 				msg.dt.sg_list[j].addr = sgl[i].addr;
729 #endif
730 				msg.dt.sg_list[j].len = sgl[i].len;
731 			}
732 		}
733 
734 		sg_entries_sent += msg.dt.cur_sg_entries;
735 		msg.dt.sg_last = (sg_entries_sent >= msg.dt.kern_sg_entries);
736 		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
737 		    sizeof(msg.dt) - sizeof(msg.dt.sg_list) +
738 		    sizeof(struct ctl_sg_entry) * msg.dt.cur_sg_entries,
739 		    M_WAITOK) > CTL_HA_STATUS_SUCCESS) {
740 			io->io_hdr.port_status = 31341;
741 			io->scsiio.be_move_done(io);
742 			return;
743 		}
744 		msg.dt.sent_sg_entries = sg_entries_sent;
745 	}
746 
747 	/*
748 	 * Officially handover the request from us to peer.
749 	 * If failover has just happened, then we must return error.
750 	 * If failover happen just after, then it is not our problem.
751 	 */
752 	if (lun)
753 		mtx_lock(&lun->lun_lock);
754 	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
755 		if (lun)
756 			mtx_unlock(&lun->lun_lock);
757 		io->io_hdr.port_status = 31342;
758 		io->scsiio.be_move_done(io);
759 		return;
760 	}
761 	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
762 	io->io_hdr.flags |= CTL_FLAG_DMA_INPROG;
763 	if (lun)
764 		mtx_unlock(&lun->lun_lock);
765 }
766 
767 static void
768 ctl_ha_done(union ctl_io *io)
769 {
770 	union ctl_ha_msg msg;
771 
772 	if (io->io_hdr.io_type == CTL_IO_SCSI) {
773 		memset(&msg, 0, sizeof(msg));
774 		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
775 		msg.hdr.original_sc = io->io_hdr.remote_io;
776 		msg.hdr.nexus = io->io_hdr.nexus;
777 		msg.hdr.status = io->io_hdr.status;
778 		msg.scsi.scsi_status = io->scsiio.scsi_status;
779 		msg.scsi.tag_num = io->scsiio.tag_num;
780 		msg.scsi.tag_type = io->scsiio.tag_type;
781 		msg.scsi.sense_len = io->scsiio.sense_len;
782 		memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
783 		    io->scsiio.sense_len);
784 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
785 		    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
786 		    msg.scsi.sense_len, M_WAITOK);
787 	}
788 	ctl_free_io(io);
789 }
790 
791 static void
792 ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
793 			    union ctl_ha_msg *msg_info)
794 {
795 	struct ctl_scsiio *ctsio;
796 
797 	if (msg_info->hdr.original_sc == NULL) {
798 		printf("%s: original_sc == NULL!\n", __func__);
799 		/* XXX KDM now what? */
800 		return;
801 	}
802 
803 	ctsio = &msg_info->hdr.original_sc->scsiio;
804 	ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
805 	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
806 	ctsio->io_hdr.status = msg_info->hdr.status;
807 	ctsio->scsi_status = msg_info->scsi.scsi_status;
808 	ctsio->sense_len = msg_info->scsi.sense_len;
809 	memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
810 	       msg_info->scsi.sense_len);
811 	ctl_enqueue_isc((union ctl_io *)ctsio);
812 }
813 
814 static void
815 ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
816 				union ctl_ha_msg *msg_info)
817 {
818 	struct ctl_scsiio *ctsio;
819 
820 	if (msg_info->hdr.serializing_sc == NULL) {
821 		printf("%s: serializing_sc == NULL!\n", __func__);
822 		/* XXX KDM now what? */
823 		return;
824 	}
825 
826 	ctsio = &msg_info->hdr.serializing_sc->scsiio;
827 	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
828 	ctl_enqueue_isc((union ctl_io *)ctsio);
829 }
830 
831 void
832 ctl_isc_announce_lun(struct ctl_lun *lun)
833 {
834 	struct ctl_softc *softc = lun->ctl_softc;
835 	union ctl_ha_msg *msg;
836 	struct ctl_ha_msg_lun_pr_key pr_key;
837 	int i, k;
838 
839 	if (softc->ha_link != CTL_HA_LINK_ONLINE)
840 		return;
841 	mtx_lock(&lun->lun_lock);
842 	i = sizeof(msg->lun);
843 	if (lun->lun_devid)
844 		i += lun->lun_devid->len;
845 	i += sizeof(pr_key) * lun->pr_key_count;
846 alloc:
847 	mtx_unlock(&lun->lun_lock);
848 	msg = malloc(i, M_CTL, M_WAITOK);
849 	mtx_lock(&lun->lun_lock);
850 	k = sizeof(msg->lun);
851 	if (lun->lun_devid)
852 		k += lun->lun_devid->len;
853 	k += sizeof(pr_key) * lun->pr_key_count;
854 	if (i < k) {
855 		free(msg, M_CTL);
856 		i = k;
857 		goto alloc;
858 	}
859 	bzero(&msg->lun, sizeof(msg->lun));
860 	msg->hdr.msg_type = CTL_MSG_LUN_SYNC;
861 	msg->hdr.nexus.targ_lun = lun->lun;
862 	msg->hdr.nexus.targ_mapped_lun = lun->lun;
863 	msg->lun.flags = lun->flags;
864 	msg->lun.pr_generation = lun->pr_generation;
865 	msg->lun.pr_res_idx = lun->pr_res_idx;
866 	msg->lun.pr_res_type = lun->pr_res_type;
867 	msg->lun.pr_key_count = lun->pr_key_count;
868 	i = 0;
869 	if (lun->lun_devid) {
870 		msg->lun.lun_devid_len = lun->lun_devid->len;
871 		memcpy(&msg->lun.data[i], lun->lun_devid->data,
872 		    msg->lun.lun_devid_len);
873 		i += msg->lun.lun_devid_len;
874 	}
875 	for (k = 0; k < CTL_MAX_INITIATORS; k++) {
876 		if ((pr_key.pr_key = ctl_get_prkey(lun, k)) == 0)
877 			continue;
878 		pr_key.pr_iid = k;
879 		memcpy(&msg->lun.data[i], &pr_key, sizeof(pr_key));
880 		i += sizeof(pr_key);
881 	}
882 	mtx_unlock(&lun->lun_lock);
883 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->port, sizeof(msg->port) + i,
884 	    M_WAITOK);
885 	free(msg, M_CTL);
886 
887 	if (lun->flags & CTL_LUN_PRIMARY_SC) {
888 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
889 			ctl_isc_announce_mode(lun, -1,
890 			    lun->mode_pages.index[i].page_code & SMPH_PC_MASK,
891 			    lun->mode_pages.index[i].subpage);
892 		}
893 	}
894 }
895 
896 void
897 ctl_isc_announce_port(struct ctl_port *port)
898 {
899 	struct ctl_softc *softc = port->ctl_softc;
900 	union ctl_ha_msg *msg;
901 	int i;
902 
903 	if (port->targ_port < softc->port_min ||
904 	    port->targ_port >= softc->port_max ||
905 	    softc->ha_link != CTL_HA_LINK_ONLINE)
906 		return;
907 	i = sizeof(msg->port) + strlen(port->port_name) + 1;
908 	if (port->lun_map)
909 		i += port->lun_map_size * sizeof(uint32_t);
910 	if (port->port_devid)
911 		i += port->port_devid->len;
912 	if (port->target_devid)
913 		i += port->target_devid->len;
914 	if (port->init_devid)
915 		i += port->init_devid->len;
916 	msg = malloc(i, M_CTL, M_WAITOK);
917 	bzero(&msg->port, sizeof(msg->port));
918 	msg->hdr.msg_type = CTL_MSG_PORT_SYNC;
919 	msg->hdr.nexus.targ_port = port->targ_port;
920 	msg->port.port_type = port->port_type;
921 	msg->port.physical_port = port->physical_port;
922 	msg->port.virtual_port = port->virtual_port;
923 	msg->port.status = port->status;
924 	i = 0;
925 	msg->port.name_len = sprintf(&msg->port.data[i],
926 	    "%d:%s", softc->ha_id, port->port_name) + 1;
927 	i += msg->port.name_len;
928 	if (port->lun_map) {
929 		msg->port.lun_map_len = port->lun_map_size * sizeof(uint32_t);
930 		memcpy(&msg->port.data[i], port->lun_map,
931 		    msg->port.lun_map_len);
932 		i += msg->port.lun_map_len;
933 	}
934 	if (port->port_devid) {
935 		msg->port.port_devid_len = port->port_devid->len;
936 		memcpy(&msg->port.data[i], port->port_devid->data,
937 		    msg->port.port_devid_len);
938 		i += msg->port.port_devid_len;
939 	}
940 	if (port->target_devid) {
941 		msg->port.target_devid_len = port->target_devid->len;
942 		memcpy(&msg->port.data[i], port->target_devid->data,
943 		    msg->port.target_devid_len);
944 		i += msg->port.target_devid_len;
945 	}
946 	if (port->init_devid) {
947 		msg->port.init_devid_len = port->init_devid->len;
948 		memcpy(&msg->port.data[i], port->init_devid->data,
949 		    msg->port.init_devid_len);
950 		i += msg->port.init_devid_len;
951 	}
952 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->port, sizeof(msg->port) + i,
953 	    M_WAITOK);
954 	free(msg, M_CTL);
955 }
956 
957 void
958 ctl_isc_announce_iid(struct ctl_port *port, int iid)
959 {
960 	struct ctl_softc *softc = port->ctl_softc;
961 	union ctl_ha_msg *msg;
962 	int i, l;
963 
964 	if (port->targ_port < softc->port_min ||
965 	    port->targ_port >= softc->port_max ||
966 	    softc->ha_link != CTL_HA_LINK_ONLINE)
967 		return;
968 	mtx_lock(&softc->ctl_lock);
969 	i = sizeof(msg->iid);
970 	l = 0;
971 	if (port->wwpn_iid[iid].name)
972 		l = strlen(port->wwpn_iid[iid].name) + 1;
973 	i += l;
974 	msg = malloc(i, M_CTL, M_NOWAIT);
975 	if (msg == NULL) {
976 		mtx_unlock(&softc->ctl_lock);
977 		return;
978 	}
979 	bzero(&msg->iid, sizeof(msg->iid));
980 	msg->hdr.msg_type = CTL_MSG_IID_SYNC;
981 	msg->hdr.nexus.targ_port = port->targ_port;
982 	msg->hdr.nexus.initid = iid;
983 	msg->iid.in_use = port->wwpn_iid[iid].in_use;
984 	msg->iid.name_len = l;
985 	msg->iid.wwpn = port->wwpn_iid[iid].wwpn;
986 	if (port->wwpn_iid[iid].name)
987 		strlcpy(msg->iid.data, port->wwpn_iid[iid].name, l);
988 	mtx_unlock(&softc->ctl_lock);
989 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->iid, i, M_NOWAIT);
990 	free(msg, M_CTL);
991 }
992 
993 void
994 ctl_isc_announce_mode(struct ctl_lun *lun, uint32_t initidx,
995     uint8_t page, uint8_t subpage)
996 {
997 	struct ctl_softc *softc = lun->ctl_softc;
998 	union ctl_ha_msg msg;
999 	u_int i;
1000 
1001 	if (softc->ha_link != CTL_HA_LINK_ONLINE)
1002 		return;
1003 	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
1004 		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) ==
1005 		    page && lun->mode_pages.index[i].subpage == subpage)
1006 			break;
1007 	}
1008 	if (i == CTL_NUM_MODE_PAGES)
1009 		return;
1010 
1011 	/* Don't try to replicate pages not present on this device. */
1012 	if (lun->mode_pages.index[i].page_data == NULL)
1013 		return;
1014 
1015 	bzero(&msg.mode, sizeof(msg.mode));
1016 	msg.hdr.msg_type = CTL_MSG_MODE_SYNC;
1017 	msg.hdr.nexus.targ_port = initidx / CTL_MAX_INIT_PER_PORT;
1018 	msg.hdr.nexus.initid = initidx % CTL_MAX_INIT_PER_PORT;
1019 	msg.hdr.nexus.targ_lun = lun->lun;
1020 	msg.hdr.nexus.targ_mapped_lun = lun->lun;
1021 	msg.mode.page_code = page;
1022 	msg.mode.subpage = subpage;
1023 	msg.mode.page_len = lun->mode_pages.index[i].page_len;
1024 	memcpy(msg.mode.data, lun->mode_pages.index[i].page_data,
1025 	    msg.mode.page_len);
1026 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg.mode, sizeof(msg.mode),
1027 	    M_WAITOK);
1028 }
1029 
1030 static void
1031 ctl_isc_ha_link_up(struct ctl_softc *softc)
1032 {
1033 	struct ctl_port *port;
1034 	struct ctl_lun *lun;
1035 	union ctl_ha_msg msg;
1036 	int i;
1037 
1038 	/* Announce this node parameters to peer for validation. */
1039 	msg.login.msg_type = CTL_MSG_LOGIN;
1040 	msg.login.version = CTL_HA_VERSION;
1041 	msg.login.ha_mode = softc->ha_mode;
1042 	msg.login.ha_id = softc->ha_id;
1043 	msg.login.max_luns = ctl_max_luns;
1044 	msg.login.max_ports = ctl_max_ports;
1045 	msg.login.max_init_per_port = CTL_MAX_INIT_PER_PORT;
1046 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg.login, sizeof(msg.login),
1047 	    M_WAITOK);
1048 
1049 	STAILQ_FOREACH(port, &softc->port_list, links) {
1050 		ctl_isc_announce_port(port);
1051 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1052 			if (port->wwpn_iid[i].in_use)
1053 				ctl_isc_announce_iid(port, i);
1054 		}
1055 	}
1056 	STAILQ_FOREACH(lun, &softc->lun_list, links)
1057 		ctl_isc_announce_lun(lun);
1058 }
1059 
1060 static void
1061 ctl_isc_ha_link_down(struct ctl_softc *softc)
1062 {
1063 	struct ctl_port *port;
1064 	struct ctl_lun *lun;
1065 	union ctl_io *io;
1066 	int i;
1067 
1068 	mtx_lock(&softc->ctl_lock);
1069 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
1070 		mtx_lock(&lun->lun_lock);
1071 		if (lun->flags & CTL_LUN_PEER_SC_PRIMARY) {
1072 			lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
1073 			ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
1074 		}
1075 		mtx_unlock(&lun->lun_lock);
1076 
1077 		mtx_unlock(&softc->ctl_lock);
1078 		io = ctl_alloc_io(softc->othersc_pool);
1079 		mtx_lock(&softc->ctl_lock);
1080 		ctl_zero_io(io);
1081 		io->io_hdr.msg_type = CTL_MSG_FAILOVER;
1082 		io->io_hdr.nexus.targ_mapped_lun = lun->lun;
1083 		ctl_enqueue_isc(io);
1084 	}
1085 
1086 	STAILQ_FOREACH(port, &softc->port_list, links) {
1087 		if (port->targ_port >= softc->port_min &&
1088 		    port->targ_port < softc->port_max)
1089 			continue;
1090 		port->status &= ~CTL_PORT_STATUS_ONLINE;
1091 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1092 			port->wwpn_iid[i].in_use = 0;
1093 			free(port->wwpn_iid[i].name, M_CTL);
1094 			port->wwpn_iid[i].name = NULL;
1095 		}
1096 	}
1097 	mtx_unlock(&softc->ctl_lock);
1098 }
1099 
1100 static void
1101 ctl_isc_ua(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1102 {
1103 	struct ctl_lun *lun;
1104 	uint32_t iid = ctl_get_initindex(&msg->hdr.nexus);
1105 
1106 	mtx_lock(&softc->ctl_lock);
1107 	if (msg->hdr.nexus.targ_mapped_lun >= ctl_max_luns ||
1108 	    (lun = softc->ctl_luns[msg->hdr.nexus.targ_mapped_lun]) == NULL) {
1109 		mtx_unlock(&softc->ctl_lock);
1110 		return;
1111 	}
1112 	mtx_lock(&lun->lun_lock);
1113 	mtx_unlock(&softc->ctl_lock);
1114 	if (msg->ua.ua_type == CTL_UA_THIN_PROV_THRES && msg->ua.ua_set)
1115 		memcpy(lun->ua_tpt_info, msg->ua.ua_info, 8);
1116 	if (msg->ua.ua_all) {
1117 		if (msg->ua.ua_set)
1118 			ctl_est_ua_all(lun, iid, msg->ua.ua_type);
1119 		else
1120 			ctl_clr_ua_all(lun, iid, msg->ua.ua_type);
1121 	} else {
1122 		if (msg->ua.ua_set)
1123 			ctl_est_ua(lun, iid, msg->ua.ua_type);
1124 		else
1125 			ctl_clr_ua(lun, iid, msg->ua.ua_type);
1126 	}
1127 	mtx_unlock(&lun->lun_lock);
1128 }
1129 
1130 static void
1131 ctl_isc_lun_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1132 {
1133 	struct ctl_lun *lun;
1134 	struct ctl_ha_msg_lun_pr_key pr_key;
1135 	int i, k;
1136 	ctl_lun_flags oflags;
1137 	uint32_t targ_lun;
1138 
1139 	targ_lun = msg->hdr.nexus.targ_mapped_lun;
1140 	mtx_lock(&softc->ctl_lock);
1141 	if (targ_lun >= ctl_max_luns ||
1142 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
1143 		mtx_unlock(&softc->ctl_lock);
1144 		return;
1145 	}
1146 	mtx_lock(&lun->lun_lock);
1147 	mtx_unlock(&softc->ctl_lock);
1148 	if (lun->flags & CTL_LUN_DISABLED) {
1149 		mtx_unlock(&lun->lun_lock);
1150 		return;
1151 	}
1152 	i = (lun->lun_devid != NULL) ? lun->lun_devid->len : 0;
1153 	if (msg->lun.lun_devid_len != i || (i > 0 &&
1154 	    memcmp(&msg->lun.data[0], lun->lun_devid->data, i) != 0)) {
1155 		mtx_unlock(&lun->lun_lock);
1156 		printf("%s: Received conflicting HA LUN %d\n",
1157 		    __func__, targ_lun);
1158 		return;
1159 	} else {
1160 		/* Record whether peer is primary. */
1161 		oflags = lun->flags;
1162 		if ((msg->lun.flags & CTL_LUN_PRIMARY_SC) &&
1163 		    (msg->lun.flags & CTL_LUN_DISABLED) == 0)
1164 			lun->flags |= CTL_LUN_PEER_SC_PRIMARY;
1165 		else
1166 			lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
1167 		if (oflags != lun->flags)
1168 			ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
1169 
1170 		/* If peer is primary and we are not -- use data */
1171 		if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
1172 		    (lun->flags & CTL_LUN_PEER_SC_PRIMARY)) {
1173 			lun->pr_generation = msg->lun.pr_generation;
1174 			lun->pr_res_idx = msg->lun.pr_res_idx;
1175 			lun->pr_res_type = msg->lun.pr_res_type;
1176 			lun->pr_key_count = msg->lun.pr_key_count;
1177 			for (k = 0; k < CTL_MAX_INITIATORS; k++)
1178 				ctl_clr_prkey(lun, k);
1179 			for (k = 0; k < msg->lun.pr_key_count; k++) {
1180 				memcpy(&pr_key, &msg->lun.data[i],
1181 				    sizeof(pr_key));
1182 				ctl_alloc_prkey(lun, pr_key.pr_iid);
1183 				ctl_set_prkey(lun, pr_key.pr_iid,
1184 				    pr_key.pr_key);
1185 				i += sizeof(pr_key);
1186 			}
1187 		}
1188 
1189 		mtx_unlock(&lun->lun_lock);
1190 		CTL_DEBUG_PRINT(("%s: Known LUN %d, peer is %s\n",
1191 		    __func__, targ_lun,
1192 		    (msg->lun.flags & CTL_LUN_PRIMARY_SC) ?
1193 		    "primary" : "secondary"));
1194 
1195 		/* If we are primary but peer doesn't know -- notify */
1196 		if ((lun->flags & CTL_LUN_PRIMARY_SC) &&
1197 		    (msg->lun.flags & CTL_LUN_PEER_SC_PRIMARY) == 0)
1198 			ctl_isc_announce_lun(lun);
1199 	}
1200 }
1201 
1202 static void
1203 ctl_isc_port_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1204 {
1205 	struct ctl_port *port;
1206 	struct ctl_lun *lun;
1207 	int i, new;
1208 
1209 	port = softc->ctl_ports[msg->hdr.nexus.targ_port];
1210 	if (port == NULL) {
1211 		CTL_DEBUG_PRINT(("%s: New port %d\n", __func__,
1212 		    msg->hdr.nexus.targ_port));
1213 		new = 1;
1214 		port = malloc(sizeof(*port), M_CTL, M_WAITOK | M_ZERO);
1215 		port->frontend = &ha_frontend;
1216 		port->targ_port = msg->hdr.nexus.targ_port;
1217 		port->fe_datamove = ctl_ha_datamove;
1218 		port->fe_done = ctl_ha_done;
1219 	} else if (port->frontend == &ha_frontend) {
1220 		CTL_DEBUG_PRINT(("%s: Updated port %d\n", __func__,
1221 		    msg->hdr.nexus.targ_port));
1222 		new = 0;
1223 	} else {
1224 		printf("%s: Received conflicting HA port %d\n",
1225 		    __func__, msg->hdr.nexus.targ_port);
1226 		return;
1227 	}
1228 	port->port_type = msg->port.port_type;
1229 	port->physical_port = msg->port.physical_port;
1230 	port->virtual_port = msg->port.virtual_port;
1231 	port->status = msg->port.status;
1232 	i = 0;
1233 	free(port->port_name, M_CTL);
1234 	port->port_name = strndup(&msg->port.data[i], msg->port.name_len,
1235 	    M_CTL);
1236 	i += msg->port.name_len;
1237 	if (msg->port.lun_map_len != 0) {
1238 		if (port->lun_map == NULL ||
1239 		    port->lun_map_size * sizeof(uint32_t) <
1240 		    msg->port.lun_map_len) {
1241 			port->lun_map_size = 0;
1242 			free(port->lun_map, M_CTL);
1243 			port->lun_map = malloc(msg->port.lun_map_len,
1244 			    M_CTL, M_WAITOK);
1245 		}
1246 		memcpy(port->lun_map, &msg->port.data[i], msg->port.lun_map_len);
1247 		port->lun_map_size = msg->port.lun_map_len / sizeof(uint32_t);
1248 		i += msg->port.lun_map_len;
1249 	} else {
1250 		port->lun_map_size = 0;
1251 		free(port->lun_map, M_CTL);
1252 		port->lun_map = NULL;
1253 	}
1254 	if (msg->port.port_devid_len != 0) {
1255 		if (port->port_devid == NULL ||
1256 		    port->port_devid->len < msg->port.port_devid_len) {
1257 			free(port->port_devid, M_CTL);
1258 			port->port_devid = malloc(sizeof(struct ctl_devid) +
1259 			    msg->port.port_devid_len, M_CTL, M_WAITOK);
1260 		}
1261 		memcpy(port->port_devid->data, &msg->port.data[i],
1262 		    msg->port.port_devid_len);
1263 		port->port_devid->len = msg->port.port_devid_len;
1264 		i += msg->port.port_devid_len;
1265 	} else {
1266 		free(port->port_devid, M_CTL);
1267 		port->port_devid = NULL;
1268 	}
1269 	if (msg->port.target_devid_len != 0) {
1270 		if (port->target_devid == NULL ||
1271 		    port->target_devid->len < msg->port.target_devid_len) {
1272 			free(port->target_devid, M_CTL);
1273 			port->target_devid = malloc(sizeof(struct ctl_devid) +
1274 			    msg->port.target_devid_len, M_CTL, M_WAITOK);
1275 		}
1276 		memcpy(port->target_devid->data, &msg->port.data[i],
1277 		    msg->port.target_devid_len);
1278 		port->target_devid->len = msg->port.target_devid_len;
1279 		i += msg->port.target_devid_len;
1280 	} else {
1281 		free(port->target_devid, M_CTL);
1282 		port->target_devid = NULL;
1283 	}
1284 	if (msg->port.init_devid_len != 0) {
1285 		if (port->init_devid == NULL ||
1286 		    port->init_devid->len < msg->port.init_devid_len) {
1287 			free(port->init_devid, M_CTL);
1288 			port->init_devid = malloc(sizeof(struct ctl_devid) +
1289 			    msg->port.init_devid_len, M_CTL, M_WAITOK);
1290 		}
1291 		memcpy(port->init_devid->data, &msg->port.data[i],
1292 		    msg->port.init_devid_len);
1293 		port->init_devid->len = msg->port.init_devid_len;
1294 		i += msg->port.init_devid_len;
1295 	} else {
1296 		free(port->init_devid, M_CTL);
1297 		port->init_devid = NULL;
1298 	}
1299 	if (new) {
1300 		if (ctl_port_register(port) != 0) {
1301 			printf("%s: ctl_port_register() failed with error\n",
1302 			    __func__);
1303 		}
1304 	}
1305 	mtx_lock(&softc->ctl_lock);
1306 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
1307 		if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
1308 			continue;
1309 		mtx_lock(&lun->lun_lock);
1310 		ctl_est_ua_all(lun, -1, CTL_UA_INQ_CHANGE);
1311 		mtx_unlock(&lun->lun_lock);
1312 	}
1313 	mtx_unlock(&softc->ctl_lock);
1314 }
1315 
1316 static void
1317 ctl_isc_iid_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1318 {
1319 	struct ctl_port *port;
1320 	int iid;
1321 
1322 	port = softc->ctl_ports[msg->hdr.nexus.targ_port];
1323 	if (port == NULL) {
1324 		printf("%s: Received IID for unknown port %d\n",
1325 		    __func__, msg->hdr.nexus.targ_port);
1326 		return;
1327 	}
1328 	iid = msg->hdr.nexus.initid;
1329 	if (port->wwpn_iid[iid].in_use != 0 &&
1330 	    msg->iid.in_use == 0)
1331 		ctl_i_t_nexus_loss(softc, iid, CTL_UA_POWERON);
1332 	port->wwpn_iid[iid].in_use = msg->iid.in_use;
1333 	port->wwpn_iid[iid].wwpn = msg->iid.wwpn;
1334 	free(port->wwpn_iid[iid].name, M_CTL);
1335 	if (msg->iid.name_len) {
1336 		port->wwpn_iid[iid].name = strndup(&msg->iid.data[0],
1337 		    msg->iid.name_len, M_CTL);
1338 	} else
1339 		port->wwpn_iid[iid].name = NULL;
1340 }
1341 
1342 static void
1343 ctl_isc_login(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1344 {
1345 
1346 	if (msg->login.version != CTL_HA_VERSION) {
1347 		printf("CTL HA peers have different versions %d != %d\n",
1348 		    msg->login.version, CTL_HA_VERSION);
1349 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1350 		return;
1351 	}
1352 	if (msg->login.ha_mode != softc->ha_mode) {
1353 		printf("CTL HA peers have different ha_mode %d != %d\n",
1354 		    msg->login.ha_mode, softc->ha_mode);
1355 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1356 		return;
1357 	}
1358 	if (msg->login.ha_id == softc->ha_id) {
1359 		printf("CTL HA peers have same ha_id %d\n", msg->login.ha_id);
1360 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1361 		return;
1362 	}
1363 	if (msg->login.max_luns != ctl_max_luns ||
1364 	    msg->login.max_ports != ctl_max_ports ||
1365 	    msg->login.max_init_per_port != CTL_MAX_INIT_PER_PORT) {
1366 		printf("CTL HA peers have different limits\n");
1367 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1368 		return;
1369 	}
1370 }
1371 
1372 static void
1373 ctl_isc_mode_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1374 {
1375 	struct ctl_lun *lun;
1376 	u_int i;
1377 	uint32_t initidx, targ_lun;
1378 
1379 	targ_lun = msg->hdr.nexus.targ_mapped_lun;
1380 	mtx_lock(&softc->ctl_lock);
1381 	if (targ_lun >= ctl_max_luns ||
1382 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
1383 		mtx_unlock(&softc->ctl_lock);
1384 		return;
1385 	}
1386 	mtx_lock(&lun->lun_lock);
1387 	mtx_unlock(&softc->ctl_lock);
1388 	if (lun->flags & CTL_LUN_DISABLED) {
1389 		mtx_unlock(&lun->lun_lock);
1390 		return;
1391 	}
1392 	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
1393 		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) ==
1394 		    msg->mode.page_code &&
1395 		    lun->mode_pages.index[i].subpage == msg->mode.subpage)
1396 			break;
1397 	}
1398 	if (i == CTL_NUM_MODE_PAGES) {
1399 		mtx_unlock(&lun->lun_lock);
1400 		return;
1401 	}
1402 	memcpy(lun->mode_pages.index[i].page_data, msg->mode.data,
1403 	    lun->mode_pages.index[i].page_len);
1404 	initidx = ctl_get_initindex(&msg->hdr.nexus);
1405 	if (initidx != -1)
1406 		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
1407 	mtx_unlock(&lun->lun_lock);
1408 }
1409 
1410 /*
1411  * ISC (Inter Shelf Communication) event handler.  Events from the HA
1412  * subsystem come in here.
1413  */
1414 static void
1415 ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
1416 {
1417 	struct ctl_softc *softc = control_softc;
1418 	union ctl_io *io;
1419 	struct ctl_prio *presio;
1420 	ctl_ha_status isc_status;
1421 
1422 	CTL_DEBUG_PRINT(("CTL: Isc Msg event %d\n", event));
1423 	if (event == CTL_HA_EVT_MSG_RECV) {
1424 		union ctl_ha_msg *msg, msgbuf;
1425 
1426 		if (param > sizeof(msgbuf))
1427 			msg = malloc(param, M_CTL, M_WAITOK);
1428 		else
1429 			msg = &msgbuf;
1430 		isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, msg, param,
1431 		    M_WAITOK);
1432 		if (isc_status != CTL_HA_STATUS_SUCCESS) {
1433 			printf("%s: Error receiving message: %d\n",
1434 			    __func__, isc_status);
1435 			if (msg != &msgbuf)
1436 				free(msg, M_CTL);
1437 			return;
1438 		}
1439 
1440 		CTL_DEBUG_PRINT(("CTL: msg_type %d\n", msg->hdr.msg_type));
1441 		switch (msg->hdr.msg_type) {
1442 		case CTL_MSG_SERIALIZE:
1443 			io = ctl_alloc_io(softc->othersc_pool);
1444 			ctl_zero_io(io);
1445 			// populate ctsio from msg
1446 			io->io_hdr.io_type = CTL_IO_SCSI;
1447 			io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
1448 			io->io_hdr.remote_io = msg->hdr.original_sc;
1449 			io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
1450 					    CTL_FLAG_IO_ACTIVE;
1451 			/*
1452 			 * If we're in serialization-only mode, we don't
1453 			 * want to go through full done processing.  Thus
1454 			 * the COPY flag.
1455 			 *
1456 			 * XXX KDM add another flag that is more specific.
1457 			 */
1458 			if (softc->ha_mode != CTL_HA_MODE_XFER)
1459 				io->io_hdr.flags |= CTL_FLAG_INT_COPY;
1460 			io->io_hdr.nexus = msg->hdr.nexus;
1461 			io->scsiio.tag_num = msg->scsi.tag_num;
1462 			io->scsiio.tag_type = msg->scsi.tag_type;
1463 #ifdef CTL_TIME_IO
1464 			io->io_hdr.start_time = time_uptime;
1465 			getbinuptime(&io->io_hdr.start_bt);
1466 #endif /* CTL_TIME_IO */
1467 			io->scsiio.cdb_len = msg->scsi.cdb_len;
1468 			memcpy(io->scsiio.cdb, msg->scsi.cdb,
1469 			       CTL_MAX_CDBLEN);
1470 			if (softc->ha_mode == CTL_HA_MODE_XFER) {
1471 				const struct ctl_cmd_entry *entry;
1472 
1473 				entry = ctl_get_cmd_entry(&io->scsiio, NULL);
1474 				io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
1475 				io->io_hdr.flags |=
1476 					entry->flags & CTL_FLAG_DATA_MASK;
1477 			}
1478 			ctl_enqueue_isc(io);
1479 			break;
1480 
1481 		/* Performed on the Originating SC, XFER mode only */
1482 		case CTL_MSG_DATAMOVE: {
1483 			struct ctl_sg_entry *sgl;
1484 			int i, j;
1485 
1486 			io = msg->hdr.original_sc;
1487 			if (io == NULL) {
1488 				printf("%s: original_sc == NULL!\n", __func__);
1489 				/* XXX KDM do something here */
1490 				break;
1491 			}
1492 			io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
1493 			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1494 			/*
1495 			 * Keep track of this, we need to send it back over
1496 			 * when the datamove is complete.
1497 			 */
1498 			io->io_hdr.remote_io = msg->hdr.serializing_sc;
1499 			if (msg->hdr.status == CTL_SUCCESS)
1500 				io->io_hdr.status = msg->hdr.status;
1501 
1502 			if (msg->dt.sg_sequence == 0) {
1503 #ifdef CTL_TIME_IO
1504 				getbinuptime(&io->io_hdr.dma_start_bt);
1505 #endif
1506 				i = msg->dt.kern_sg_entries +
1507 				    msg->dt.kern_data_len /
1508 				    CTL_HA_DATAMOVE_SEGMENT + 1;
1509 				sgl = malloc(sizeof(*sgl) * i, M_CTL,
1510 				    M_WAITOK | M_ZERO);
1511 				CTL_RSGL(io) = sgl;
1512 				CTL_LSGL(io) = &sgl[msg->dt.kern_sg_entries];
1513 
1514 				io->scsiio.kern_data_ptr = (uint8_t *)sgl;
1515 
1516 				io->scsiio.kern_sg_entries =
1517 					msg->dt.kern_sg_entries;
1518 				io->scsiio.rem_sg_entries =
1519 					msg->dt.kern_sg_entries;
1520 				io->scsiio.kern_data_len =
1521 					msg->dt.kern_data_len;
1522 				io->scsiio.kern_total_len =
1523 					msg->dt.kern_total_len;
1524 				io->scsiio.kern_data_resid =
1525 					msg->dt.kern_data_resid;
1526 				io->scsiio.kern_rel_offset =
1527 					msg->dt.kern_rel_offset;
1528 				io->io_hdr.flags &= ~CTL_FLAG_BUS_ADDR;
1529 				io->io_hdr.flags |= msg->dt.flags &
1530 				    CTL_FLAG_BUS_ADDR;
1531 			} else
1532 				sgl = (struct ctl_sg_entry *)
1533 					io->scsiio.kern_data_ptr;
1534 
1535 			for (i = msg->dt.sent_sg_entries, j = 0;
1536 			     i < (msg->dt.sent_sg_entries +
1537 			     msg->dt.cur_sg_entries); i++, j++) {
1538 				sgl[i].addr = msg->dt.sg_list[j].addr;
1539 				sgl[i].len = msg->dt.sg_list[j].len;
1540 			}
1541 
1542 			/*
1543 			 * If this is the last piece of the I/O, we've got
1544 			 * the full S/G list.  Queue processing in the thread.
1545 			 * Otherwise wait for the next piece.
1546 			 */
1547 			if (msg->dt.sg_last != 0)
1548 				ctl_enqueue_isc(io);
1549 			break;
1550 		}
1551 		/* Performed on the Serializing (primary) SC, XFER mode only */
1552 		case CTL_MSG_DATAMOVE_DONE: {
1553 			if (msg->hdr.serializing_sc == NULL) {
1554 				printf("%s: serializing_sc == NULL!\n",
1555 				       __func__);
1556 				/* XXX KDM now what? */
1557 				break;
1558 			}
1559 			/*
1560 			 * We grab the sense information here in case
1561 			 * there was a failure, so we can return status
1562 			 * back to the initiator.
1563 			 */
1564 			io = msg->hdr.serializing_sc;
1565 			io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
1566 			io->io_hdr.flags &= ~CTL_FLAG_DMA_INPROG;
1567 			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1568 			io->io_hdr.port_status = msg->scsi.port_status;
1569 			io->scsiio.kern_data_resid = msg->scsi.kern_data_resid;
1570 			if (msg->hdr.status != CTL_STATUS_NONE) {
1571 				io->io_hdr.status = msg->hdr.status;
1572 				io->scsiio.scsi_status = msg->scsi.scsi_status;
1573 				io->scsiio.sense_len = msg->scsi.sense_len;
1574 				memcpy(&io->scsiio.sense_data,
1575 				    &msg->scsi.sense_data,
1576 				    msg->scsi.sense_len);
1577 				if (msg->hdr.status == CTL_SUCCESS)
1578 					io->io_hdr.flags |= CTL_FLAG_STATUS_SENT;
1579 			}
1580 			ctl_enqueue_isc(io);
1581 			break;
1582 		}
1583 
1584 		/* Preformed on Originating SC, SER_ONLY mode */
1585 		case CTL_MSG_R2R:
1586 			io = msg->hdr.original_sc;
1587 			if (io == NULL) {
1588 				printf("%s: original_sc == NULL!\n",
1589 				    __func__);
1590 				break;
1591 			}
1592 			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1593 			io->io_hdr.msg_type = CTL_MSG_R2R;
1594 			io->io_hdr.remote_io = msg->hdr.serializing_sc;
1595 			ctl_enqueue_isc(io);
1596 			break;
1597 
1598 		/*
1599 		 * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
1600 		 * mode.
1601 		 * Performed on the Originating (i.e. secondary) SC in XFER
1602 		 * mode
1603 		 */
1604 		case CTL_MSG_FINISH_IO:
1605 			if (softc->ha_mode == CTL_HA_MODE_XFER)
1606 				ctl_isc_handler_finish_xfer(softc, msg);
1607 			else
1608 				ctl_isc_handler_finish_ser_only(softc, msg);
1609 			break;
1610 
1611 		/* Preformed on Originating SC */
1612 		case CTL_MSG_BAD_JUJU:
1613 			io = msg->hdr.original_sc;
1614 			if (io == NULL) {
1615 				printf("%s: Bad JUJU!, original_sc is NULL!\n",
1616 				       __func__);
1617 				break;
1618 			}
1619 			ctl_copy_sense_data(msg, io);
1620 			/*
1621 			 * IO should have already been cleaned up on other
1622 			 * SC so clear this flag so we won't send a message
1623 			 * back to finish the IO there.
1624 			 */
1625 			io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
1626 			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1627 
1628 			/* io = msg->hdr.serializing_sc; */
1629 			io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
1630 			ctl_enqueue_isc(io);
1631 			break;
1632 
1633 		/* Handle resets sent from the other side */
1634 		case CTL_MSG_MANAGE_TASKS: {
1635 			struct ctl_taskio *taskio;
1636 			taskio = (struct ctl_taskio *)ctl_alloc_io(
1637 			    softc->othersc_pool);
1638 			ctl_zero_io((union ctl_io *)taskio);
1639 			taskio->io_hdr.io_type = CTL_IO_TASK;
1640 			taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1641 			taskio->io_hdr.nexus = msg->hdr.nexus;
1642 			taskio->task_action = msg->task.task_action;
1643 			taskio->tag_num = msg->task.tag_num;
1644 			taskio->tag_type = msg->task.tag_type;
1645 #ifdef CTL_TIME_IO
1646 			taskio->io_hdr.start_time = time_uptime;
1647 			getbinuptime(&taskio->io_hdr.start_bt);
1648 #endif /* CTL_TIME_IO */
1649 			ctl_run_task((union ctl_io *)taskio);
1650 			break;
1651 		}
1652 		/* Persistent Reserve action which needs attention */
1653 		case CTL_MSG_PERS_ACTION:
1654 			presio = (struct ctl_prio *)ctl_alloc_io(
1655 			    softc->othersc_pool);
1656 			ctl_zero_io((union ctl_io *)presio);
1657 			presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
1658 			presio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1659 			presio->io_hdr.nexus = msg->hdr.nexus;
1660 			presio->pr_msg = msg->pr;
1661 			ctl_enqueue_isc((union ctl_io *)presio);
1662 			break;
1663 		case CTL_MSG_UA:
1664 			ctl_isc_ua(softc, msg, param);
1665 			break;
1666 		case CTL_MSG_PORT_SYNC:
1667 			ctl_isc_port_sync(softc, msg, param);
1668 			break;
1669 		case CTL_MSG_LUN_SYNC:
1670 			ctl_isc_lun_sync(softc, msg, param);
1671 			break;
1672 		case CTL_MSG_IID_SYNC:
1673 			ctl_isc_iid_sync(softc, msg, param);
1674 			break;
1675 		case CTL_MSG_LOGIN:
1676 			ctl_isc_login(softc, msg, param);
1677 			break;
1678 		case CTL_MSG_MODE_SYNC:
1679 			ctl_isc_mode_sync(softc, msg, param);
1680 			break;
1681 		default:
1682 			printf("Received HA message of unknown type %d\n",
1683 			    msg->hdr.msg_type);
1684 			ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1685 			break;
1686 		}
1687 		if (msg != &msgbuf)
1688 			free(msg, M_CTL);
1689 	} else if (event == CTL_HA_EVT_LINK_CHANGE) {
1690 		printf("CTL: HA link status changed from %d to %d\n",
1691 		    softc->ha_link, param);
1692 		if (param == softc->ha_link)
1693 			return;
1694 		if (softc->ha_link == CTL_HA_LINK_ONLINE) {
1695 			softc->ha_link = param;
1696 			ctl_isc_ha_link_down(softc);
1697 		} else {
1698 			softc->ha_link = param;
1699 			if (softc->ha_link == CTL_HA_LINK_ONLINE)
1700 				ctl_isc_ha_link_up(softc);
1701 		}
1702 		return;
1703 	} else {
1704 		printf("ctl_isc_event_handler: Unknown event %d\n", event);
1705 		return;
1706 	}
1707 }
1708 
1709 static void
1710 ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
1711 {
1712 
1713 	memcpy(&dest->scsiio.sense_data, &src->scsi.sense_data,
1714 	    src->scsi.sense_len);
1715 	dest->scsiio.scsi_status = src->scsi.scsi_status;
1716 	dest->scsiio.sense_len = src->scsi.sense_len;
1717 	dest->io_hdr.status = src->hdr.status;
1718 }
1719 
1720 static void
1721 ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest)
1722 {
1723 
1724 	memcpy(&dest->scsi.sense_data, &src->scsiio.sense_data,
1725 	    src->scsiio.sense_len);
1726 	dest->scsi.scsi_status = src->scsiio.scsi_status;
1727 	dest->scsi.sense_len = src->scsiio.sense_len;
1728 	dest->hdr.status = src->io_hdr.status;
1729 }
1730 
1731 void
1732 ctl_est_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1733 {
1734 	struct ctl_softc *softc = lun->ctl_softc;
1735 	ctl_ua_type *pu;
1736 
1737 	if (initidx < softc->init_min || initidx >= softc->init_max)
1738 		return;
1739 	mtx_assert(&lun->lun_lock, MA_OWNED);
1740 	pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1741 	if (pu == NULL)
1742 		return;
1743 	pu[initidx % CTL_MAX_INIT_PER_PORT] |= ua;
1744 }
1745 
1746 void
1747 ctl_est_ua_port(struct ctl_lun *lun, int port, uint32_t except, ctl_ua_type ua)
1748 {
1749 	int i;
1750 
1751 	mtx_assert(&lun->lun_lock, MA_OWNED);
1752 	if (lun->pending_ua[port] == NULL)
1753 		return;
1754 	for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1755 		if (port * CTL_MAX_INIT_PER_PORT + i == except)
1756 			continue;
1757 		lun->pending_ua[port][i] |= ua;
1758 	}
1759 }
1760 
1761 void
1762 ctl_est_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1763 {
1764 	struct ctl_softc *softc = lun->ctl_softc;
1765 	int i;
1766 
1767 	mtx_assert(&lun->lun_lock, MA_OWNED);
1768 	for (i = softc->port_min; i < softc->port_max; i++)
1769 		ctl_est_ua_port(lun, i, except, ua);
1770 }
1771 
1772 void
1773 ctl_clr_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1774 {
1775 	struct ctl_softc *softc = lun->ctl_softc;
1776 	ctl_ua_type *pu;
1777 
1778 	if (initidx < softc->init_min || initidx >= softc->init_max)
1779 		return;
1780 	mtx_assert(&lun->lun_lock, MA_OWNED);
1781 	pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1782 	if (pu == NULL)
1783 		return;
1784 	pu[initidx % CTL_MAX_INIT_PER_PORT] &= ~ua;
1785 }
1786 
1787 void
1788 ctl_clr_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1789 {
1790 	struct ctl_softc *softc = lun->ctl_softc;
1791 	int i, j;
1792 
1793 	mtx_assert(&lun->lun_lock, MA_OWNED);
1794 	for (i = softc->port_min; i < softc->port_max; i++) {
1795 		if (lun->pending_ua[i] == NULL)
1796 			continue;
1797 		for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
1798 			if (i * CTL_MAX_INIT_PER_PORT + j == except)
1799 				continue;
1800 			lun->pending_ua[i][j] &= ~ua;
1801 		}
1802 	}
1803 }
1804 
1805 void
1806 ctl_clr_ua_allluns(struct ctl_softc *ctl_softc, uint32_t initidx,
1807     ctl_ua_type ua_type)
1808 {
1809 	struct ctl_lun *lun;
1810 
1811 	mtx_assert(&ctl_softc->ctl_lock, MA_OWNED);
1812 	STAILQ_FOREACH(lun, &ctl_softc->lun_list, links) {
1813 		mtx_lock(&lun->lun_lock);
1814 		ctl_clr_ua(lun, initidx, ua_type);
1815 		mtx_unlock(&lun->lun_lock);
1816 	}
1817 }
1818 
1819 static int
1820 ctl_ha_role_sysctl(SYSCTL_HANDLER_ARGS)
1821 {
1822 	struct ctl_softc *softc = (struct ctl_softc *)arg1;
1823 	struct ctl_lun *lun;
1824 	struct ctl_lun_req ireq;
1825 	int error, value;
1826 
1827 	value = (softc->flags & CTL_FLAG_ACTIVE_SHELF) ? 0 : 1;
1828 	error = sysctl_handle_int(oidp, &value, 0, req);
1829 	if ((error != 0) || (req->newptr == NULL))
1830 		return (error);
1831 
1832 	mtx_lock(&softc->ctl_lock);
1833 	if (value == 0)
1834 		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1835 	else
1836 		softc->flags &= ~CTL_FLAG_ACTIVE_SHELF;
1837 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
1838 		mtx_unlock(&softc->ctl_lock);
1839 		bzero(&ireq, sizeof(ireq));
1840 		ireq.reqtype = CTL_LUNREQ_MODIFY;
1841 		ireq.reqdata.modify.lun_id = lun->lun;
1842 		lun->backend->ioctl(NULL, CTL_LUN_REQ, (caddr_t)&ireq, 0,
1843 		    curthread);
1844 		if (ireq.status != CTL_LUN_OK) {
1845 			printf("%s: CTL_LUNREQ_MODIFY returned %d '%s'\n",
1846 			    __func__, ireq.status, ireq.error_str);
1847 		}
1848 		mtx_lock(&softc->ctl_lock);
1849 	}
1850 	mtx_unlock(&softc->ctl_lock);
1851 	return (0);
1852 }
1853 
1854 static int
1855 ctl_init(void)
1856 {
1857 	struct make_dev_args args;
1858 	struct ctl_softc *softc;
1859 	int i, error;
1860 
1861 	softc = control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
1862 			       M_WAITOK | M_ZERO);
1863 
1864 	make_dev_args_init(&args);
1865 	args.mda_devsw = &ctl_cdevsw;
1866 	args.mda_uid = UID_ROOT;
1867 	args.mda_gid = GID_OPERATOR;
1868 	args.mda_mode = 0600;
1869 	args.mda_si_drv1 = softc;
1870 	args.mda_si_drv2 = NULL;
1871 	error = make_dev_s(&args, &softc->dev, "cam/ctl");
1872 	if (error != 0) {
1873 		free(softc, M_DEVBUF);
1874 		control_softc = NULL;
1875 		return (error);
1876 	}
1877 
1878 	sysctl_ctx_init(&softc->sysctl_ctx);
1879 	softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
1880 		SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
1881 		CTLFLAG_RD | CTLFLAG_MPSAFE, 0, "CAM Target Layer");
1882 
1883 	if (softc->sysctl_tree == NULL) {
1884 		printf("%s: unable to allocate sysctl tree\n", __func__);
1885 		destroy_dev(softc->dev);
1886 		free(softc, M_DEVBUF);
1887 		control_softc = NULL;
1888 		return (ENOMEM);
1889 	}
1890 
1891 	mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
1892 	softc->io_zone = uma_zcreate("CTL IO", sizeof(union ctl_io),
1893 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1894 	softc->flags = 0;
1895 
1896 	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1897 	    OID_AUTO, "ha_mode", CTLFLAG_RDTUN, (int *)&softc->ha_mode, 0,
1898 	    "HA mode (0 - act/stby, 1 - serialize only, 2 - xfer)");
1899 
1900 	if (ctl_max_luns <= 0 || powerof2(ctl_max_luns) == 0) {
1901 		printf("Bad value %d for kern.cam.ctl.max_luns, must be a power of two, using %d\n",
1902 		    ctl_max_luns, CTL_DEFAULT_MAX_LUNS);
1903 		ctl_max_luns = CTL_DEFAULT_MAX_LUNS;
1904 	}
1905 	softc->ctl_luns = malloc(sizeof(struct ctl_lun *) * ctl_max_luns,
1906 	    M_DEVBUF, M_WAITOK | M_ZERO);
1907 	softc->ctl_lun_mask = malloc(sizeof(uint32_t) *
1908 	    ((ctl_max_luns + 31) / 32), M_DEVBUF, M_WAITOK | M_ZERO);
1909 	if (ctl_max_ports <= 0 || powerof2(ctl_max_ports) == 0) {
1910 		printf("Bad value %d for kern.cam.ctl.max_ports, must be a power of two, using %d\n",
1911 		    ctl_max_ports, CTL_DEFAULT_MAX_PORTS);
1912 		ctl_max_ports = CTL_DEFAULT_MAX_PORTS;
1913 	}
1914 	softc->ctl_port_mask = malloc(sizeof(uint32_t) *
1915 	  ((ctl_max_ports + 31) / 32), M_DEVBUF, M_WAITOK | M_ZERO);
1916 	softc->ctl_ports = malloc(sizeof(struct ctl_port *) * ctl_max_ports,
1917 	     M_DEVBUF, M_WAITOK | M_ZERO);
1918 
1919 
1920 	/*
1921 	 * In Copan's HA scheme, the "master" and "slave" roles are
1922 	 * figured out through the slot the controller is in.  Although it
1923 	 * is an active/active system, someone has to be in charge.
1924 	 */
1925 	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1926 	    OID_AUTO, "ha_id", CTLFLAG_RDTUN, &softc->ha_id, 0,
1927 	    "HA head ID (0 - no HA)");
1928 	if (softc->ha_id == 0 || softc->ha_id > NUM_HA_SHELVES) {
1929 		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1930 		softc->is_single = 1;
1931 		softc->port_cnt = ctl_max_ports;
1932 		softc->port_min = 0;
1933 	} else {
1934 		softc->port_cnt = ctl_max_ports / NUM_HA_SHELVES;
1935 		softc->port_min = (softc->ha_id - 1) * softc->port_cnt;
1936 	}
1937 	softc->port_max = softc->port_min + softc->port_cnt;
1938 	softc->init_min = softc->port_min * CTL_MAX_INIT_PER_PORT;
1939 	softc->init_max = softc->port_max * CTL_MAX_INIT_PER_PORT;
1940 
1941 	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1942 	    OID_AUTO, "ha_link", CTLFLAG_RD, (int *)&softc->ha_link, 0,
1943 	    "HA link state (0 - offline, 1 - unknown, 2 - online)");
1944 
1945 	STAILQ_INIT(&softc->lun_list);
1946 	STAILQ_INIT(&softc->fe_list);
1947 	STAILQ_INIT(&softc->port_list);
1948 	STAILQ_INIT(&softc->be_list);
1949 	ctl_tpc_init(softc);
1950 
1951 	if (worker_threads <= 0)
1952 		worker_threads = max(1, mp_ncpus / 4);
1953 	if (worker_threads > CTL_MAX_THREADS)
1954 		worker_threads = CTL_MAX_THREADS;
1955 
1956 	for (i = 0; i < worker_threads; i++) {
1957 		struct ctl_thread *thr = &softc->threads[i];
1958 
1959 		mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1960 		thr->ctl_softc = softc;
1961 		STAILQ_INIT(&thr->incoming_queue);
1962 		STAILQ_INIT(&thr->rtr_queue);
1963 		STAILQ_INIT(&thr->done_queue);
1964 		STAILQ_INIT(&thr->isc_queue);
1965 
1966 		error = kproc_kthread_add(ctl_work_thread, thr,
1967 		    &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1968 		if (error != 0) {
1969 			printf("error creating CTL work thread!\n");
1970 			return (error);
1971 		}
1972 	}
1973 	error = kproc_kthread_add(ctl_thresh_thread, softc,
1974 	    &softc->ctl_proc, &softc->thresh_thread, 0, 0, "ctl", "thresh");
1975 	if (error != 0) {
1976 		printf("error creating CTL threshold thread!\n");
1977 		return (error);
1978 	}
1979 
1980 	SYSCTL_ADD_PROC(&softc->sysctl_ctx,SYSCTL_CHILDREN(softc->sysctl_tree),
1981 	    OID_AUTO, "ha_role",
1982 	    CTLTYPE_INT | CTLFLAG_RWTUN | CTLFLAG_NEEDGIANT,
1983 	    softc, 0, ctl_ha_role_sysctl, "I", "HA role for this head");
1984 
1985 	if (softc->is_single == 0) {
1986 		if (ctl_frontend_register(&ha_frontend) != 0)
1987 			softc->is_single = 1;
1988 	}
1989 	return (0);
1990 }
1991 
1992 static int
1993 ctl_shutdown(void)
1994 {
1995 	struct ctl_softc *softc = control_softc;
1996 	int i;
1997 
1998 	if (softc->is_single == 0)
1999 		ctl_frontend_deregister(&ha_frontend);
2000 
2001 	destroy_dev(softc->dev);
2002 
2003 	/* Shutdown CTL threads. */
2004 	softc->shutdown = 1;
2005 	for (i = 0; i < worker_threads; i++) {
2006 		struct ctl_thread *thr = &softc->threads[i];
2007 		while (thr->thread != NULL) {
2008 			wakeup(thr);
2009 			if (thr->thread != NULL)
2010 				pause("CTL thr shutdown", 1);
2011 		}
2012 		mtx_destroy(&thr->queue_lock);
2013 	}
2014 	while (softc->thresh_thread != NULL) {
2015 		wakeup(softc->thresh_thread);
2016 		if (softc->thresh_thread != NULL)
2017 			pause("CTL thr shutdown", 1);
2018 	}
2019 
2020 	ctl_tpc_shutdown(softc);
2021 	uma_zdestroy(softc->io_zone);
2022 	mtx_destroy(&softc->ctl_lock);
2023 
2024 	free(softc->ctl_luns, M_DEVBUF);
2025 	free(softc->ctl_lun_mask, M_DEVBUF);
2026 	free(softc->ctl_port_mask, M_DEVBUF);
2027 	free(softc->ctl_ports, M_DEVBUF);
2028 
2029 	sysctl_ctx_free(&softc->sysctl_ctx);
2030 
2031 	free(softc, M_DEVBUF);
2032 	control_softc = NULL;
2033 	return (0);
2034 }
2035 
2036 static int
2037 ctl_module_event_handler(module_t mod, int what, void *arg)
2038 {
2039 
2040 	switch (what) {
2041 	case MOD_LOAD:
2042 		return (ctl_init());
2043 	case MOD_UNLOAD:
2044 		return (ctl_shutdown());
2045 	default:
2046 		return (EOPNOTSUPP);
2047 	}
2048 }
2049 
2050 /*
2051  * XXX KDM should we do some access checks here?  Bump a reference count to
2052  * prevent a CTL module from being unloaded while someone has it open?
2053  */
2054 static int
2055 ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
2056 {
2057 	return (0);
2058 }
2059 
2060 static int
2061 ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
2062 {
2063 	return (0);
2064 }
2065 
2066 /*
2067  * Remove an initiator by port number and initiator ID.
2068  * Returns 0 for success, -1 for failure.
2069  */
2070 int
2071 ctl_remove_initiator(struct ctl_port *port, int iid)
2072 {
2073 	struct ctl_softc *softc = port->ctl_softc;
2074 	int last;
2075 
2076 	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
2077 
2078 	if (iid > CTL_MAX_INIT_PER_PORT) {
2079 		printf("%s: initiator ID %u > maximun %u!\n",
2080 		       __func__, iid, CTL_MAX_INIT_PER_PORT);
2081 		return (-1);
2082 	}
2083 
2084 	mtx_lock(&softc->ctl_lock);
2085 	last = (--port->wwpn_iid[iid].in_use == 0);
2086 	port->wwpn_iid[iid].last_use = time_uptime;
2087 	mtx_unlock(&softc->ctl_lock);
2088 	if (last)
2089 		ctl_i_t_nexus_loss(softc, iid, CTL_UA_POWERON);
2090 	ctl_isc_announce_iid(port, iid);
2091 
2092 	return (0);
2093 }
2094 
2095 /*
2096  * Add an initiator to the initiator map.
2097  * Returns iid for success, < 0 for failure.
2098  */
2099 int
2100 ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
2101 {
2102 	struct ctl_softc *softc = port->ctl_softc;
2103 	time_t best_time;
2104 	int i, best;
2105 
2106 	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
2107 
2108 	if (iid >= CTL_MAX_INIT_PER_PORT) {
2109 		printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
2110 		       __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
2111 		free(name, M_CTL);
2112 		return (-1);
2113 	}
2114 
2115 	mtx_lock(&softc->ctl_lock);
2116 
2117 	if (iid < 0 && (wwpn != 0 || name != NULL)) {
2118 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2119 			if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
2120 				iid = i;
2121 				break;
2122 			}
2123 			if (name != NULL && port->wwpn_iid[i].name != NULL &&
2124 			    strcmp(name, port->wwpn_iid[i].name) == 0) {
2125 				iid = i;
2126 				break;
2127 			}
2128 		}
2129 	}
2130 
2131 	if (iid < 0) {
2132 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2133 			if (port->wwpn_iid[i].in_use == 0 &&
2134 			    port->wwpn_iid[i].wwpn == 0 &&
2135 			    port->wwpn_iid[i].name == NULL) {
2136 				iid = i;
2137 				break;
2138 			}
2139 		}
2140 	}
2141 
2142 	if (iid < 0) {
2143 		best = -1;
2144 		best_time = INT32_MAX;
2145 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2146 			if (port->wwpn_iid[i].in_use == 0) {
2147 				if (port->wwpn_iid[i].last_use < best_time) {
2148 					best = i;
2149 					best_time = port->wwpn_iid[i].last_use;
2150 				}
2151 			}
2152 		}
2153 		iid = best;
2154 	}
2155 
2156 	if (iid < 0) {
2157 		mtx_unlock(&softc->ctl_lock);
2158 		free(name, M_CTL);
2159 		return (-2);
2160 	}
2161 
2162 	if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
2163 		/*
2164 		 * This is not an error yet.
2165 		 */
2166 		if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
2167 #if 0
2168 			printf("%s: port %d iid %u WWPN %#jx arrived"
2169 			    " again\n", __func__, port->targ_port,
2170 			    iid, (uintmax_t)wwpn);
2171 #endif
2172 			goto take;
2173 		}
2174 		if (name != NULL && port->wwpn_iid[iid].name != NULL &&
2175 		    strcmp(name, port->wwpn_iid[iid].name) == 0) {
2176 #if 0
2177 			printf("%s: port %d iid %u name '%s' arrived"
2178 			    " again\n", __func__, port->targ_port,
2179 			    iid, name);
2180 #endif
2181 			goto take;
2182 		}
2183 
2184 		/*
2185 		 * This is an error, but what do we do about it?  The
2186 		 * driver is telling us we have a new WWPN for this
2187 		 * initiator ID, so we pretty much need to use it.
2188 		 */
2189 		printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
2190 		    " but WWPN %#jx '%s' is still at that address\n",
2191 		    __func__, port->targ_port, iid, wwpn, name,
2192 		    (uintmax_t)port->wwpn_iid[iid].wwpn,
2193 		    port->wwpn_iid[iid].name);
2194 	}
2195 take:
2196 	free(port->wwpn_iid[iid].name, M_CTL);
2197 	port->wwpn_iid[iid].name = name;
2198 	port->wwpn_iid[iid].wwpn = wwpn;
2199 	port->wwpn_iid[iid].in_use++;
2200 	mtx_unlock(&softc->ctl_lock);
2201 	ctl_isc_announce_iid(port, iid);
2202 
2203 	return (iid);
2204 }
2205 
2206 static int
2207 ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
2208 {
2209 	int len;
2210 
2211 	switch (port->port_type) {
2212 	case CTL_PORT_FC:
2213 	{
2214 		struct scsi_transportid_fcp *id =
2215 		    (struct scsi_transportid_fcp *)buf;
2216 		if (port->wwpn_iid[iid].wwpn == 0)
2217 			return (0);
2218 		memset(id, 0, sizeof(*id));
2219 		id->format_protocol = SCSI_PROTO_FC;
2220 		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
2221 		return (sizeof(*id));
2222 	}
2223 	case CTL_PORT_ISCSI:
2224 	{
2225 		struct scsi_transportid_iscsi_port *id =
2226 		    (struct scsi_transportid_iscsi_port *)buf;
2227 		if (port->wwpn_iid[iid].name == NULL)
2228 			return (0);
2229 		memset(id, 0, 256);
2230 		id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
2231 		    SCSI_PROTO_ISCSI;
2232 		len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
2233 		len = roundup2(min(len, 252), 4);
2234 		scsi_ulto2b(len, id->additional_length);
2235 		return (sizeof(*id) + len);
2236 	}
2237 	case CTL_PORT_SAS:
2238 	{
2239 		struct scsi_transportid_sas *id =
2240 		    (struct scsi_transportid_sas *)buf;
2241 		if (port->wwpn_iid[iid].wwpn == 0)
2242 			return (0);
2243 		memset(id, 0, sizeof(*id));
2244 		id->format_protocol = SCSI_PROTO_SAS;
2245 		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
2246 		return (sizeof(*id));
2247 	}
2248 	default:
2249 	{
2250 		struct scsi_transportid_spi *id =
2251 		    (struct scsi_transportid_spi *)buf;
2252 		memset(id, 0, sizeof(*id));
2253 		id->format_protocol = SCSI_PROTO_SPI;
2254 		scsi_ulto2b(iid, id->scsi_addr);
2255 		scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
2256 		return (sizeof(*id));
2257 	}
2258 	}
2259 }
2260 
2261 /*
2262  * Serialize a command that went down the "wrong" side, and so was sent to
2263  * this controller for execution.  The logic is a little different than the
2264  * standard case in ctl_scsiio_precheck().  Errors in this case need to get
2265  * sent back to the other side, but in the success case, we execute the
2266  * command on this side (XFER mode) or tell the other side to execute it
2267  * (SER_ONLY mode).
2268  */
2269 static void
2270 ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
2271 {
2272 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
2273 	struct ctl_port *port = CTL_PORT(ctsio);
2274 	union ctl_ha_msg msg_info;
2275 	struct ctl_lun *lun;
2276 	const struct ctl_cmd_entry *entry;
2277 	union ctl_io *bio;
2278 	uint32_t targ_lun;
2279 
2280 	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
2281 
2282 	/* Make sure that we know about this port. */
2283 	if (port == NULL || (port->status & CTL_PORT_STATUS_ONLINE) == 0) {
2284 		ctl_set_internal_failure(ctsio, /*sks_valid*/ 0,
2285 					 /*retry_count*/ 1);
2286 		goto badjuju;
2287 	}
2288 
2289 	/* Make sure that we know about this LUN. */
2290 	mtx_lock(&softc->ctl_lock);
2291 	if (targ_lun >= ctl_max_luns ||
2292 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
2293 		mtx_unlock(&softc->ctl_lock);
2294 
2295 		/*
2296 		 * The other node would not send this request to us unless
2297 		 * received announce that we are primary node for this LUN.
2298 		 * If this LUN does not exist now, it is probably result of
2299 		 * a race, so respond to initiator in the most opaque way.
2300 		 */
2301 		ctl_set_busy(ctsio);
2302 		goto badjuju;
2303 	}
2304 	mtx_lock(&lun->lun_lock);
2305 	mtx_unlock(&softc->ctl_lock);
2306 
2307 	/*
2308 	 * If the LUN is invalid, pretend that it doesn't exist.
2309 	 * It will go away as soon as all pending I/Os completed.
2310 	 */
2311 	if (lun->flags & CTL_LUN_DISABLED) {
2312 		mtx_unlock(&lun->lun_lock);
2313 		ctl_set_busy(ctsio);
2314 		goto badjuju;
2315 	}
2316 
2317 	entry = ctl_get_cmd_entry(ctsio, NULL);
2318 	if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
2319 		mtx_unlock(&lun->lun_lock);
2320 		goto badjuju;
2321 	}
2322 
2323 	CTL_LUN(ctsio) = lun;
2324 	CTL_BACKEND_LUN(ctsio) = lun->be_lun;
2325 
2326 	/*
2327 	 * Every I/O goes into the OOA queue for a
2328 	 * particular LUN, and stays there until completion.
2329 	 */
2330 #ifdef CTL_TIME_IO
2331 	if (TAILQ_EMPTY(&lun->ooa_queue))
2332 		lun->idle_time += getsbinuptime() - lun->last_busy;
2333 #endif
2334 	TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2335 
2336 	bio = (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq, ooa_links);
2337 	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio, &bio)) {
2338 	case CTL_ACTION_BLOCK:
2339 		ctsio->io_hdr.blocker = bio;
2340 		TAILQ_INSERT_TAIL(&bio->io_hdr.blocked_queue, &ctsio->io_hdr,
2341 				  blocked_links);
2342 		mtx_unlock(&lun->lun_lock);
2343 		break;
2344 	case CTL_ACTION_PASS:
2345 	case CTL_ACTION_SKIP:
2346 		if (softc->ha_mode == CTL_HA_MODE_XFER) {
2347 			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
2348 			ctl_enqueue_rtr((union ctl_io *)ctsio);
2349 			mtx_unlock(&lun->lun_lock);
2350 		} else {
2351 			ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
2352 			mtx_unlock(&lun->lun_lock);
2353 
2354 			/* send msg back to other side */
2355 			msg_info.hdr.original_sc = ctsio->io_hdr.remote_io;
2356 			msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
2357 			msg_info.hdr.msg_type = CTL_MSG_R2R;
2358 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2359 			    sizeof(msg_info.hdr), M_WAITOK);
2360 		}
2361 		break;
2362 	case CTL_ACTION_OVERLAP:
2363 		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2364 		mtx_unlock(&lun->lun_lock);
2365 		ctl_set_overlapped_cmd(ctsio);
2366 		goto badjuju;
2367 	case CTL_ACTION_OVERLAP_TAG:
2368 		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2369 		mtx_unlock(&lun->lun_lock);
2370 		ctl_set_overlapped_tag(ctsio, ctsio->tag_num);
2371 		goto badjuju;
2372 	case CTL_ACTION_ERROR:
2373 	default:
2374 		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2375 		mtx_unlock(&lun->lun_lock);
2376 
2377 		ctl_set_internal_failure(ctsio, /*sks_valid*/ 0,
2378 					 /*retry_count*/ 0);
2379 badjuju:
2380 		ctl_copy_sense_data_back((union ctl_io *)ctsio, &msg_info);
2381 		msg_info.hdr.original_sc = ctsio->io_hdr.remote_io;
2382 		msg_info.hdr.serializing_sc = NULL;
2383 		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
2384 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2385 		    sizeof(msg_info.scsi), M_WAITOK);
2386 		ctl_free_io((union ctl_io *)ctsio);
2387 		break;
2388 	}
2389 }
2390 
2391 /*
2392  * Returns 0 for success, errno for failure.
2393  */
2394 static void
2395 ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2396 		   struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2397 {
2398 	union ctl_io *io;
2399 
2400 	mtx_lock(&lun->lun_lock);
2401 	for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
2402 	     (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2403 	     ooa_links)) {
2404 		struct ctl_ooa_entry *entry;
2405 
2406 		/*
2407 		 * If we've got more than we can fit, just count the
2408 		 * remaining entries.
2409 		 */
2410 		if (*cur_fill_num >= ooa_hdr->alloc_num)
2411 			continue;
2412 
2413 		entry = &kern_entries[*cur_fill_num];
2414 
2415 		entry->tag_num = io->scsiio.tag_num;
2416 		entry->lun_num = lun->lun;
2417 #ifdef CTL_TIME_IO
2418 		entry->start_bt = io->io_hdr.start_bt;
2419 #endif
2420 		bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2421 		entry->cdb_len = io->scsiio.cdb_len;
2422 		if (io->io_hdr.blocker != NULL)
2423 			entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2424 
2425 		if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2426 			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2427 
2428 		if (io->io_hdr.flags & CTL_FLAG_ABORT)
2429 			entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2430 
2431 		if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2432 			entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2433 
2434 		if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2435 			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2436 
2437 		if (io->io_hdr.flags & CTL_FLAG_STATUS_QUEUED)
2438 			entry->cmd_flags |= CTL_OOACMD_FLAG_STATUS_QUEUED;
2439 
2440 		if (io->io_hdr.flags & CTL_FLAG_STATUS_SENT)
2441 			entry->cmd_flags |= CTL_OOACMD_FLAG_STATUS_SENT;
2442 	}
2443 	mtx_unlock(&lun->lun_lock);
2444 }
2445 
2446 /*
2447  * Escape characters that are illegal or not recommended in XML.
2448  */
2449 int
2450 ctl_sbuf_printf_esc(struct sbuf *sb, char *str, int size)
2451 {
2452 	char *end = str + size;
2453 	int retval;
2454 
2455 	retval = 0;
2456 
2457 	for (; *str && str < end; str++) {
2458 		switch (*str) {
2459 		case '&':
2460 			retval = sbuf_printf(sb, "&amp;");
2461 			break;
2462 		case '>':
2463 			retval = sbuf_printf(sb, "&gt;");
2464 			break;
2465 		case '<':
2466 			retval = sbuf_printf(sb, "&lt;");
2467 			break;
2468 		default:
2469 			retval = sbuf_putc(sb, *str);
2470 			break;
2471 		}
2472 
2473 		if (retval != 0)
2474 			break;
2475 
2476 	}
2477 
2478 	return (retval);
2479 }
2480 
2481 static void
2482 ctl_id_sbuf(struct ctl_devid *id, struct sbuf *sb)
2483 {
2484 	struct scsi_vpd_id_descriptor *desc;
2485 	int i;
2486 
2487 	if (id == NULL || id->len < 4)
2488 		return;
2489 	desc = (struct scsi_vpd_id_descriptor *)id->data;
2490 	switch (desc->id_type & SVPD_ID_TYPE_MASK) {
2491 	case SVPD_ID_TYPE_T10:
2492 		sbuf_printf(sb, "t10.");
2493 		break;
2494 	case SVPD_ID_TYPE_EUI64:
2495 		sbuf_printf(sb, "eui.");
2496 		break;
2497 	case SVPD_ID_TYPE_NAA:
2498 		sbuf_printf(sb, "naa.");
2499 		break;
2500 	case SVPD_ID_TYPE_SCSI_NAME:
2501 		break;
2502 	}
2503 	switch (desc->proto_codeset & SVPD_ID_CODESET_MASK) {
2504 	case SVPD_ID_CODESET_BINARY:
2505 		for (i = 0; i < desc->length; i++)
2506 			sbuf_printf(sb, "%02x", desc->identifier[i]);
2507 		break;
2508 	case SVPD_ID_CODESET_ASCII:
2509 		sbuf_printf(sb, "%.*s", (int)desc->length,
2510 		    (char *)desc->identifier);
2511 		break;
2512 	case SVPD_ID_CODESET_UTF8:
2513 		sbuf_printf(sb, "%s", (char *)desc->identifier);
2514 		break;
2515 	}
2516 }
2517 
2518 static int
2519 ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2520 	  struct thread *td)
2521 {
2522 	struct ctl_softc *softc = dev->si_drv1;
2523 	struct ctl_port *port;
2524 	struct ctl_lun *lun;
2525 	int retval;
2526 
2527 	retval = 0;
2528 
2529 	switch (cmd) {
2530 	case CTL_IO:
2531 		retval = ctl_ioctl_io(dev, cmd, addr, flag, td);
2532 		break;
2533 	case CTL_ENABLE_PORT:
2534 	case CTL_DISABLE_PORT:
2535 	case CTL_SET_PORT_WWNS: {
2536 		struct ctl_port *port;
2537 		struct ctl_port_entry *entry;
2538 
2539 		entry = (struct ctl_port_entry *)addr;
2540 
2541 		mtx_lock(&softc->ctl_lock);
2542 		STAILQ_FOREACH(port, &softc->port_list, links) {
2543 			int action, done;
2544 
2545 			if (port->targ_port < softc->port_min ||
2546 			    port->targ_port >= softc->port_max)
2547 				continue;
2548 
2549 			action = 0;
2550 			done = 0;
2551 			if ((entry->port_type == CTL_PORT_NONE)
2552 			 && (entry->targ_port == port->targ_port)) {
2553 				/*
2554 				 * If the user only wants to enable or
2555 				 * disable or set WWNs on a specific port,
2556 				 * do the operation and we're done.
2557 				 */
2558 				action = 1;
2559 				done = 1;
2560 			} else if (entry->port_type & port->port_type) {
2561 				/*
2562 				 * Compare the user's type mask with the
2563 				 * particular frontend type to see if we
2564 				 * have a match.
2565 				 */
2566 				action = 1;
2567 				done = 0;
2568 
2569 				/*
2570 				 * Make sure the user isn't trying to set
2571 				 * WWNs on multiple ports at the same time.
2572 				 */
2573 				if (cmd == CTL_SET_PORT_WWNS) {
2574 					printf("%s: Can't set WWNs on "
2575 					       "multiple ports\n", __func__);
2576 					retval = EINVAL;
2577 					break;
2578 				}
2579 			}
2580 			if (action == 0)
2581 				continue;
2582 
2583 			/*
2584 			 * XXX KDM we have to drop the lock here, because
2585 			 * the online/offline operations can potentially
2586 			 * block.  We need to reference count the frontends
2587 			 * so they can't go away,
2588 			 */
2589 			if (cmd == CTL_ENABLE_PORT) {
2590 				mtx_unlock(&softc->ctl_lock);
2591 				ctl_port_online(port);
2592 				mtx_lock(&softc->ctl_lock);
2593 			} else if (cmd == CTL_DISABLE_PORT) {
2594 				mtx_unlock(&softc->ctl_lock);
2595 				ctl_port_offline(port);
2596 				mtx_lock(&softc->ctl_lock);
2597 			} else if (cmd == CTL_SET_PORT_WWNS) {
2598 				ctl_port_set_wwns(port,
2599 				    (entry->flags & CTL_PORT_WWNN_VALID) ?
2600 				    1 : 0, entry->wwnn,
2601 				    (entry->flags & CTL_PORT_WWPN_VALID) ?
2602 				    1 : 0, entry->wwpn);
2603 			}
2604 			if (done != 0)
2605 				break;
2606 		}
2607 		mtx_unlock(&softc->ctl_lock);
2608 		break;
2609 	}
2610 	case CTL_GET_OOA: {
2611 		struct ctl_ooa *ooa_hdr;
2612 		struct ctl_ooa_entry *entries;
2613 		uint32_t cur_fill_num;
2614 
2615 		ooa_hdr = (struct ctl_ooa *)addr;
2616 
2617 		if ((ooa_hdr->alloc_len == 0)
2618 		 || (ooa_hdr->alloc_num == 0)) {
2619 			printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2620 			       "must be non-zero\n", __func__,
2621 			       ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2622 			retval = EINVAL;
2623 			break;
2624 		}
2625 
2626 		if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2627 		    sizeof(struct ctl_ooa_entry))) {
2628 			printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2629 			       "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2630 			       __func__, ooa_hdr->alloc_len,
2631 			       ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2632 			retval = EINVAL;
2633 			break;
2634 		}
2635 
2636 		entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2637 		if (entries == NULL) {
2638 			printf("%s: could not allocate %d bytes for OOA "
2639 			       "dump\n", __func__, ooa_hdr->alloc_len);
2640 			retval = ENOMEM;
2641 			break;
2642 		}
2643 
2644 		mtx_lock(&softc->ctl_lock);
2645 		if ((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0 &&
2646 		    (ooa_hdr->lun_num >= ctl_max_luns ||
2647 		     softc->ctl_luns[ooa_hdr->lun_num] == NULL)) {
2648 			mtx_unlock(&softc->ctl_lock);
2649 			free(entries, M_CTL);
2650 			printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2651 			       __func__, (uintmax_t)ooa_hdr->lun_num);
2652 			retval = EINVAL;
2653 			break;
2654 		}
2655 
2656 		cur_fill_num = 0;
2657 
2658 		if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2659 			STAILQ_FOREACH(lun, &softc->lun_list, links) {
2660 				ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2661 				    ooa_hdr, entries);
2662 			}
2663 		} else {
2664 			lun = softc->ctl_luns[ooa_hdr->lun_num];
2665 			ctl_ioctl_fill_ooa(lun, &cur_fill_num, ooa_hdr,
2666 			    entries);
2667 		}
2668 		mtx_unlock(&softc->ctl_lock);
2669 
2670 		ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2671 		ooa_hdr->fill_len = ooa_hdr->fill_num *
2672 			sizeof(struct ctl_ooa_entry);
2673 		retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2674 		if (retval != 0) {
2675 			printf("%s: error copying out %d bytes for OOA dump\n",
2676 			       __func__, ooa_hdr->fill_len);
2677 		}
2678 
2679 		getbinuptime(&ooa_hdr->cur_bt);
2680 
2681 		if (cur_fill_num > ooa_hdr->alloc_num) {
2682 			ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2683 			ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2684 		} else {
2685 			ooa_hdr->dropped_num = 0;
2686 			ooa_hdr->status = CTL_OOA_OK;
2687 		}
2688 
2689 		free(entries, M_CTL);
2690 		break;
2691 	}
2692 	case CTL_DELAY_IO: {
2693 		struct ctl_io_delay_info *delay_info;
2694 
2695 		delay_info = (struct ctl_io_delay_info *)addr;
2696 
2697 #ifdef CTL_IO_DELAY
2698 		mtx_lock(&softc->ctl_lock);
2699 		if (delay_info->lun_id >= ctl_max_luns ||
2700 		    (lun = softc->ctl_luns[delay_info->lun_id]) == NULL) {
2701 			mtx_unlock(&softc->ctl_lock);
2702 			delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2703 			break;
2704 		}
2705 		mtx_lock(&lun->lun_lock);
2706 		mtx_unlock(&softc->ctl_lock);
2707 		delay_info->status = CTL_DELAY_STATUS_OK;
2708 		switch (delay_info->delay_type) {
2709 		case CTL_DELAY_TYPE_CONT:
2710 		case CTL_DELAY_TYPE_ONESHOT:
2711 			break;
2712 		default:
2713 			delay_info->status = CTL_DELAY_STATUS_INVALID_TYPE;
2714 			break;
2715 		}
2716 		switch (delay_info->delay_loc) {
2717 		case CTL_DELAY_LOC_DATAMOVE:
2718 			lun->delay_info.datamove_type = delay_info->delay_type;
2719 			lun->delay_info.datamove_delay = delay_info->delay_secs;
2720 			break;
2721 		case CTL_DELAY_LOC_DONE:
2722 			lun->delay_info.done_type = delay_info->delay_type;
2723 			lun->delay_info.done_delay = delay_info->delay_secs;
2724 			break;
2725 		default:
2726 			delay_info->status = CTL_DELAY_STATUS_INVALID_LOC;
2727 			break;
2728 		}
2729 		mtx_unlock(&lun->lun_lock);
2730 #else
2731 		delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2732 #endif /* CTL_IO_DELAY */
2733 		break;
2734 	}
2735 	case CTL_ERROR_INJECT: {
2736 		struct ctl_error_desc *err_desc, *new_err_desc;
2737 
2738 		err_desc = (struct ctl_error_desc *)addr;
2739 
2740 		new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2741 				      M_WAITOK | M_ZERO);
2742 		bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2743 
2744 		mtx_lock(&softc->ctl_lock);
2745 		if (err_desc->lun_id >= ctl_max_luns ||
2746 		    (lun = softc->ctl_luns[err_desc->lun_id]) == NULL) {
2747 			mtx_unlock(&softc->ctl_lock);
2748 			free(new_err_desc, M_CTL);
2749 			printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
2750 			       __func__, (uintmax_t)err_desc->lun_id);
2751 			retval = EINVAL;
2752 			break;
2753 		}
2754 		mtx_lock(&lun->lun_lock);
2755 		mtx_unlock(&softc->ctl_lock);
2756 
2757 		/*
2758 		 * We could do some checking here to verify the validity
2759 		 * of the request, but given the complexity of error
2760 		 * injection requests, the checking logic would be fairly
2761 		 * complex.
2762 		 *
2763 		 * For now, if the request is invalid, it just won't get
2764 		 * executed and might get deleted.
2765 		 */
2766 		STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
2767 
2768 		/*
2769 		 * XXX KDM check to make sure the serial number is unique,
2770 		 * in case we somehow manage to wrap.  That shouldn't
2771 		 * happen for a very long time, but it's the right thing to
2772 		 * do.
2773 		 */
2774 		new_err_desc->serial = lun->error_serial;
2775 		err_desc->serial = lun->error_serial;
2776 		lun->error_serial++;
2777 
2778 		mtx_unlock(&lun->lun_lock);
2779 		break;
2780 	}
2781 	case CTL_ERROR_INJECT_DELETE: {
2782 		struct ctl_error_desc *delete_desc, *desc, *desc2;
2783 		int delete_done;
2784 
2785 		delete_desc = (struct ctl_error_desc *)addr;
2786 		delete_done = 0;
2787 
2788 		mtx_lock(&softc->ctl_lock);
2789 		if (delete_desc->lun_id >= ctl_max_luns ||
2790 		    (lun = softc->ctl_luns[delete_desc->lun_id]) == NULL) {
2791 			mtx_unlock(&softc->ctl_lock);
2792 			printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
2793 			       __func__, (uintmax_t)delete_desc->lun_id);
2794 			retval = EINVAL;
2795 			break;
2796 		}
2797 		mtx_lock(&lun->lun_lock);
2798 		mtx_unlock(&softc->ctl_lock);
2799 		STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
2800 			if (desc->serial != delete_desc->serial)
2801 				continue;
2802 
2803 			STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
2804 				      links);
2805 			free(desc, M_CTL);
2806 			delete_done = 1;
2807 		}
2808 		mtx_unlock(&lun->lun_lock);
2809 		if (delete_done == 0) {
2810 			printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
2811 			       "error serial %ju on LUN %u\n", __func__,
2812 			       delete_desc->serial, delete_desc->lun_id);
2813 			retval = EINVAL;
2814 			break;
2815 		}
2816 		break;
2817 	}
2818 	case CTL_DUMP_STRUCTS: {
2819 		int j, k;
2820 		struct ctl_port *port;
2821 		struct ctl_frontend *fe;
2822 
2823 		mtx_lock(&softc->ctl_lock);
2824 		printf("CTL Persistent Reservation information start:\n");
2825 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
2826 			mtx_lock(&lun->lun_lock);
2827 			if ((lun->flags & CTL_LUN_DISABLED) != 0) {
2828 				mtx_unlock(&lun->lun_lock);
2829 				continue;
2830 			}
2831 
2832 			for (j = 0; j < ctl_max_ports; j++) {
2833 				if (lun->pr_keys[j] == NULL)
2834 					continue;
2835 				for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
2836 					if (lun->pr_keys[j][k] == 0)
2837 						continue;
2838 					printf("  LUN %ju port %d iid %d key "
2839 					       "%#jx\n", lun->lun, j, k,
2840 					       (uintmax_t)lun->pr_keys[j][k]);
2841 				}
2842 			}
2843 			mtx_unlock(&lun->lun_lock);
2844 		}
2845 		printf("CTL Persistent Reservation information end\n");
2846 		printf("CTL Ports:\n");
2847 		STAILQ_FOREACH(port, &softc->port_list, links) {
2848 			printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
2849 			       "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
2850 			       port->frontend->name, port->port_type,
2851 			       port->physical_port, port->virtual_port,
2852 			       (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
2853 			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
2854 				if (port->wwpn_iid[j].in_use == 0 &&
2855 				    port->wwpn_iid[j].wwpn == 0 &&
2856 				    port->wwpn_iid[j].name == NULL)
2857 					continue;
2858 
2859 				printf("    iid %u use %d WWPN %#jx '%s'\n",
2860 				    j, port->wwpn_iid[j].in_use,
2861 				    (uintmax_t)port->wwpn_iid[j].wwpn,
2862 				    port->wwpn_iid[j].name);
2863 			}
2864 		}
2865 		printf("CTL Port information end\n");
2866 		mtx_unlock(&softc->ctl_lock);
2867 		/*
2868 		 * XXX KDM calling this without a lock.  We'd likely want
2869 		 * to drop the lock before calling the frontend's dump
2870 		 * routine anyway.
2871 		 */
2872 		printf("CTL Frontends:\n");
2873 		STAILQ_FOREACH(fe, &softc->fe_list, links) {
2874 			printf("  Frontend '%s'\n", fe->name);
2875 			if (fe->fe_dump != NULL)
2876 				fe->fe_dump();
2877 		}
2878 		printf("CTL Frontend information end\n");
2879 		break;
2880 	}
2881 	case CTL_LUN_REQ: {
2882 		struct ctl_lun_req *lun_req;
2883 		struct ctl_backend_driver *backend;
2884 		void *packed;
2885 		nvlist_t *tmp_args_nvl;
2886 		size_t packed_len;
2887 
2888 		lun_req = (struct ctl_lun_req *)addr;
2889 		tmp_args_nvl = lun_req->args_nvl;
2890 
2891 		backend = ctl_backend_find(lun_req->backend);
2892 		if (backend == NULL) {
2893 			lun_req->status = CTL_LUN_ERROR;
2894 			snprintf(lun_req->error_str,
2895 				 sizeof(lun_req->error_str),
2896 				 "Backend \"%s\" not found.",
2897 				 lun_req->backend);
2898 			break;
2899 		}
2900 
2901 		if (lun_req->args != NULL) {
2902 			packed = malloc(lun_req->args_len, M_CTL, M_WAITOK);
2903 			if (copyin(lun_req->args, packed, lun_req->args_len) != 0) {
2904 				free(packed, M_CTL);
2905 				lun_req->status = CTL_LUN_ERROR;
2906 				snprintf(lun_req->error_str, sizeof(lun_req->error_str),
2907 				    "Cannot copyin args.");
2908 				break;
2909 			}
2910 			lun_req->args_nvl = nvlist_unpack(packed,
2911 			    lun_req->args_len, 0);
2912 			free(packed, M_CTL);
2913 
2914 			if (lun_req->args_nvl == NULL) {
2915 				lun_req->status = CTL_LUN_ERROR;
2916 				snprintf(lun_req->error_str, sizeof(lun_req->error_str),
2917 				    "Cannot unpack args nvlist.");
2918 				break;
2919 			}
2920 		} else
2921 			lun_req->args_nvl = nvlist_create(0);
2922 
2923 		retval = backend->ioctl(dev, cmd, addr, flag, td);
2924 		nvlist_destroy(lun_req->args_nvl);
2925 		lun_req->args_nvl = tmp_args_nvl;
2926 
2927 		if (lun_req->result_nvl != NULL) {
2928 			if (lun_req->result != NULL) {
2929 				packed = nvlist_pack(lun_req->result_nvl,
2930 				    &packed_len);
2931 				if (packed == NULL) {
2932 					lun_req->status = CTL_LUN_ERROR;
2933 					snprintf(lun_req->error_str,
2934 					    sizeof(lun_req->error_str),
2935 					    "Cannot pack result nvlist.");
2936 					break;
2937 				}
2938 
2939 				if (packed_len > lun_req->result_len) {
2940 					lun_req->status = CTL_LUN_ERROR;
2941 					snprintf(lun_req->error_str,
2942 					    sizeof(lun_req->error_str),
2943 					    "Result nvlist too large.");
2944 					free(packed, M_NVLIST);
2945 					break;
2946 				}
2947 
2948 				if (copyout(packed, lun_req->result, packed_len)) {
2949 					lun_req->status = CTL_LUN_ERROR;
2950 					snprintf(lun_req->error_str,
2951 					    sizeof(lun_req->error_str),
2952 					    "Cannot copyout() the result.");
2953 					free(packed, M_NVLIST);
2954 					break;
2955 				}
2956 
2957 				lun_req->result_len = packed_len;
2958 				free(packed, M_NVLIST);
2959 			}
2960 
2961 			nvlist_destroy(lun_req->result_nvl);
2962 		}
2963 		break;
2964 	}
2965 	case CTL_LUN_LIST: {
2966 		struct sbuf *sb;
2967 		struct ctl_lun_list *list;
2968 		const char *name, *value;
2969 		void *cookie;
2970 		int type;
2971 
2972 		list = (struct ctl_lun_list *)addr;
2973 
2974 		/*
2975 		 * Allocate a fixed length sbuf here, based on the length
2976 		 * of the user's buffer.  We could allocate an auto-extending
2977 		 * buffer, and then tell the user how much larger our
2978 		 * amount of data is than his buffer, but that presents
2979 		 * some problems:
2980 		 *
2981 		 * 1.  The sbuf(9) routines use a blocking malloc, and so
2982 		 *     we can't hold a lock while calling them with an
2983 		 *     auto-extending buffer.
2984  		 *
2985 		 * 2.  There is not currently a LUN reference counting
2986 		 *     mechanism, outside of outstanding transactions on
2987 		 *     the LUN's OOA queue.  So a LUN could go away on us
2988 		 *     while we're getting the LUN number, backend-specific
2989 		 *     information, etc.  Thus, given the way things
2990 		 *     currently work, we need to hold the CTL lock while
2991 		 *     grabbing LUN information.
2992 		 *
2993 		 * So, from the user's standpoint, the best thing to do is
2994 		 * allocate what he thinks is a reasonable buffer length,
2995 		 * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
2996 		 * double the buffer length and try again.  (And repeat
2997 		 * that until he succeeds.)
2998 		 */
2999 		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3000 		if (sb == NULL) {
3001 			list->status = CTL_LUN_LIST_ERROR;
3002 			snprintf(list->error_str, sizeof(list->error_str),
3003 				 "Unable to allocate %d bytes for LUN list",
3004 				 list->alloc_len);
3005 			break;
3006 		}
3007 
3008 		sbuf_printf(sb, "<ctllunlist>\n");
3009 
3010 		mtx_lock(&softc->ctl_lock);
3011 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
3012 			mtx_lock(&lun->lun_lock);
3013 			retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3014 					     (uintmax_t)lun->lun);
3015 
3016 			/*
3017 			 * Bail out as soon as we see that we've overfilled
3018 			 * the buffer.
3019 			 */
3020 			if (retval != 0)
3021 				break;
3022 
3023 			retval = sbuf_printf(sb, "\t<backend_type>%s"
3024 					     "</backend_type>\n",
3025 					     (lun->backend == NULL) ?  "none" :
3026 					     lun->backend->name);
3027 
3028 			if (retval != 0)
3029 				break;
3030 
3031 			retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3032 					     lun->be_lun->lun_type);
3033 
3034 			if (retval != 0)
3035 				break;
3036 
3037 			if (lun->backend == NULL) {
3038 				retval = sbuf_printf(sb, "</lun>\n");
3039 				if (retval != 0)
3040 					break;
3041 				continue;
3042 			}
3043 
3044 			retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3045 					     (lun->be_lun->maxlba > 0) ?
3046 					     lun->be_lun->maxlba + 1 : 0);
3047 
3048 			if (retval != 0)
3049 				break;
3050 
3051 			retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3052 					     lun->be_lun->blocksize);
3053 
3054 			if (retval != 0)
3055 				break;
3056 
3057 			retval = sbuf_printf(sb, "\t<serial_number>");
3058 
3059 			if (retval != 0)
3060 				break;
3061 
3062 			retval = ctl_sbuf_printf_esc(sb,
3063 			    lun->be_lun->serial_num,
3064 			    sizeof(lun->be_lun->serial_num));
3065 
3066 			if (retval != 0)
3067 				break;
3068 
3069 			retval = sbuf_printf(sb, "</serial_number>\n");
3070 
3071 			if (retval != 0)
3072 				break;
3073 
3074 			retval = sbuf_printf(sb, "\t<device_id>");
3075 
3076 			if (retval != 0)
3077 				break;
3078 
3079 			retval = ctl_sbuf_printf_esc(sb,
3080 			    lun->be_lun->device_id,
3081 			    sizeof(lun->be_lun->device_id));
3082 
3083 			if (retval != 0)
3084 				break;
3085 
3086 			retval = sbuf_printf(sb, "</device_id>\n");
3087 
3088 			if (retval != 0)
3089 				break;
3090 
3091 			if (lun->backend->lun_info != NULL) {
3092 				retval = lun->backend->lun_info(lun->be_lun, sb);
3093 				if (retval != 0)
3094 					break;
3095 			}
3096 
3097 			cookie = NULL;
3098 			while ((name = nvlist_next(lun->be_lun->options, &type,
3099 			    &cookie)) != NULL) {
3100 				sbuf_printf(sb, "\t<%s>", name);
3101 
3102 				if (type == NV_TYPE_STRING) {
3103 					value = dnvlist_get_string(
3104 					    lun->be_lun->options, name, NULL);
3105 					if (value != NULL)
3106 						sbuf_printf(sb, "%s", value);
3107 				}
3108 
3109 				sbuf_printf(sb, "</%s>\n", name);
3110 			}
3111 
3112 			retval = sbuf_printf(sb, "</lun>\n");
3113 
3114 			if (retval != 0)
3115 				break;
3116 			mtx_unlock(&lun->lun_lock);
3117 		}
3118 		if (lun != NULL)
3119 			mtx_unlock(&lun->lun_lock);
3120 		mtx_unlock(&softc->ctl_lock);
3121 
3122 		if ((retval != 0)
3123 		 || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3124 			retval = 0;
3125 			sbuf_delete(sb);
3126 			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3127 			snprintf(list->error_str, sizeof(list->error_str),
3128 				 "Out of space, %d bytes is too small",
3129 				 list->alloc_len);
3130 			break;
3131 		}
3132 
3133 		sbuf_finish(sb);
3134 
3135 		retval = copyout(sbuf_data(sb), list->lun_xml,
3136 				 sbuf_len(sb) + 1);
3137 
3138 		list->fill_len = sbuf_len(sb) + 1;
3139 		list->status = CTL_LUN_LIST_OK;
3140 		sbuf_delete(sb);
3141 		break;
3142 	}
3143 	case CTL_ISCSI: {
3144 		struct ctl_iscsi *ci;
3145 		struct ctl_frontend *fe;
3146 
3147 		ci = (struct ctl_iscsi *)addr;
3148 
3149 		fe = ctl_frontend_find("iscsi");
3150 		if (fe == NULL) {
3151 			ci->status = CTL_ISCSI_ERROR;
3152 			snprintf(ci->error_str, sizeof(ci->error_str),
3153 			    "Frontend \"iscsi\" not found.");
3154 			break;
3155 		}
3156 
3157 		retval = fe->ioctl(dev, cmd, addr, flag, td);
3158 		break;
3159 	}
3160 	case CTL_PORT_REQ: {
3161 		struct ctl_req *req;
3162 		struct ctl_frontend *fe;
3163 		void *packed;
3164 		nvlist_t *tmp_args_nvl;
3165 		size_t packed_len;
3166 
3167 		req = (struct ctl_req *)addr;
3168 		tmp_args_nvl = req->args_nvl;
3169 
3170 		fe = ctl_frontend_find(req->driver);
3171 		if (fe == NULL) {
3172 			req->status = CTL_LUN_ERROR;
3173 			snprintf(req->error_str, sizeof(req->error_str),
3174 			    "Frontend \"%s\" not found.", req->driver);
3175 			break;
3176 		}
3177 
3178 		if (req->args != NULL) {
3179 			packed = malloc(req->args_len, M_CTL, M_WAITOK);
3180 			if (copyin(req->args, packed, req->args_len) != 0) {
3181 				free(packed, M_CTL);
3182 				req->status = CTL_LUN_ERROR;
3183 				snprintf(req->error_str, sizeof(req->error_str),
3184 				    "Cannot copyin args.");
3185 				break;
3186 			}
3187 			req->args_nvl = nvlist_unpack(packed,
3188 			    req->args_len, 0);
3189 			free(packed, M_CTL);
3190 
3191 			if (req->args_nvl == NULL) {
3192 				req->status = CTL_LUN_ERROR;
3193 				snprintf(req->error_str, sizeof(req->error_str),
3194 				    "Cannot unpack args nvlist.");
3195 				break;
3196 			}
3197 		} else
3198 			req->args_nvl = nvlist_create(0);
3199 
3200 		if (fe->ioctl)
3201 			retval = fe->ioctl(dev, cmd, addr, flag, td);
3202 		else
3203 			retval = ENODEV;
3204 
3205 		nvlist_destroy(req->args_nvl);
3206 		req->args_nvl = tmp_args_nvl;
3207 
3208 		if (req->result_nvl != NULL) {
3209 			if (req->result != NULL) {
3210 				packed = nvlist_pack(req->result_nvl,
3211 				    &packed_len);
3212 				if (packed == NULL) {
3213 					req->status = CTL_LUN_ERROR;
3214 					snprintf(req->error_str,
3215 					    sizeof(req->error_str),
3216 					    "Cannot pack result nvlist.");
3217 					break;
3218 				}
3219 
3220 				if (packed_len > req->result_len) {
3221 					req->status = CTL_LUN_ERROR;
3222 					snprintf(req->error_str,
3223 					    sizeof(req->error_str),
3224 					    "Result nvlist too large.");
3225 					free(packed, M_NVLIST);
3226 					break;
3227 				}
3228 
3229 				if (copyout(packed, req->result, packed_len)) {
3230 					req->status = CTL_LUN_ERROR;
3231 					snprintf(req->error_str,
3232 					    sizeof(req->error_str),
3233 					    "Cannot copyout() the result.");
3234 					free(packed, M_NVLIST);
3235 					break;
3236 				}
3237 
3238 				req->result_len = packed_len;
3239 				free(packed, M_NVLIST);
3240 			}
3241 
3242 			nvlist_destroy(req->result_nvl);
3243 		}
3244 		break;
3245 	}
3246 	case CTL_PORT_LIST: {
3247 		struct sbuf *sb;
3248 		struct ctl_port *port;
3249 		struct ctl_lun_list *list;
3250 		const char *name, *value;
3251 		void *cookie;
3252 		int j, type;
3253 		uint32_t plun;
3254 
3255 		list = (struct ctl_lun_list *)addr;
3256 
3257 		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3258 		if (sb == NULL) {
3259 			list->status = CTL_LUN_LIST_ERROR;
3260 			snprintf(list->error_str, sizeof(list->error_str),
3261 				 "Unable to allocate %d bytes for LUN list",
3262 				 list->alloc_len);
3263 			break;
3264 		}
3265 
3266 		sbuf_printf(sb, "<ctlportlist>\n");
3267 
3268 		mtx_lock(&softc->ctl_lock);
3269 		STAILQ_FOREACH(port, &softc->port_list, links) {
3270 			retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3271 					     (uintmax_t)port->targ_port);
3272 
3273 			/*
3274 			 * Bail out as soon as we see that we've overfilled
3275 			 * the buffer.
3276 			 */
3277 			if (retval != 0)
3278 				break;
3279 
3280 			retval = sbuf_printf(sb, "\t<frontend_type>%s"
3281 			    "</frontend_type>\n", port->frontend->name);
3282 			if (retval != 0)
3283 				break;
3284 
3285 			retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3286 					     port->port_type);
3287 			if (retval != 0)
3288 				break;
3289 
3290 			retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3291 			    (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3292 			if (retval != 0)
3293 				break;
3294 
3295 			retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3296 			    port->port_name);
3297 			if (retval != 0)
3298 				break;
3299 
3300 			retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3301 			    port->physical_port);
3302 			if (retval != 0)
3303 				break;
3304 
3305 			retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3306 			    port->virtual_port);
3307 			if (retval != 0)
3308 				break;
3309 
3310 			if (port->target_devid != NULL) {
3311 				sbuf_printf(sb, "\t<target>");
3312 				ctl_id_sbuf(port->target_devid, sb);
3313 				sbuf_printf(sb, "</target>\n");
3314 			}
3315 
3316 			if (port->port_devid != NULL) {
3317 				sbuf_printf(sb, "\t<port>");
3318 				ctl_id_sbuf(port->port_devid, sb);
3319 				sbuf_printf(sb, "</port>\n");
3320 			}
3321 
3322 			if (port->port_info != NULL) {
3323 				retval = port->port_info(port->onoff_arg, sb);
3324 				if (retval != 0)
3325 					break;
3326 			}
3327 
3328 			cookie = NULL;
3329 			while ((name = nvlist_next(port->options, &type,
3330 			    &cookie)) != NULL) {
3331 				sbuf_printf(sb, "\t<%s>", name);
3332 
3333 				if (type == NV_TYPE_STRING) {
3334 					value = dnvlist_get_string(port->options,
3335 					    name, NULL);
3336 					if (value != NULL)
3337 						sbuf_printf(sb, "%s", value);
3338 				}
3339 
3340 				sbuf_printf(sb, "</%s>\n", name);
3341 			}
3342 
3343 			if (port->lun_map != NULL) {
3344 				sbuf_printf(sb, "\t<lun_map>on</lun_map>\n");
3345 				for (j = 0; j < port->lun_map_size; j++) {
3346 					plun = ctl_lun_map_from_port(port, j);
3347 					if (plun == UINT32_MAX)
3348 						continue;
3349 					sbuf_printf(sb,
3350 					    "\t<lun id=\"%u\">%u</lun>\n",
3351 					    j, plun);
3352 				}
3353 			}
3354 
3355 			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3356 				if (port->wwpn_iid[j].in_use == 0 ||
3357 				    (port->wwpn_iid[j].wwpn == 0 &&
3358 				     port->wwpn_iid[j].name == NULL))
3359 					continue;
3360 
3361 				if (port->wwpn_iid[j].name != NULL)
3362 					retval = sbuf_printf(sb,
3363 					    "\t<initiator id=\"%u\">%s</initiator>\n",
3364 					    j, port->wwpn_iid[j].name);
3365 				else
3366 					retval = sbuf_printf(sb,
3367 					    "\t<initiator id=\"%u\">naa.%08jx</initiator>\n",
3368 					    j, port->wwpn_iid[j].wwpn);
3369 				if (retval != 0)
3370 					break;
3371 			}
3372 			if (retval != 0)
3373 				break;
3374 
3375 			retval = sbuf_printf(sb, "</targ_port>\n");
3376 			if (retval != 0)
3377 				break;
3378 		}
3379 		mtx_unlock(&softc->ctl_lock);
3380 
3381 		if ((retval != 0)
3382 		 || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3383 			retval = 0;
3384 			sbuf_delete(sb);
3385 			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3386 			snprintf(list->error_str, sizeof(list->error_str),
3387 				 "Out of space, %d bytes is too small",
3388 				 list->alloc_len);
3389 			break;
3390 		}
3391 
3392 		sbuf_finish(sb);
3393 
3394 		retval = copyout(sbuf_data(sb), list->lun_xml,
3395 				 sbuf_len(sb) + 1);
3396 
3397 		list->fill_len = sbuf_len(sb) + 1;
3398 		list->status = CTL_LUN_LIST_OK;
3399 		sbuf_delete(sb);
3400 		break;
3401 	}
3402 	case CTL_LUN_MAP: {
3403 		struct ctl_lun_map *lm  = (struct ctl_lun_map *)addr;
3404 		struct ctl_port *port;
3405 
3406 		mtx_lock(&softc->ctl_lock);
3407 		if (lm->port < softc->port_min ||
3408 		    lm->port >= softc->port_max ||
3409 		    (port = softc->ctl_ports[lm->port]) == NULL) {
3410 			mtx_unlock(&softc->ctl_lock);
3411 			return (ENXIO);
3412 		}
3413 		if (port->status & CTL_PORT_STATUS_ONLINE) {
3414 			STAILQ_FOREACH(lun, &softc->lun_list, links) {
3415 				if (ctl_lun_map_to_port(port, lun->lun) ==
3416 				    UINT32_MAX)
3417 					continue;
3418 				mtx_lock(&lun->lun_lock);
3419 				ctl_est_ua_port(lun, lm->port, -1,
3420 				    CTL_UA_LUN_CHANGE);
3421 				mtx_unlock(&lun->lun_lock);
3422 			}
3423 		}
3424 		mtx_unlock(&softc->ctl_lock); // XXX: port_enable sleeps
3425 		if (lm->plun != UINT32_MAX) {
3426 			if (lm->lun == UINT32_MAX)
3427 				retval = ctl_lun_map_unset(port, lm->plun);
3428 			else if (lm->lun < ctl_max_luns &&
3429 			    softc->ctl_luns[lm->lun] != NULL)
3430 				retval = ctl_lun_map_set(port, lm->plun, lm->lun);
3431 			else
3432 				return (ENXIO);
3433 		} else {
3434 			if (lm->lun == UINT32_MAX)
3435 				retval = ctl_lun_map_deinit(port);
3436 			else
3437 				retval = ctl_lun_map_init(port);
3438 		}
3439 		if (port->status & CTL_PORT_STATUS_ONLINE)
3440 			ctl_isc_announce_port(port);
3441 		break;
3442 	}
3443 	case CTL_GET_LUN_STATS: {
3444 		struct ctl_get_io_stats *stats = (struct ctl_get_io_stats *)addr;
3445 		int i;
3446 
3447 		/*
3448 		 * XXX KDM no locking here.  If the LUN list changes,
3449 		 * things can blow up.
3450 		 */
3451 		i = 0;
3452 		stats->status = CTL_SS_OK;
3453 		stats->fill_len = 0;
3454 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
3455 			if (lun->lun < stats->first_item)
3456 				continue;
3457 			if (stats->fill_len + sizeof(lun->stats) >
3458 			    stats->alloc_len) {
3459 				stats->status = CTL_SS_NEED_MORE_SPACE;
3460 				break;
3461 			}
3462 			retval = copyout(&lun->stats, &stats->stats[i++],
3463 					 sizeof(lun->stats));
3464 			if (retval != 0)
3465 				break;
3466 			stats->fill_len += sizeof(lun->stats);
3467 		}
3468 		stats->num_items = softc->num_luns;
3469 		stats->flags = CTL_STATS_FLAG_NONE;
3470 #ifdef CTL_TIME_IO
3471 		stats->flags |= CTL_STATS_FLAG_TIME_VALID;
3472 #endif
3473 		getnanouptime(&stats->timestamp);
3474 		break;
3475 	}
3476 	case CTL_GET_PORT_STATS: {
3477 		struct ctl_get_io_stats *stats = (struct ctl_get_io_stats *)addr;
3478 		int i;
3479 
3480 		/*
3481 		 * XXX KDM no locking here.  If the LUN list changes,
3482 		 * things can blow up.
3483 		 */
3484 		i = 0;
3485 		stats->status = CTL_SS_OK;
3486 		stats->fill_len = 0;
3487 		STAILQ_FOREACH(port, &softc->port_list, links) {
3488 			if (port->targ_port < stats->first_item)
3489 				continue;
3490 			if (stats->fill_len + sizeof(port->stats) >
3491 			    stats->alloc_len) {
3492 				stats->status = CTL_SS_NEED_MORE_SPACE;
3493 				break;
3494 			}
3495 			retval = copyout(&port->stats, &stats->stats[i++],
3496 					 sizeof(port->stats));
3497 			if (retval != 0)
3498 				break;
3499 			stats->fill_len += sizeof(port->stats);
3500 		}
3501 		stats->num_items = softc->num_ports;
3502 		stats->flags = CTL_STATS_FLAG_NONE;
3503 #ifdef CTL_TIME_IO
3504 		stats->flags |= CTL_STATS_FLAG_TIME_VALID;
3505 #endif
3506 		getnanouptime(&stats->timestamp);
3507 		break;
3508 	}
3509 	default: {
3510 		/* XXX KDM should we fix this? */
3511 #if 0
3512 		struct ctl_backend_driver *backend;
3513 		unsigned int type;
3514 		int found;
3515 
3516 		found = 0;
3517 
3518 		/*
3519 		 * We encode the backend type as the ioctl type for backend
3520 		 * ioctls.  So parse it out here, and then search for a
3521 		 * backend of this type.
3522 		 */
3523 		type = _IOC_TYPE(cmd);
3524 
3525 		STAILQ_FOREACH(backend, &softc->be_list, links) {
3526 			if (backend->type == type) {
3527 				found = 1;
3528 				break;
3529 			}
3530 		}
3531 		if (found == 0) {
3532 			printf("ctl: unknown ioctl command %#lx or backend "
3533 			       "%d\n", cmd, type);
3534 			retval = EINVAL;
3535 			break;
3536 		}
3537 		retval = backend->ioctl(dev, cmd, addr, flag, td);
3538 #endif
3539 		retval = ENOTTY;
3540 		break;
3541 	}
3542 	}
3543 	return (retval);
3544 }
3545 
3546 uint32_t
3547 ctl_get_initindex(struct ctl_nexus *nexus)
3548 {
3549 	return (nexus->initid + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3550 }
3551 
3552 int
3553 ctl_lun_map_init(struct ctl_port *port)
3554 {
3555 	struct ctl_softc *softc = port->ctl_softc;
3556 	struct ctl_lun *lun;
3557 	int size = ctl_lun_map_size;
3558 	uint32_t i;
3559 
3560 	if (port->lun_map == NULL || port->lun_map_size < size) {
3561 		port->lun_map_size = 0;
3562 		free(port->lun_map, M_CTL);
3563 		port->lun_map = malloc(size * sizeof(uint32_t),
3564 		    M_CTL, M_NOWAIT);
3565 	}
3566 	if (port->lun_map == NULL)
3567 		return (ENOMEM);
3568 	for (i = 0; i < size; i++)
3569 		port->lun_map[i] = UINT32_MAX;
3570 	port->lun_map_size = size;
3571 	if (port->status & CTL_PORT_STATUS_ONLINE) {
3572 		if (port->lun_disable != NULL) {
3573 			STAILQ_FOREACH(lun, &softc->lun_list, links)
3574 				port->lun_disable(port->targ_lun_arg, lun->lun);
3575 		}
3576 		ctl_isc_announce_port(port);
3577 	}
3578 	return (0);
3579 }
3580 
3581 int
3582 ctl_lun_map_deinit(struct ctl_port *port)
3583 {
3584 	struct ctl_softc *softc = port->ctl_softc;
3585 	struct ctl_lun *lun;
3586 
3587 	if (port->lun_map == NULL)
3588 		return (0);
3589 	port->lun_map_size = 0;
3590 	free(port->lun_map, M_CTL);
3591 	port->lun_map = NULL;
3592 	if (port->status & CTL_PORT_STATUS_ONLINE) {
3593 		if (port->lun_enable != NULL) {
3594 			STAILQ_FOREACH(lun, &softc->lun_list, links)
3595 				port->lun_enable(port->targ_lun_arg, lun->lun);
3596 		}
3597 		ctl_isc_announce_port(port);
3598 	}
3599 	return (0);
3600 }
3601 
3602 int
3603 ctl_lun_map_set(struct ctl_port *port, uint32_t plun, uint32_t glun)
3604 {
3605 	int status;
3606 	uint32_t old;
3607 
3608 	if (port->lun_map == NULL) {
3609 		status = ctl_lun_map_init(port);
3610 		if (status != 0)
3611 			return (status);
3612 	}
3613 	if (plun >= port->lun_map_size)
3614 		return (EINVAL);
3615 	old = port->lun_map[plun];
3616 	port->lun_map[plun] = glun;
3617 	if ((port->status & CTL_PORT_STATUS_ONLINE) && old == UINT32_MAX) {
3618 		if (port->lun_enable != NULL)
3619 			port->lun_enable(port->targ_lun_arg, plun);
3620 		ctl_isc_announce_port(port);
3621 	}
3622 	return (0);
3623 }
3624 
3625 int
3626 ctl_lun_map_unset(struct ctl_port *port, uint32_t plun)
3627 {
3628 	uint32_t old;
3629 
3630 	if (port->lun_map == NULL || plun >= port->lun_map_size)
3631 		return (0);
3632 	old = port->lun_map[plun];
3633 	port->lun_map[plun] = UINT32_MAX;
3634 	if ((port->status & CTL_PORT_STATUS_ONLINE) && old != UINT32_MAX) {
3635 		if (port->lun_disable != NULL)
3636 			port->lun_disable(port->targ_lun_arg, plun);
3637 		ctl_isc_announce_port(port);
3638 	}
3639 	return (0);
3640 }
3641 
3642 uint32_t
3643 ctl_lun_map_from_port(struct ctl_port *port, uint32_t lun_id)
3644 {
3645 
3646 	if (port == NULL)
3647 		return (UINT32_MAX);
3648 	if (port->lun_map == NULL)
3649 		return (lun_id);
3650 	if (lun_id > port->lun_map_size)
3651 		return (UINT32_MAX);
3652 	return (port->lun_map[lun_id]);
3653 }
3654 
3655 uint32_t
3656 ctl_lun_map_to_port(struct ctl_port *port, uint32_t lun_id)
3657 {
3658 	uint32_t i;
3659 
3660 	if (port == NULL)
3661 		return (UINT32_MAX);
3662 	if (port->lun_map == NULL)
3663 		return (lun_id);
3664 	for (i = 0; i < port->lun_map_size; i++) {
3665 		if (port->lun_map[i] == lun_id)
3666 			return (i);
3667 	}
3668 	return (UINT32_MAX);
3669 }
3670 
3671 uint32_t
3672 ctl_decode_lun(uint64_t encoded)
3673 {
3674 	uint8_t lun[8];
3675 	uint32_t result = 0xffffffff;
3676 
3677 	be64enc(lun, encoded);
3678 	switch (lun[0] & RPL_LUNDATA_ATYP_MASK) {
3679 	case RPL_LUNDATA_ATYP_PERIPH:
3680 		if ((lun[0] & 0x3f) == 0 && lun[2] == 0 && lun[3] == 0 &&
3681 		    lun[4] == 0 && lun[5] == 0 && lun[6] == 0 && lun[7] == 0)
3682 			result = lun[1];
3683 		break;
3684 	case RPL_LUNDATA_ATYP_FLAT:
3685 		if (lun[2] == 0 && lun[3] == 0 && lun[4] == 0 && lun[5] == 0 &&
3686 		    lun[6] == 0 && lun[7] == 0)
3687 			result = ((lun[0] & 0x3f) << 8) + lun[1];
3688 		break;
3689 	case RPL_LUNDATA_ATYP_EXTLUN:
3690 		switch (lun[0] & RPL_LUNDATA_EXT_EAM_MASK) {
3691 		case 0x02:
3692 			switch (lun[0] & RPL_LUNDATA_EXT_LEN_MASK) {
3693 			case 0x00:
3694 				result = lun[1];
3695 				break;
3696 			case 0x10:
3697 				result = (lun[1] << 16) + (lun[2] << 8) +
3698 				    lun[3];
3699 				break;
3700 			case 0x20:
3701 				if (lun[1] == 0 && lun[6] == 0 && lun[7] == 0)
3702 					result = (lun[2] << 24) +
3703 					    (lun[3] << 16) + (lun[4] << 8) +
3704 					    lun[5];
3705 				break;
3706 			}
3707 			break;
3708 		case RPL_LUNDATA_EXT_EAM_NOT_SPEC:
3709 			result = 0xffffffff;
3710 			break;
3711 		}
3712 		break;
3713 	}
3714 	return (result);
3715 }
3716 
3717 uint64_t
3718 ctl_encode_lun(uint32_t decoded)
3719 {
3720 	uint64_t l = decoded;
3721 
3722 	if (l <= 0xff)
3723 		return (((uint64_t)RPL_LUNDATA_ATYP_PERIPH << 56) | (l << 48));
3724 	if (l <= 0x3fff)
3725 		return (((uint64_t)RPL_LUNDATA_ATYP_FLAT << 56) | (l << 48));
3726 	if (l <= 0xffffff)
3727 		return (((uint64_t)(RPL_LUNDATA_ATYP_EXTLUN | 0x12) << 56) |
3728 		    (l << 32));
3729 	return ((((uint64_t)RPL_LUNDATA_ATYP_EXTLUN | 0x22) << 56) | (l << 16));
3730 }
3731 
3732 int
3733 ctl_ffz(uint32_t *mask, uint32_t first, uint32_t last)
3734 {
3735 	int i;
3736 
3737 	for (i = first; i < last; i++) {
3738 		if ((mask[i / 32] & (1 << (i % 32))) == 0)
3739 			return (i);
3740 	}
3741 	return (-1);
3742 }
3743 
3744 int
3745 ctl_set_mask(uint32_t *mask, uint32_t bit)
3746 {
3747 	uint32_t chunk, piece;
3748 
3749 	chunk = bit >> 5;
3750 	piece = bit % (sizeof(uint32_t) * 8);
3751 
3752 	if ((mask[chunk] & (1 << piece)) != 0)
3753 		return (-1);
3754 	else
3755 		mask[chunk] |= (1 << piece);
3756 
3757 	return (0);
3758 }
3759 
3760 int
3761 ctl_clear_mask(uint32_t *mask, uint32_t bit)
3762 {
3763 	uint32_t chunk, piece;
3764 
3765 	chunk = bit >> 5;
3766 	piece = bit % (sizeof(uint32_t) * 8);
3767 
3768 	if ((mask[chunk] & (1 << piece)) == 0)
3769 		return (-1);
3770 	else
3771 		mask[chunk] &= ~(1 << piece);
3772 
3773 	return (0);
3774 }
3775 
3776 int
3777 ctl_is_set(uint32_t *mask, uint32_t bit)
3778 {
3779 	uint32_t chunk, piece;
3780 
3781 	chunk = bit >> 5;
3782 	piece = bit % (sizeof(uint32_t) * 8);
3783 
3784 	if ((mask[chunk] & (1 << piece)) == 0)
3785 		return (0);
3786 	else
3787 		return (1);
3788 }
3789 
3790 static uint64_t
3791 ctl_get_prkey(struct ctl_lun *lun, uint32_t residx)
3792 {
3793 	uint64_t *t;
3794 
3795 	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3796 	if (t == NULL)
3797 		return (0);
3798 	return (t[residx % CTL_MAX_INIT_PER_PORT]);
3799 }
3800 
3801 static void
3802 ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx)
3803 {
3804 	uint64_t *t;
3805 
3806 	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3807 	if (t == NULL)
3808 		return;
3809 	t[residx % CTL_MAX_INIT_PER_PORT] = 0;
3810 }
3811 
3812 static void
3813 ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx)
3814 {
3815 	uint64_t *p;
3816 	u_int i;
3817 
3818 	i = residx/CTL_MAX_INIT_PER_PORT;
3819 	if (lun->pr_keys[i] != NULL)
3820 		return;
3821 	mtx_unlock(&lun->lun_lock);
3822 	p = malloc(sizeof(uint64_t) * CTL_MAX_INIT_PER_PORT, M_CTL,
3823 	    M_WAITOK | M_ZERO);
3824 	mtx_lock(&lun->lun_lock);
3825 	if (lun->pr_keys[i] == NULL)
3826 		lun->pr_keys[i] = p;
3827 	else
3828 		free(p, M_CTL);
3829 }
3830 
3831 static void
3832 ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key)
3833 {
3834 	uint64_t *t;
3835 
3836 	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3837 	KASSERT(t != NULL, ("prkey %d is not allocated", residx));
3838 	t[residx % CTL_MAX_INIT_PER_PORT] = key;
3839 }
3840 
3841 /*
3842  * ctl_softc, pool_name, total_ctl_io are passed in.
3843  * npool is passed out.
3844  */
3845 int
3846 ctl_pool_create(struct ctl_softc *ctl_softc, const char *pool_name,
3847 		uint32_t total_ctl_io, void **npool)
3848 {
3849 	struct ctl_io_pool *pool;
3850 
3851 	pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3852 					    M_NOWAIT | M_ZERO);
3853 	if (pool == NULL)
3854 		return (ENOMEM);
3855 
3856 	snprintf(pool->name, sizeof(pool->name), "CTL IO %s", pool_name);
3857 	pool->ctl_softc = ctl_softc;
3858 #ifdef IO_POOLS
3859 	pool->zone = uma_zsecond_create(pool->name, NULL,
3860 	    NULL, NULL, NULL, ctl_softc->io_zone);
3861 	/* uma_prealloc(pool->zone, total_ctl_io); */
3862 #else
3863 	pool->zone = ctl_softc->io_zone;
3864 #endif
3865 
3866 	*npool = pool;
3867 	return (0);
3868 }
3869 
3870 void
3871 ctl_pool_free(struct ctl_io_pool *pool)
3872 {
3873 
3874 	if (pool == NULL)
3875 		return;
3876 
3877 #ifdef IO_POOLS
3878 	uma_zdestroy(pool->zone);
3879 #endif
3880 	free(pool, M_CTL);
3881 }
3882 
3883 union ctl_io *
3884 ctl_alloc_io(void *pool_ref)
3885 {
3886 	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3887 	union ctl_io *io;
3888 
3889 	io = uma_zalloc(pool->zone, M_WAITOK);
3890 	if (io != NULL) {
3891 		io->io_hdr.pool = pool_ref;
3892 		CTL_SOFTC(io) = pool->ctl_softc;
3893 		TAILQ_INIT(&io->io_hdr.blocked_queue);
3894 	}
3895 	return (io);
3896 }
3897 
3898 union ctl_io *
3899 ctl_alloc_io_nowait(void *pool_ref)
3900 {
3901 	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3902 	union ctl_io *io;
3903 
3904 	io = uma_zalloc(pool->zone, M_NOWAIT);
3905 	if (io != NULL) {
3906 		io->io_hdr.pool = pool_ref;
3907 		CTL_SOFTC(io) = pool->ctl_softc;
3908 		TAILQ_INIT(&io->io_hdr.blocked_queue);
3909 	}
3910 	return (io);
3911 }
3912 
3913 void
3914 ctl_free_io(union ctl_io *io)
3915 {
3916 	struct ctl_io_pool *pool;
3917 
3918 	if (io == NULL)
3919 		return;
3920 
3921 	pool = (struct ctl_io_pool *)io->io_hdr.pool;
3922 	uma_zfree(pool->zone, io);
3923 }
3924 
3925 void
3926 ctl_zero_io(union ctl_io *io)
3927 {
3928 	struct ctl_io_pool *pool;
3929 
3930 	if (io == NULL)
3931 		return;
3932 
3933 	/*
3934 	 * May need to preserve linked list pointers at some point too.
3935 	 */
3936 	pool = io->io_hdr.pool;
3937 	memset(io, 0, sizeof(*io));
3938 	io->io_hdr.pool = pool;
3939 	CTL_SOFTC(io) = pool->ctl_softc;
3940 	TAILQ_INIT(&io->io_hdr.blocked_queue);
3941 }
3942 
3943 int
3944 ctl_expand_number(const char *buf, uint64_t *num)
3945 {
3946 	char *endptr;
3947 	uint64_t number;
3948 	unsigned shift;
3949 
3950 	number = strtoq(buf, &endptr, 0);
3951 
3952 	switch (tolower((unsigned char)*endptr)) {
3953 	case 'e':
3954 		shift = 60;
3955 		break;
3956 	case 'p':
3957 		shift = 50;
3958 		break;
3959 	case 't':
3960 		shift = 40;
3961 		break;
3962 	case 'g':
3963 		shift = 30;
3964 		break;
3965 	case 'm':
3966 		shift = 20;
3967 		break;
3968 	case 'k':
3969 		shift = 10;
3970 		break;
3971 	case 'b':
3972 	case '\0': /* No unit. */
3973 		*num = number;
3974 		return (0);
3975 	default:
3976 		/* Unrecognized unit. */
3977 		return (-1);
3978 	}
3979 
3980 	if ((number << shift) >> shift != number) {
3981 		/* Overflow */
3982 		return (-1);
3983 	}
3984 	*num = number << shift;
3985 	return (0);
3986 }
3987 
3988 
3989 /*
3990  * This routine could be used in the future to load default and/or saved
3991  * mode page parameters for a particuar lun.
3992  */
3993 static int
3994 ctl_init_page_index(struct ctl_lun *lun)
3995 {
3996 	int i, page_code;
3997 	struct ctl_page_index *page_index;
3998 	const char *value;
3999 	uint64_t ival;
4000 
4001 	memcpy(&lun->mode_pages.index, page_index_template,
4002 	       sizeof(page_index_template));
4003 
4004 	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
4005 
4006 		page_index = &lun->mode_pages.index[i];
4007 		if (lun->be_lun->lun_type == T_DIRECT &&
4008 		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
4009 			continue;
4010 		if (lun->be_lun->lun_type == T_PROCESSOR &&
4011 		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
4012 			continue;
4013 		if (lun->be_lun->lun_type == T_CDROM &&
4014 		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
4015 			continue;
4016 
4017 		page_code = page_index->page_code & SMPH_PC_MASK;
4018 		switch (page_code) {
4019 		case SMS_RW_ERROR_RECOVERY_PAGE: {
4020 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4021 			    ("subpage %#x for page %#x is incorrect!",
4022 			    page_index->subpage, page_code));
4023 			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT],
4024 			       &rw_er_page_default,
4025 			       sizeof(rw_er_page_default));
4026 			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CHANGEABLE],
4027 			       &rw_er_page_changeable,
4028 			       sizeof(rw_er_page_changeable));
4029 			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_DEFAULT],
4030 			       &rw_er_page_default,
4031 			       sizeof(rw_er_page_default));
4032 			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_SAVED],
4033 			       &rw_er_page_default,
4034 			       sizeof(rw_er_page_default));
4035 			page_index->page_data =
4036 				(uint8_t *)lun->mode_pages.rw_er_page;
4037 			break;
4038 		}
4039 		case SMS_FORMAT_DEVICE_PAGE: {
4040 			struct scsi_format_page *format_page;
4041 
4042 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4043 			    ("subpage %#x for page %#x is incorrect!",
4044 			    page_index->subpage, page_code));
4045 
4046 			/*
4047 			 * Sectors per track are set above.  Bytes per
4048 			 * sector need to be set here on a per-LUN basis.
4049 			 */
4050 			memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
4051 			       &format_page_default,
4052 			       sizeof(format_page_default));
4053 			memcpy(&lun->mode_pages.format_page[
4054 			       CTL_PAGE_CHANGEABLE], &format_page_changeable,
4055 			       sizeof(format_page_changeable));
4056 			memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
4057 			       &format_page_default,
4058 			       sizeof(format_page_default));
4059 			memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
4060 			       &format_page_default,
4061 			       sizeof(format_page_default));
4062 
4063 			format_page = &lun->mode_pages.format_page[
4064 				CTL_PAGE_CURRENT];
4065 			scsi_ulto2b(lun->be_lun->blocksize,
4066 				    format_page->bytes_per_sector);
4067 
4068 			format_page = &lun->mode_pages.format_page[
4069 				CTL_PAGE_DEFAULT];
4070 			scsi_ulto2b(lun->be_lun->blocksize,
4071 				    format_page->bytes_per_sector);
4072 
4073 			format_page = &lun->mode_pages.format_page[
4074 				CTL_PAGE_SAVED];
4075 			scsi_ulto2b(lun->be_lun->blocksize,
4076 				    format_page->bytes_per_sector);
4077 
4078 			page_index->page_data =
4079 				(uint8_t *)lun->mode_pages.format_page;
4080 			break;
4081 		}
4082 		case SMS_RIGID_DISK_PAGE: {
4083 			struct scsi_rigid_disk_page *rigid_disk_page;
4084 			uint32_t sectors_per_cylinder;
4085 			uint64_t cylinders;
4086 #ifndef	__XSCALE__
4087 			int shift;
4088 #endif /* !__XSCALE__ */
4089 
4090 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4091 			    ("subpage %#x for page %#x is incorrect!",
4092 			    page_index->subpage, page_code));
4093 
4094 			/*
4095 			 * Rotation rate and sectors per track are set
4096 			 * above.  We calculate the cylinders here based on
4097 			 * capacity.  Due to the number of heads and
4098 			 * sectors per track we're using, smaller arrays
4099 			 * may turn out to have 0 cylinders.  Linux and
4100 			 * FreeBSD don't pay attention to these mode pages
4101 			 * to figure out capacity, but Solaris does.  It
4102 			 * seems to deal with 0 cylinders just fine, and
4103 			 * works out a fake geometry based on the capacity.
4104 			 */
4105 			memcpy(&lun->mode_pages.rigid_disk_page[
4106 			       CTL_PAGE_DEFAULT], &rigid_disk_page_default,
4107 			       sizeof(rigid_disk_page_default));
4108 			memcpy(&lun->mode_pages.rigid_disk_page[
4109 			       CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
4110 			       sizeof(rigid_disk_page_changeable));
4111 
4112 			sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
4113 				CTL_DEFAULT_HEADS;
4114 
4115 			/*
4116 			 * The divide method here will be more accurate,
4117 			 * probably, but results in floating point being
4118 			 * used in the kernel on i386 (__udivdi3()).  On the
4119 			 * XScale, though, __udivdi3() is implemented in
4120 			 * software.
4121 			 *
4122 			 * The shift method for cylinder calculation is
4123 			 * accurate if sectors_per_cylinder is a power of
4124 			 * 2.  Otherwise it might be slightly off -- you
4125 			 * might have a bit of a truncation problem.
4126 			 */
4127 #ifdef	__XSCALE__
4128 			cylinders = (lun->be_lun->maxlba + 1) /
4129 				sectors_per_cylinder;
4130 #else
4131 			for (shift = 31; shift > 0; shift--) {
4132 				if (sectors_per_cylinder & (1 << shift))
4133 					break;
4134 			}
4135 			cylinders = (lun->be_lun->maxlba + 1) >> shift;
4136 #endif
4137 
4138 			/*
4139 			 * We've basically got 3 bytes, or 24 bits for the
4140 			 * cylinder size in the mode page.  If we're over,
4141 			 * just round down to 2^24.
4142 			 */
4143 			if (cylinders > 0xffffff)
4144 				cylinders = 0xffffff;
4145 
4146 			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4147 				CTL_PAGE_DEFAULT];
4148 			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4149 
4150 			if ((value = dnvlist_get_string(lun->be_lun->options,
4151 			    "rpm", NULL)) != NULL) {
4152 				scsi_ulto2b(strtol(value, NULL, 0),
4153 				     rigid_disk_page->rotation_rate);
4154 			}
4155 
4156 			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_CURRENT],
4157 			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4158 			       sizeof(rigid_disk_page_default));
4159 			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_SAVED],
4160 			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4161 			       sizeof(rigid_disk_page_default));
4162 
4163 			page_index->page_data =
4164 				(uint8_t *)lun->mode_pages.rigid_disk_page;
4165 			break;
4166 		}
4167 		case SMS_VERIFY_ERROR_RECOVERY_PAGE: {
4168 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4169 			    ("subpage %#x for page %#x is incorrect!",
4170 			    page_index->subpage, page_code));
4171 			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_CURRENT],
4172 			       &verify_er_page_default,
4173 			       sizeof(verify_er_page_default));
4174 			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_CHANGEABLE],
4175 			       &verify_er_page_changeable,
4176 			       sizeof(verify_er_page_changeable));
4177 			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_DEFAULT],
4178 			       &verify_er_page_default,
4179 			       sizeof(verify_er_page_default));
4180 			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_SAVED],
4181 			       &verify_er_page_default,
4182 			       sizeof(verify_er_page_default));
4183 			page_index->page_data =
4184 				(uint8_t *)lun->mode_pages.verify_er_page;
4185 			break;
4186 		}
4187 		case SMS_CACHING_PAGE: {
4188 			struct scsi_caching_page *caching_page;
4189 
4190 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4191 			    ("subpage %#x for page %#x is incorrect!",
4192 			    page_index->subpage, page_code));
4193 			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4194 			       &caching_page_default,
4195 			       sizeof(caching_page_default));
4196 			memcpy(&lun->mode_pages.caching_page[
4197 			       CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4198 			       sizeof(caching_page_changeable));
4199 			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4200 			       &caching_page_default,
4201 			       sizeof(caching_page_default));
4202 			caching_page = &lun->mode_pages.caching_page[
4203 			    CTL_PAGE_SAVED];
4204 			value = dnvlist_get_string(lun->be_lun->options,
4205 			    "writecache", NULL);
4206 			if (value != NULL && strcmp(value, "off") == 0)
4207 				caching_page->flags1 &= ~SCP_WCE;
4208 			value = dnvlist_get_string(lun->be_lun->options,
4209 			    "readcache", NULL);
4210 			if (value != NULL && strcmp(value, "off") == 0)
4211 				caching_page->flags1 |= SCP_RCD;
4212 			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4213 			       &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4214 			       sizeof(caching_page_default));
4215 			page_index->page_data =
4216 				(uint8_t *)lun->mode_pages.caching_page;
4217 			break;
4218 		}
4219 		case SMS_CONTROL_MODE_PAGE: {
4220 			switch (page_index->subpage) {
4221 			case SMS_SUBPAGE_PAGE_0: {
4222 				struct scsi_control_page *control_page;
4223 
4224 				memcpy(&lun->mode_pages.control_page[
4225 				    CTL_PAGE_DEFAULT],
4226 				       &control_page_default,
4227 				       sizeof(control_page_default));
4228 				memcpy(&lun->mode_pages.control_page[
4229 				    CTL_PAGE_CHANGEABLE],
4230 				       &control_page_changeable,
4231 				       sizeof(control_page_changeable));
4232 				memcpy(&lun->mode_pages.control_page[
4233 				    CTL_PAGE_SAVED],
4234 				       &control_page_default,
4235 				       sizeof(control_page_default));
4236 				control_page = &lun->mode_pages.control_page[
4237 				    CTL_PAGE_SAVED];
4238 				value = dnvlist_get_string(lun->be_lun->options,
4239 				    "reordering", NULL);
4240 				if (value != NULL &&
4241 				    strcmp(value, "unrestricted") == 0) {
4242 					control_page->queue_flags &=
4243 					    ~SCP_QUEUE_ALG_MASK;
4244 					control_page->queue_flags |=
4245 					    SCP_QUEUE_ALG_UNRESTRICTED;
4246 				}
4247 				memcpy(&lun->mode_pages.control_page[
4248 				    CTL_PAGE_CURRENT],
4249 				       &lun->mode_pages.control_page[
4250 				    CTL_PAGE_SAVED],
4251 				       sizeof(control_page_default));
4252 				page_index->page_data =
4253 				    (uint8_t *)lun->mode_pages.control_page;
4254 				break;
4255 			}
4256 			case 0x01:
4257 				memcpy(&lun->mode_pages.control_ext_page[
4258 				    CTL_PAGE_DEFAULT],
4259 				       &control_ext_page_default,
4260 				       sizeof(control_ext_page_default));
4261 				memcpy(&lun->mode_pages.control_ext_page[
4262 				    CTL_PAGE_CHANGEABLE],
4263 				       &control_ext_page_changeable,
4264 				       sizeof(control_ext_page_changeable));
4265 				memcpy(&lun->mode_pages.control_ext_page[
4266 				    CTL_PAGE_SAVED],
4267 				       &control_ext_page_default,
4268 				       sizeof(control_ext_page_default));
4269 				memcpy(&lun->mode_pages.control_ext_page[
4270 				    CTL_PAGE_CURRENT],
4271 				       &lun->mode_pages.control_ext_page[
4272 				    CTL_PAGE_SAVED],
4273 				       sizeof(control_ext_page_default));
4274 				page_index->page_data =
4275 				    (uint8_t *)lun->mode_pages.control_ext_page;
4276 				break;
4277 			default:
4278 				panic("subpage %#x for page %#x is incorrect!",
4279 				      page_index->subpage, page_code);
4280 			}
4281 			break;
4282 		}
4283 		case SMS_INFO_EXCEPTIONS_PAGE: {
4284 			switch (page_index->subpage) {
4285 			case SMS_SUBPAGE_PAGE_0:
4286 				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_CURRENT],
4287 				       &ie_page_default,
4288 				       sizeof(ie_page_default));
4289 				memcpy(&lun->mode_pages.ie_page[
4290 				       CTL_PAGE_CHANGEABLE], &ie_page_changeable,
4291 				       sizeof(ie_page_changeable));
4292 				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_DEFAULT],
4293 				       &ie_page_default,
4294 				       sizeof(ie_page_default));
4295 				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_SAVED],
4296 				       &ie_page_default,
4297 				       sizeof(ie_page_default));
4298 				page_index->page_data =
4299 					(uint8_t *)lun->mode_pages.ie_page;
4300 				break;
4301 			case 0x02: {
4302 				struct ctl_logical_block_provisioning_page *page;
4303 
4304 				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_DEFAULT],
4305 				       &lbp_page_default,
4306 				       sizeof(lbp_page_default));
4307 				memcpy(&lun->mode_pages.lbp_page[
4308 				       CTL_PAGE_CHANGEABLE], &lbp_page_changeable,
4309 				       sizeof(lbp_page_changeable));
4310 				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4311 				       &lbp_page_default,
4312 				       sizeof(lbp_page_default));
4313 				page = &lun->mode_pages.lbp_page[CTL_PAGE_SAVED];
4314 				value = dnvlist_get_string(lun->be_lun->options,
4315 				    "avail-threshold", NULL);
4316 				if (value != NULL &&
4317 				    ctl_expand_number(value, &ival) == 0) {
4318 					page->descr[0].flags |= SLBPPD_ENABLED |
4319 					    SLBPPD_ARMING_DEC;
4320 					if (lun->be_lun->blocksize)
4321 						ival /= lun->be_lun->blocksize;
4322 					else
4323 						ival /= 512;
4324 					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4325 					    page->descr[0].count);
4326 				}
4327 				value = dnvlist_get_string(lun->be_lun->options,
4328 				    "used-threshold", NULL);
4329 				if (value != NULL &&
4330 				    ctl_expand_number(value, &ival) == 0) {
4331 					page->descr[1].flags |= SLBPPD_ENABLED |
4332 					    SLBPPD_ARMING_INC;
4333 					if (lun->be_lun->blocksize)
4334 						ival /= lun->be_lun->blocksize;
4335 					else
4336 						ival /= 512;
4337 					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4338 					    page->descr[1].count);
4339 				}
4340 				value = dnvlist_get_string(lun->be_lun->options,
4341 				    "pool-avail-threshold", NULL);
4342 				if (value != NULL &&
4343 				    ctl_expand_number(value, &ival) == 0) {
4344 					page->descr[2].flags |= SLBPPD_ENABLED |
4345 					    SLBPPD_ARMING_DEC;
4346 					if (lun->be_lun->blocksize)
4347 						ival /= lun->be_lun->blocksize;
4348 					else
4349 						ival /= 512;
4350 					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4351 					    page->descr[2].count);
4352 				}
4353 				value = dnvlist_get_string(lun->be_lun->options,
4354 				    "pool-used-threshold", NULL);
4355 				if (value != NULL &&
4356 				    ctl_expand_number(value, &ival) == 0) {
4357 					page->descr[3].flags |= SLBPPD_ENABLED |
4358 					    SLBPPD_ARMING_INC;
4359 					if (lun->be_lun->blocksize)
4360 						ival /= lun->be_lun->blocksize;
4361 					else
4362 						ival /= 512;
4363 					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4364 					    page->descr[3].count);
4365 				}
4366 				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_CURRENT],
4367 				       &lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4368 				       sizeof(lbp_page_default));
4369 				page_index->page_data =
4370 					(uint8_t *)lun->mode_pages.lbp_page;
4371 				break;
4372 			}
4373 			default:
4374 				panic("subpage %#x for page %#x is incorrect!",
4375 				      page_index->subpage, page_code);
4376 			}
4377 			break;
4378 		}
4379 		case SMS_CDDVD_CAPS_PAGE:{
4380 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4381 			    ("subpage %#x for page %#x is incorrect!",
4382 			    page_index->subpage, page_code));
4383 			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_DEFAULT],
4384 			       &cddvd_page_default,
4385 			       sizeof(cddvd_page_default));
4386 			memcpy(&lun->mode_pages.cddvd_page[
4387 			       CTL_PAGE_CHANGEABLE], &cddvd_page_changeable,
4388 			       sizeof(cddvd_page_changeable));
4389 			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_SAVED],
4390 			       &cddvd_page_default,
4391 			       sizeof(cddvd_page_default));
4392 			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_CURRENT],
4393 			       &lun->mode_pages.cddvd_page[CTL_PAGE_SAVED],
4394 			       sizeof(cddvd_page_default));
4395 			page_index->page_data =
4396 				(uint8_t *)lun->mode_pages.cddvd_page;
4397 			break;
4398 		}
4399 		default:
4400 			panic("invalid page code value %#x", page_code);
4401 		}
4402 	}
4403 
4404 	return (CTL_RETVAL_COMPLETE);
4405 }
4406 
4407 static int
4408 ctl_init_log_page_index(struct ctl_lun *lun)
4409 {
4410 	struct ctl_page_index *page_index;
4411 	int i, j, k, prev;
4412 
4413 	memcpy(&lun->log_pages.index, log_page_index_template,
4414 	       sizeof(log_page_index_template));
4415 
4416 	prev = -1;
4417 	for (i = 0, j = 0, k = 0; i < CTL_NUM_LOG_PAGES; i++) {
4418 
4419 		page_index = &lun->log_pages.index[i];
4420 		if (lun->be_lun->lun_type == T_DIRECT &&
4421 		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
4422 			continue;
4423 		if (lun->be_lun->lun_type == T_PROCESSOR &&
4424 		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
4425 			continue;
4426 		if (lun->be_lun->lun_type == T_CDROM &&
4427 		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
4428 			continue;
4429 
4430 		if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING &&
4431 		    lun->backend->lun_attr == NULL)
4432 			continue;
4433 
4434 		if (page_index->page_code != prev) {
4435 			lun->log_pages.pages_page[j] = page_index->page_code;
4436 			prev = page_index->page_code;
4437 			j++;
4438 		}
4439 		lun->log_pages.subpages_page[k*2] = page_index->page_code;
4440 		lun->log_pages.subpages_page[k*2+1] = page_index->subpage;
4441 		k++;
4442 	}
4443 	lun->log_pages.index[0].page_data = &lun->log_pages.pages_page[0];
4444 	lun->log_pages.index[0].page_len = j;
4445 	lun->log_pages.index[1].page_data = &lun->log_pages.subpages_page[0];
4446 	lun->log_pages.index[1].page_len = k * 2;
4447 	lun->log_pages.index[2].page_data = (uint8_t *)&lun->log_pages.temp_page;
4448 	lun->log_pages.index[2].page_len = sizeof(lun->log_pages.temp_page);
4449 	lun->log_pages.index[3].page_data = &lun->log_pages.lbp_page[0];
4450 	lun->log_pages.index[3].page_len = 12*CTL_NUM_LBP_PARAMS;
4451 	lun->log_pages.index[4].page_data = (uint8_t *)&lun->log_pages.stat_page;
4452 	lun->log_pages.index[4].page_len = sizeof(lun->log_pages.stat_page);
4453 	lun->log_pages.index[5].page_data = (uint8_t *)&lun->log_pages.ie_page;
4454 	lun->log_pages.index[5].page_len = sizeof(lun->log_pages.ie_page);
4455 
4456 	return (CTL_RETVAL_COMPLETE);
4457 }
4458 
4459 static int
4460 hex2bin(const char *str, uint8_t *buf, int buf_size)
4461 {
4462 	int i;
4463 	u_char c;
4464 
4465 	memset(buf, 0, buf_size);
4466 	while (isspace(str[0]))
4467 		str++;
4468 	if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
4469 		str += 2;
4470 	buf_size *= 2;
4471 	for (i = 0; str[i] != 0 && i < buf_size; i++) {
4472 		while (str[i] == '-')	/* Skip dashes in UUIDs. */
4473 			str++;
4474 		c = str[i];
4475 		if (isdigit(c))
4476 			c -= '0';
4477 		else if (isalpha(c))
4478 			c -= isupper(c) ? 'A' - 10 : 'a' - 10;
4479 		else
4480 			break;
4481 		if (c >= 16)
4482 			break;
4483 		if ((i & 1) == 0)
4484 			buf[i / 2] |= (c << 4);
4485 		else
4486 			buf[i / 2] |= c;
4487 	}
4488 	return ((i + 1) / 2);
4489 }
4490 
4491 /*
4492  * Add LUN.
4493  *
4494  * Returns 0 for success, non-zero (errno) for failure.
4495  */
4496 int
4497 ctl_add_lun(struct ctl_be_lun *be_lun)
4498 {
4499 	struct ctl_softc *ctl_softc = control_softc;
4500 	struct ctl_lun *nlun, *lun;
4501 	struct scsi_vpd_id_descriptor *desc;
4502 	struct scsi_vpd_id_t10 *t10id;
4503 	const char *eui, *naa, *scsiname, *uuid, *vendor, *value;
4504 	int lun_number;
4505 	int devidlen, idlen1, idlen2 = 0, len;
4506 
4507 	/*
4508 	 * We support only Direct Access, CD-ROM or Processor LUN types.
4509 	 */
4510 	switch (be_lun->lun_type) {
4511 	case T_DIRECT:
4512 	case T_PROCESSOR:
4513 	case T_CDROM:
4514 		break;
4515 	case T_SEQUENTIAL:
4516 	case T_CHANGER:
4517 	default:
4518 		return (EINVAL);
4519 	}
4520 	lun = malloc(sizeof(*lun), M_CTL, M_WAITOK | M_ZERO);
4521 
4522 	lun->pending_sense = malloc(sizeof(struct scsi_sense_data *) *
4523 	    ctl_max_ports, M_DEVBUF, M_WAITOK | M_ZERO);
4524 	lun->pending_ua = malloc(sizeof(ctl_ua_type *) * ctl_max_ports,
4525 	    M_DEVBUF, M_WAITOK | M_ZERO);
4526 	lun->pr_keys = malloc(sizeof(uint64_t *) * ctl_max_ports,
4527 	    M_DEVBUF, M_WAITOK | M_ZERO);
4528 
4529 	/* Generate LUN ID. */
4530 	devidlen = max(CTL_DEVID_MIN_LEN,
4531 	    strnlen(be_lun->device_id, CTL_DEVID_LEN));
4532 	idlen1 = sizeof(*t10id) + devidlen;
4533 	len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4534 	scsiname = dnvlist_get_string(be_lun->options, "scsiname", NULL);
4535 	if (scsiname != NULL) {
4536 		idlen2 = roundup2(strlen(scsiname) + 1, 4);
4537 		len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4538 	}
4539 	eui = dnvlist_get_string(be_lun->options, "eui", NULL);
4540 	if (eui != NULL) {
4541 		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4542 	}
4543 	naa = dnvlist_get_string(be_lun->options, "naa", NULL);
4544 	if (naa != NULL) {
4545 		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4546 	}
4547 	uuid = dnvlist_get_string(be_lun->options, "uuid", NULL);
4548 	if (uuid != NULL) {
4549 		len += sizeof(struct scsi_vpd_id_descriptor) + 18;
4550 	}
4551 	lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4552 	    M_CTL, M_WAITOK | M_ZERO);
4553 	desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4554 	desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4555 	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4556 	desc->length = idlen1;
4557 	t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4558 	memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4559 	if ((vendor = dnvlist_get_string(be_lun->options, "vendor", NULL)) == NULL) {
4560 		strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4561 	} else {
4562 		strncpy(t10id->vendor, vendor,
4563 		    min(sizeof(t10id->vendor), strlen(vendor)));
4564 	}
4565 	strncpy((char *)t10id->vendor_spec_id,
4566 	    (char *)be_lun->device_id, devidlen);
4567 	if (scsiname != NULL) {
4568 		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4569 		    desc->length);
4570 		desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4571 		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4572 		    SVPD_ID_TYPE_SCSI_NAME;
4573 		desc->length = idlen2;
4574 		strlcpy(desc->identifier, scsiname, idlen2);
4575 	}
4576 	if (eui != NULL) {
4577 		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4578 		    desc->length);
4579 		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4580 		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4581 		    SVPD_ID_TYPE_EUI64;
4582 		desc->length = hex2bin(eui, desc->identifier, 16);
4583 		desc->length = desc->length > 12 ? 16 :
4584 		    (desc->length > 8 ? 12 : 8);
4585 		len -= 16 - desc->length;
4586 	}
4587 	if (naa != NULL) {
4588 		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4589 		    desc->length);
4590 		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4591 		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4592 		    SVPD_ID_TYPE_NAA;
4593 		desc->length = hex2bin(naa, desc->identifier, 16);
4594 		desc->length = desc->length > 8 ? 16 : 8;
4595 		len -= 16 - desc->length;
4596 	}
4597 	if (uuid != NULL) {
4598 		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4599 		    desc->length);
4600 		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4601 		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4602 		    SVPD_ID_TYPE_UUID;
4603 		desc->identifier[0] = 0x10;
4604 		hex2bin(uuid, &desc->identifier[2], 16);
4605 		desc->length = 18;
4606 	}
4607 	lun->lun_devid->len = len;
4608 
4609 	mtx_lock(&ctl_softc->ctl_lock);
4610 	/*
4611 	 * See if the caller requested a particular LUN number.  If so, see
4612 	 * if it is available.  Otherwise, allocate the first available LUN.
4613 	 */
4614 	if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4615 		if ((be_lun->req_lun_id > (ctl_max_luns - 1))
4616 		 || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4617 			mtx_unlock(&ctl_softc->ctl_lock);
4618 			if (be_lun->req_lun_id > (ctl_max_luns - 1)) {
4619 				printf("ctl: requested LUN ID %d is higher "
4620 				       "than ctl_max_luns - 1 (%d)\n",
4621 				       be_lun->req_lun_id, ctl_max_luns - 1);
4622 			} else {
4623 				/*
4624 				 * XXX KDM return an error, or just assign
4625 				 * another LUN ID in this case??
4626 				 */
4627 				printf("ctl: requested LUN ID %d is already "
4628 				       "in use\n", be_lun->req_lun_id);
4629 			}
4630 fail:
4631 			free(lun->lun_devid, M_CTL);
4632 			free(lun, M_CTL);
4633 			return (ENOSPC);
4634 		}
4635 		lun_number = be_lun->req_lun_id;
4636 	} else {
4637 		lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, 0, ctl_max_luns);
4638 		if (lun_number == -1) {
4639 			mtx_unlock(&ctl_softc->ctl_lock);
4640 			printf("ctl: can't allocate LUN, out of LUNs\n");
4641 			goto fail;
4642 		}
4643 	}
4644 	ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4645 	mtx_unlock(&ctl_softc->ctl_lock);
4646 
4647 	mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4648 	lun->lun = lun_number;
4649 	lun->be_lun = be_lun;
4650 	/*
4651 	 * The processor LUN is always enabled.  Disk LUNs come on line
4652 	 * disabled, and must be enabled by the backend.
4653 	 */
4654 	lun->flags |= CTL_LUN_DISABLED;
4655 	lun->backend = be_lun->be;
4656 	be_lun->ctl_lun = lun;
4657 	be_lun->lun_id = lun_number;
4658 	if (be_lun->flags & CTL_LUN_FLAG_EJECTED)
4659 		lun->flags |= CTL_LUN_EJECTED;
4660 	if (be_lun->flags & CTL_LUN_FLAG_NO_MEDIA)
4661 		lun->flags |= CTL_LUN_NO_MEDIA;
4662 	if (be_lun->flags & CTL_LUN_FLAG_STOPPED)
4663 		lun->flags |= CTL_LUN_STOPPED;
4664 
4665 	if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4666 		lun->flags |= CTL_LUN_PRIMARY_SC;
4667 
4668 	value = dnvlist_get_string(be_lun->options, "removable", NULL);
4669 	if (value != NULL) {
4670 		if (strcmp(value, "on") == 0)
4671 			lun->flags |= CTL_LUN_REMOVABLE;
4672 	} else if (be_lun->lun_type == T_CDROM)
4673 		lun->flags |= CTL_LUN_REMOVABLE;
4674 
4675 	lun->ctl_softc = ctl_softc;
4676 #ifdef CTL_TIME_IO
4677 	lun->last_busy = getsbinuptime();
4678 #endif
4679 	TAILQ_INIT(&lun->ooa_queue);
4680 	STAILQ_INIT(&lun->error_list);
4681 	lun->ie_reported = 1;
4682 	callout_init_mtx(&lun->ie_callout, &lun->lun_lock, 0);
4683 	ctl_tpc_lun_init(lun);
4684 	if (lun->flags & CTL_LUN_REMOVABLE) {
4685 		lun->prevent = malloc((CTL_MAX_INITIATORS + 31) / 32 * 4,
4686 		    M_CTL, M_WAITOK);
4687 	}
4688 
4689 	/*
4690 	 * Initialize the mode and log page index.
4691 	 */
4692 	ctl_init_page_index(lun);
4693 	ctl_init_log_page_index(lun);
4694 
4695 	/* Setup statistics gathering */
4696 	lun->stats.item = lun_number;
4697 
4698 	/*
4699 	 * Now, before we insert this lun on the lun list, set the lun
4700 	 * inventory changed UA for all other luns.
4701 	 */
4702 	mtx_lock(&ctl_softc->ctl_lock);
4703 	STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4704 		mtx_lock(&nlun->lun_lock);
4705 		ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4706 		mtx_unlock(&nlun->lun_lock);
4707 	}
4708 	STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4709 	ctl_softc->ctl_luns[lun_number] = lun;
4710 	ctl_softc->num_luns++;
4711 	mtx_unlock(&ctl_softc->ctl_lock);
4712 
4713 	/*
4714 	 * We successfully added the LUN, attempt to enable it.
4715 	 */
4716 	if (ctl_enable_lun(lun) != 0) {
4717 		printf("%s: ctl_enable_lun() failed!\n", __func__);
4718 		mtx_lock(&ctl_softc->ctl_lock);
4719 		STAILQ_REMOVE(&ctl_softc->lun_list, lun, ctl_lun, links);
4720 		ctl_clear_mask(ctl_softc->ctl_lun_mask, lun_number);
4721 		ctl_softc->ctl_luns[lun_number] = NULL;
4722 		ctl_softc->num_luns--;
4723 		mtx_unlock(&ctl_softc->ctl_lock);
4724 		free(lun->lun_devid, M_CTL);
4725 		free(lun, M_CTL);
4726 		return (EIO);
4727 	}
4728 
4729 	return (0);
4730 }
4731 
4732 /*
4733  * Free LUN that has no active requests.
4734  */
4735 static int
4736 ctl_free_lun(struct ctl_lun *lun)
4737 {
4738 	struct ctl_softc *softc = lun->ctl_softc;
4739 	struct ctl_lun *nlun;
4740 	int i;
4741 
4742 	KASSERT(TAILQ_EMPTY(&lun->ooa_queue),
4743 	    ("Freeing a LUN %p with outstanding I/O!\n", lun));
4744 
4745 	mtx_lock(&softc->ctl_lock);
4746 	STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4747 	ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4748 	softc->ctl_luns[lun->lun] = NULL;
4749 	softc->num_luns--;
4750 	STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4751 		mtx_lock(&nlun->lun_lock);
4752 		ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4753 		mtx_unlock(&nlun->lun_lock);
4754 	}
4755 	mtx_unlock(&softc->ctl_lock);
4756 
4757 	/*
4758 	 * Tell the backend to free resources, if this LUN has a backend.
4759 	 */
4760 	lun->be_lun->lun_shutdown(lun->be_lun);
4761 
4762 	lun->ie_reportcnt = UINT32_MAX;
4763 	callout_drain(&lun->ie_callout);
4764 	ctl_tpc_lun_shutdown(lun);
4765 	mtx_destroy(&lun->lun_lock);
4766 	free(lun->lun_devid, M_CTL);
4767 	for (i = 0; i < ctl_max_ports; i++)
4768 		free(lun->pending_ua[i], M_CTL);
4769 	free(lun->pending_ua, M_DEVBUF);
4770 	for (i = 0; i < ctl_max_ports; i++)
4771 		free(lun->pr_keys[i], M_CTL);
4772 	free(lun->pr_keys, M_DEVBUF);
4773 	free(lun->write_buffer, M_CTL);
4774 	free(lun->prevent, M_CTL);
4775 	free(lun, M_CTL);
4776 
4777 	return (0);
4778 }
4779 
4780 static int
4781 ctl_enable_lun(struct ctl_lun *lun)
4782 {
4783 	struct ctl_softc *softc;
4784 	struct ctl_port *port, *nport;
4785 	int retval;
4786 
4787 	softc = lun->ctl_softc;
4788 
4789 	mtx_lock(&softc->ctl_lock);
4790 	mtx_lock(&lun->lun_lock);
4791 	KASSERT((lun->flags & CTL_LUN_DISABLED) != 0,
4792 	    ("%s: LUN not disabled", __func__));
4793 	lun->flags &= ~CTL_LUN_DISABLED;
4794 	mtx_unlock(&lun->lun_lock);
4795 
4796 	STAILQ_FOREACH_SAFE(port, &softc->port_list, links, nport) {
4797 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4798 		    port->lun_map != NULL || port->lun_enable == NULL)
4799 			continue;
4800 
4801 		/*
4802 		 * Drop the lock while we call the FETD's enable routine.
4803 		 * This can lead to a callback into CTL (at least in the
4804 		 * case of the internal initiator frontend.
4805 		 */
4806 		mtx_unlock(&softc->ctl_lock);
4807 		retval = port->lun_enable(port->targ_lun_arg, lun->lun);
4808 		mtx_lock(&softc->ctl_lock);
4809 		if (retval != 0) {
4810 			printf("%s: FETD %s port %d returned error "
4811 			       "%d for lun_enable on lun %jd\n",
4812 			       __func__, port->port_name, port->targ_port,
4813 			       retval, (intmax_t)lun->lun);
4814 		}
4815 	}
4816 
4817 	mtx_unlock(&softc->ctl_lock);
4818 	ctl_isc_announce_lun(lun);
4819 
4820 	return (0);
4821 }
4822 
4823 static int
4824 ctl_disable_lun(struct ctl_lun *lun)
4825 {
4826 	struct ctl_softc *softc;
4827 	struct ctl_port *port;
4828 	int retval;
4829 
4830 	softc = lun->ctl_softc;
4831 
4832 	mtx_lock(&softc->ctl_lock);
4833 	mtx_lock(&lun->lun_lock);
4834 	KASSERT((lun->flags & CTL_LUN_DISABLED) == 0,
4835 	    ("%s: LUN not enabled", __func__));
4836 	lun->flags |= CTL_LUN_DISABLED;
4837 	mtx_unlock(&lun->lun_lock);
4838 
4839 	STAILQ_FOREACH(port, &softc->port_list, links) {
4840 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4841 		    port->lun_map != NULL || port->lun_disable == NULL)
4842 			continue;
4843 
4844 		/*
4845 		 * Drop the lock before we call the frontend's disable
4846 		 * routine, to avoid lock order reversals.
4847 		 *
4848 		 * XXX KDM what happens if the frontend list changes while
4849 		 * we're traversing it?  It's unlikely, but should be handled.
4850 		 */
4851 		mtx_unlock(&softc->ctl_lock);
4852 		retval = port->lun_disable(port->targ_lun_arg, lun->lun);
4853 		mtx_lock(&softc->ctl_lock);
4854 		if (retval != 0) {
4855 			printf("%s: FETD %s port %d returned error "
4856 			       "%d for lun_disable on lun %jd\n",
4857 			       __func__, port->port_name, port->targ_port,
4858 			       retval, (intmax_t)lun->lun);
4859 		}
4860 	}
4861 
4862 	mtx_unlock(&softc->ctl_lock);
4863 	ctl_isc_announce_lun(lun);
4864 
4865 	return (0);
4866 }
4867 
4868 int
4869 ctl_start_lun(struct ctl_be_lun *be_lun)
4870 {
4871 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4872 
4873 	mtx_lock(&lun->lun_lock);
4874 	lun->flags &= ~CTL_LUN_STOPPED;
4875 	mtx_unlock(&lun->lun_lock);
4876 	return (0);
4877 }
4878 
4879 int
4880 ctl_stop_lun(struct ctl_be_lun *be_lun)
4881 {
4882 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4883 
4884 	mtx_lock(&lun->lun_lock);
4885 	lun->flags |= CTL_LUN_STOPPED;
4886 	mtx_unlock(&lun->lun_lock);
4887 	return (0);
4888 }
4889 
4890 int
4891 ctl_lun_no_media(struct ctl_be_lun *be_lun)
4892 {
4893 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4894 
4895 	mtx_lock(&lun->lun_lock);
4896 	lun->flags |= CTL_LUN_NO_MEDIA;
4897 	mtx_unlock(&lun->lun_lock);
4898 	return (0);
4899 }
4900 
4901 int
4902 ctl_lun_has_media(struct ctl_be_lun *be_lun)
4903 {
4904 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4905 	union ctl_ha_msg msg;
4906 
4907 	mtx_lock(&lun->lun_lock);
4908 	lun->flags &= ~(CTL_LUN_NO_MEDIA | CTL_LUN_EJECTED);
4909 	if (lun->flags & CTL_LUN_REMOVABLE)
4910 		ctl_est_ua_all(lun, -1, CTL_UA_MEDIUM_CHANGE);
4911 	mtx_unlock(&lun->lun_lock);
4912 	if ((lun->flags & CTL_LUN_REMOVABLE) &&
4913 	    lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
4914 		bzero(&msg.ua, sizeof(msg.ua));
4915 		msg.hdr.msg_type = CTL_MSG_UA;
4916 		msg.hdr.nexus.initid = -1;
4917 		msg.hdr.nexus.targ_port = -1;
4918 		msg.hdr.nexus.targ_lun = lun->lun;
4919 		msg.hdr.nexus.targ_mapped_lun = lun->lun;
4920 		msg.ua.ua_all = 1;
4921 		msg.ua.ua_set = 1;
4922 		msg.ua.ua_type = CTL_UA_MEDIUM_CHANGE;
4923 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
4924 		    M_WAITOK);
4925 	}
4926 	return (0);
4927 }
4928 
4929 int
4930 ctl_lun_ejected(struct ctl_be_lun *be_lun)
4931 {
4932 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4933 
4934 	mtx_lock(&lun->lun_lock);
4935 	lun->flags |= CTL_LUN_EJECTED;
4936 	mtx_unlock(&lun->lun_lock);
4937 	return (0);
4938 }
4939 
4940 int
4941 ctl_lun_primary(struct ctl_be_lun *be_lun)
4942 {
4943 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4944 
4945 	mtx_lock(&lun->lun_lock);
4946 	lun->flags |= CTL_LUN_PRIMARY_SC;
4947 	ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
4948 	mtx_unlock(&lun->lun_lock);
4949 	ctl_isc_announce_lun(lun);
4950 	return (0);
4951 }
4952 
4953 int
4954 ctl_lun_secondary(struct ctl_be_lun *be_lun)
4955 {
4956 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4957 
4958 	mtx_lock(&lun->lun_lock);
4959 	lun->flags &= ~CTL_LUN_PRIMARY_SC;
4960 	ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
4961 	mtx_unlock(&lun->lun_lock);
4962 	ctl_isc_announce_lun(lun);
4963 	return (0);
4964 }
4965 
4966 /*
4967  * Remove LUN.  If there are active requests, wait for completion.
4968  *
4969  * Returns 0 for success, non-zero (errno) for failure.
4970  * Completion is reported to backed via the lun_shutdown() method.
4971  */
4972 int
4973 ctl_remove_lun(struct ctl_be_lun *be_lun)
4974 {
4975 	struct ctl_lun *lun;
4976 
4977 	lun = (struct ctl_lun *)be_lun->ctl_lun;
4978 
4979 	ctl_disable_lun(lun);
4980 
4981 	mtx_lock(&lun->lun_lock);
4982 	lun->flags |= CTL_LUN_INVALID;
4983 
4984 	/*
4985 	 * If there is nothing in the OOA queue, go ahead and free the LUN.
4986 	 * If we have something in the OOA queue, we'll free it when the
4987 	 * last I/O completes.
4988 	 */
4989 	if (TAILQ_EMPTY(&lun->ooa_queue)) {
4990 		mtx_unlock(&lun->lun_lock);
4991 		ctl_free_lun(lun);
4992 	} else
4993 		mtx_unlock(&lun->lun_lock);
4994 
4995 	return (0);
4996 }
4997 
4998 void
4999 ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
5000 {
5001 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5002 	union ctl_ha_msg msg;
5003 
5004 	mtx_lock(&lun->lun_lock);
5005 	ctl_est_ua_all(lun, -1, CTL_UA_CAPACITY_CHANGE);
5006 	mtx_unlock(&lun->lun_lock);
5007 	if (lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
5008 		/* Send msg to other side. */
5009 		bzero(&msg.ua, sizeof(msg.ua));
5010 		msg.hdr.msg_type = CTL_MSG_UA;
5011 		msg.hdr.nexus.initid = -1;
5012 		msg.hdr.nexus.targ_port = -1;
5013 		msg.hdr.nexus.targ_lun = lun->lun;
5014 		msg.hdr.nexus.targ_mapped_lun = lun->lun;
5015 		msg.ua.ua_all = 1;
5016 		msg.ua.ua_set = 1;
5017 		msg.ua.ua_type = CTL_UA_CAPACITY_CHANGE;
5018 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
5019 		    M_WAITOK);
5020 	}
5021 }
5022 
5023 /*
5024  * Backend "memory move is complete" callback for requests that never
5025  * make it down to say RAIDCore's configuration code.
5026  */
5027 int
5028 ctl_config_move_done(union ctl_io *io)
5029 {
5030 	int retval;
5031 
5032 	CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
5033 	KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
5034 	    ("Config I/O type isn't CTL_IO_SCSI (%d)!", io->io_hdr.io_type));
5035 
5036 	if ((io->io_hdr.port_status != 0) &&
5037 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5038 	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5039 		ctl_set_internal_failure(&io->scsiio, /*sks_valid*/ 1,
5040 		    /*retry_count*/ io->io_hdr.port_status);
5041 	} else if (io->scsiio.kern_data_resid != 0 &&
5042 	    (io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT &&
5043 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5044 	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5045 		ctl_set_invalid_field_ciu(&io->scsiio);
5046 	}
5047 
5048 	if (ctl_debug & CTL_DEBUG_CDB_DATA)
5049 		ctl_data_print(io);
5050 	if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN) ||
5051 	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5052 	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) ||
5053 	    ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
5054 		/*
5055 		 * XXX KDM just assuming a single pointer here, and not a
5056 		 * S/G list.  If we start using S/G lists for config data,
5057 		 * we'll need to know how to clean them up here as well.
5058 		 */
5059 		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5060 			free(io->scsiio.kern_data_ptr, M_CTL);
5061 		ctl_done(io);
5062 		retval = CTL_RETVAL_COMPLETE;
5063 	} else {
5064 		/*
5065 		 * XXX KDM now we need to continue data movement.  Some
5066 		 * options:
5067 		 * - call ctl_scsiio() again?  We don't do this for data
5068 		 *   writes, because for those at least we know ahead of
5069 		 *   time where the write will go and how long it is.  For
5070 		 *   config writes, though, that information is largely
5071 		 *   contained within the write itself, thus we need to
5072 		 *   parse out the data again.
5073 		 *
5074 		 * - Call some other function once the data is in?
5075 		 */
5076 
5077 		/*
5078 		 * XXX KDM call ctl_scsiio() again for now, and check flag
5079 		 * bits to see whether we're allocated or not.
5080 		 */
5081 		retval = ctl_scsiio(&io->scsiio);
5082 	}
5083 	return (retval);
5084 }
5085 
5086 /*
5087  * This gets called by a backend driver when it is done with a
5088  * data_submit method.
5089  */
5090 void
5091 ctl_data_submit_done(union ctl_io *io)
5092 {
5093 	/*
5094 	 * If the IO_CONT flag is set, we need to call the supplied
5095 	 * function to continue processing the I/O, instead of completing
5096 	 * the I/O just yet.
5097 	 *
5098 	 * If there is an error, though, we don't want to keep processing.
5099 	 * Instead, just send status back to the initiator.
5100 	 */
5101 	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5102 	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5103 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5104 	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5105 		io->scsiio.io_cont(io);
5106 		return;
5107 	}
5108 	ctl_done(io);
5109 }
5110 
5111 /*
5112  * This gets called by a backend driver when it is done with a
5113  * configuration write.
5114  */
5115 void
5116 ctl_config_write_done(union ctl_io *io)
5117 {
5118 	uint8_t *buf;
5119 
5120 	/*
5121 	 * If the IO_CONT flag is set, we need to call the supplied
5122 	 * function to continue processing the I/O, instead of completing
5123 	 * the I/O just yet.
5124 	 *
5125 	 * If there is an error, though, we don't want to keep processing.
5126 	 * Instead, just send status back to the initiator.
5127 	 */
5128 	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5129 	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5130 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5131 	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5132 		io->scsiio.io_cont(io);
5133 		return;
5134 	}
5135 	/*
5136 	 * Since a configuration write can be done for commands that actually
5137 	 * have data allocated, like write buffer, and commands that have
5138 	 * no data, like start/stop unit, we need to check here.
5139 	 */
5140 	if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5141 		buf = io->scsiio.kern_data_ptr;
5142 	else
5143 		buf = NULL;
5144 	ctl_done(io);
5145 	if (buf)
5146 		free(buf, M_CTL);
5147 }
5148 
5149 void
5150 ctl_config_read_done(union ctl_io *io)
5151 {
5152 	uint8_t *buf;
5153 
5154 	/*
5155 	 * If there is some error -- we are done, skip data transfer.
5156 	 */
5157 	if ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0 ||
5158 	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5159 	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)) {
5160 		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5161 			buf = io->scsiio.kern_data_ptr;
5162 		else
5163 			buf = NULL;
5164 		ctl_done(io);
5165 		if (buf)
5166 			free(buf, M_CTL);
5167 		return;
5168 	}
5169 
5170 	/*
5171 	 * If the IO_CONT flag is set, we need to call the supplied
5172 	 * function to continue processing the I/O, instead of completing
5173 	 * the I/O just yet.
5174 	 */
5175 	if (io->io_hdr.flags & CTL_FLAG_IO_CONT) {
5176 		io->scsiio.io_cont(io);
5177 		return;
5178 	}
5179 
5180 	ctl_datamove(io);
5181 }
5182 
5183 /*
5184  * SCSI release command.
5185  */
5186 int
5187 ctl_scsi_release(struct ctl_scsiio *ctsio)
5188 {
5189 	struct ctl_lun *lun = CTL_LUN(ctsio);
5190 	uint32_t residx;
5191 
5192 	CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5193 
5194 	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5195 
5196 	/*
5197 	 * XXX KDM right now, we only support LUN reservation.  We don't
5198 	 * support 3rd party reservations, or extent reservations, which
5199 	 * might actually need the parameter list.  If we've gotten this
5200 	 * far, we've got a LUN reservation.  Anything else got kicked out
5201 	 * above.  So, according to SPC, ignore the length.
5202 	 */
5203 
5204 	mtx_lock(&lun->lun_lock);
5205 
5206 	/*
5207 	 * According to SPC, it is not an error for an intiator to attempt
5208 	 * to release a reservation on a LUN that isn't reserved, or that
5209 	 * is reserved by another initiator.  The reservation can only be
5210 	 * released, though, by the initiator who made it or by one of
5211 	 * several reset type events.
5212 	 */
5213 	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
5214 			lun->flags &= ~CTL_LUN_RESERVED;
5215 
5216 	mtx_unlock(&lun->lun_lock);
5217 
5218 	ctl_set_success(ctsio);
5219 	ctl_done((union ctl_io *)ctsio);
5220 	return (CTL_RETVAL_COMPLETE);
5221 }
5222 
5223 int
5224 ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5225 {
5226 	struct ctl_lun *lun = CTL_LUN(ctsio);
5227 	uint32_t residx;
5228 
5229 	CTL_DEBUG_PRINT(("ctl_reserve\n"));
5230 
5231 	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5232 
5233 	/*
5234 	 * XXX KDM right now, we only support LUN reservation.  We don't
5235 	 * support 3rd party reservations, or extent reservations, which
5236 	 * might actually need the parameter list.  If we've gotten this
5237 	 * far, we've got a LUN reservation.  Anything else got kicked out
5238 	 * above.  So, according to SPC, ignore the length.
5239 	 */
5240 
5241 	mtx_lock(&lun->lun_lock);
5242 	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
5243 		ctl_set_reservation_conflict(ctsio);
5244 		goto bailout;
5245 	}
5246 
5247 	/* SPC-3 exceptions to SPC-2 RESERVE and RELEASE behavior. */
5248 	if (lun->flags & CTL_LUN_PR_RESERVED) {
5249 		ctl_set_success(ctsio);
5250 		goto bailout;
5251 	}
5252 
5253 	lun->flags |= CTL_LUN_RESERVED;
5254 	lun->res_idx = residx;
5255 	ctl_set_success(ctsio);
5256 
5257 bailout:
5258 	mtx_unlock(&lun->lun_lock);
5259 	ctl_done((union ctl_io *)ctsio);
5260 	return (CTL_RETVAL_COMPLETE);
5261 }
5262 
5263 int
5264 ctl_start_stop(struct ctl_scsiio *ctsio)
5265 {
5266 	struct ctl_lun *lun = CTL_LUN(ctsio);
5267 	struct scsi_start_stop_unit *cdb;
5268 	int retval;
5269 
5270 	CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5271 
5272 	cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5273 
5274 	if ((cdb->how & SSS_PC_MASK) == 0) {
5275 		if ((lun->flags & CTL_LUN_PR_RESERVED) &&
5276 		    (cdb->how & SSS_START) == 0) {
5277 			uint32_t residx;
5278 
5279 			residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5280 			if (ctl_get_prkey(lun, residx) == 0 ||
5281 			    (lun->pr_res_idx != residx && lun->pr_res_type < 4)) {
5282 
5283 				ctl_set_reservation_conflict(ctsio);
5284 				ctl_done((union ctl_io *)ctsio);
5285 				return (CTL_RETVAL_COMPLETE);
5286 			}
5287 		}
5288 
5289 		if ((cdb->how & SSS_LOEJ) &&
5290 		    (lun->flags & CTL_LUN_REMOVABLE) == 0) {
5291 			ctl_set_invalid_field(ctsio,
5292 					      /*sks_valid*/ 1,
5293 					      /*command*/ 1,
5294 					      /*field*/ 4,
5295 					      /*bit_valid*/ 1,
5296 					      /*bit*/ 1);
5297 			ctl_done((union ctl_io *)ctsio);
5298 			return (CTL_RETVAL_COMPLETE);
5299 		}
5300 
5301 		if ((cdb->how & SSS_START) == 0 && (cdb->how & SSS_LOEJ) &&
5302 		    lun->prevent_count > 0) {
5303 			/* "Medium removal prevented" */
5304 			ctl_set_sense(ctsio, /*current_error*/ 1,
5305 			    /*sense_key*/(lun->flags & CTL_LUN_NO_MEDIA) ?
5306 			     SSD_KEY_NOT_READY : SSD_KEY_ILLEGAL_REQUEST,
5307 			    /*asc*/ 0x53, /*ascq*/ 0x02, SSD_ELEM_NONE);
5308 			ctl_done((union ctl_io *)ctsio);
5309 			return (CTL_RETVAL_COMPLETE);
5310 		}
5311 	}
5312 
5313 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5314 	return (retval);
5315 }
5316 
5317 int
5318 ctl_prevent_allow(struct ctl_scsiio *ctsio)
5319 {
5320 	struct ctl_lun *lun = CTL_LUN(ctsio);
5321 	struct scsi_prevent *cdb;
5322 	int retval;
5323 	uint32_t initidx;
5324 
5325 	CTL_DEBUG_PRINT(("ctl_prevent_allow\n"));
5326 
5327 	cdb = (struct scsi_prevent *)ctsio->cdb;
5328 
5329 	if ((lun->flags & CTL_LUN_REMOVABLE) == 0 || lun->prevent == NULL) {
5330 		ctl_set_invalid_opcode(ctsio);
5331 		ctl_done((union ctl_io *)ctsio);
5332 		return (CTL_RETVAL_COMPLETE);
5333 	}
5334 
5335 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5336 	mtx_lock(&lun->lun_lock);
5337 	if ((cdb->how & PR_PREVENT) &&
5338 	    ctl_is_set(lun->prevent, initidx) == 0) {
5339 		ctl_set_mask(lun->prevent, initidx);
5340 		lun->prevent_count++;
5341 	} else if ((cdb->how & PR_PREVENT) == 0 &&
5342 	    ctl_is_set(lun->prevent, initidx)) {
5343 		ctl_clear_mask(lun->prevent, initidx);
5344 		lun->prevent_count--;
5345 	}
5346 	mtx_unlock(&lun->lun_lock);
5347 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5348 	return (retval);
5349 }
5350 
5351 /*
5352  * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5353  * we don't really do anything with the LBA and length fields if the user
5354  * passes them in.  Instead we'll just flush out the cache for the entire
5355  * LUN.
5356  */
5357 int
5358 ctl_sync_cache(struct ctl_scsiio *ctsio)
5359 {
5360 	struct ctl_lun *lun = CTL_LUN(ctsio);
5361 	struct ctl_lba_len_flags *lbalen;
5362 	uint64_t starting_lba;
5363 	uint32_t block_count;
5364 	int retval;
5365 	uint8_t byte2;
5366 
5367 	CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5368 
5369 	retval = 0;
5370 
5371 	switch (ctsio->cdb[0]) {
5372 	case SYNCHRONIZE_CACHE: {
5373 		struct scsi_sync_cache *cdb;
5374 		cdb = (struct scsi_sync_cache *)ctsio->cdb;
5375 
5376 		starting_lba = scsi_4btoul(cdb->begin_lba);
5377 		block_count = scsi_2btoul(cdb->lb_count);
5378 		byte2 = cdb->byte2;
5379 		break;
5380 	}
5381 	case SYNCHRONIZE_CACHE_16: {
5382 		struct scsi_sync_cache_16 *cdb;
5383 		cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5384 
5385 		starting_lba = scsi_8btou64(cdb->begin_lba);
5386 		block_count = scsi_4btoul(cdb->lb_count);
5387 		byte2 = cdb->byte2;
5388 		break;
5389 	}
5390 	default:
5391 		ctl_set_invalid_opcode(ctsio);
5392 		ctl_done((union ctl_io *)ctsio);
5393 		goto bailout;
5394 		break; /* NOTREACHED */
5395 	}
5396 
5397 	/*
5398 	 * We check the LBA and length, but don't do anything with them.
5399 	 * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5400 	 * get flushed.  This check will just help satisfy anyone who wants
5401 	 * to see an error for an out of range LBA.
5402 	 */
5403 	if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5404 		ctl_set_lba_out_of_range(ctsio,
5405 		    MAX(starting_lba, lun->be_lun->maxlba + 1));
5406 		ctl_done((union ctl_io *)ctsio);
5407 		goto bailout;
5408 	}
5409 
5410 	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5411 	lbalen->lba = starting_lba;
5412 	lbalen->len = block_count;
5413 	lbalen->flags = byte2;
5414 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5415 
5416 bailout:
5417 	return (retval);
5418 }
5419 
5420 int
5421 ctl_format(struct ctl_scsiio *ctsio)
5422 {
5423 	struct scsi_format *cdb;
5424 	int length, defect_list_len;
5425 
5426 	CTL_DEBUG_PRINT(("ctl_format\n"));
5427 
5428 	cdb = (struct scsi_format *)ctsio->cdb;
5429 
5430 	length = 0;
5431 	if (cdb->byte2 & SF_FMTDATA) {
5432 		if (cdb->byte2 & SF_LONGLIST)
5433 			length = sizeof(struct scsi_format_header_long);
5434 		else
5435 			length = sizeof(struct scsi_format_header_short);
5436 	}
5437 
5438 	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5439 	 && (length > 0)) {
5440 		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5441 		ctsio->kern_data_len = length;
5442 		ctsio->kern_total_len = length;
5443 		ctsio->kern_rel_offset = 0;
5444 		ctsio->kern_sg_entries = 0;
5445 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5446 		ctsio->be_move_done = ctl_config_move_done;
5447 		ctl_datamove((union ctl_io *)ctsio);
5448 
5449 		return (CTL_RETVAL_COMPLETE);
5450 	}
5451 
5452 	defect_list_len = 0;
5453 
5454 	if (cdb->byte2 & SF_FMTDATA) {
5455 		if (cdb->byte2 & SF_LONGLIST) {
5456 			struct scsi_format_header_long *header;
5457 
5458 			header = (struct scsi_format_header_long *)
5459 				ctsio->kern_data_ptr;
5460 
5461 			defect_list_len = scsi_4btoul(header->defect_list_len);
5462 			if (defect_list_len != 0) {
5463 				ctl_set_invalid_field(ctsio,
5464 						      /*sks_valid*/ 1,
5465 						      /*command*/ 0,
5466 						      /*field*/ 2,
5467 						      /*bit_valid*/ 0,
5468 						      /*bit*/ 0);
5469 				goto bailout;
5470 			}
5471 		} else {
5472 			struct scsi_format_header_short *header;
5473 
5474 			header = (struct scsi_format_header_short *)
5475 				ctsio->kern_data_ptr;
5476 
5477 			defect_list_len = scsi_2btoul(header->defect_list_len);
5478 			if (defect_list_len != 0) {
5479 				ctl_set_invalid_field(ctsio,
5480 						      /*sks_valid*/ 1,
5481 						      /*command*/ 0,
5482 						      /*field*/ 2,
5483 						      /*bit_valid*/ 0,
5484 						      /*bit*/ 0);
5485 				goto bailout;
5486 			}
5487 		}
5488 	}
5489 
5490 	ctl_set_success(ctsio);
5491 bailout:
5492 
5493 	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5494 		free(ctsio->kern_data_ptr, M_CTL);
5495 		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5496 	}
5497 
5498 	ctl_done((union ctl_io *)ctsio);
5499 	return (CTL_RETVAL_COMPLETE);
5500 }
5501 
5502 int
5503 ctl_read_buffer(struct ctl_scsiio *ctsio)
5504 {
5505 	struct ctl_lun *lun = CTL_LUN(ctsio);
5506 	uint64_t buffer_offset;
5507 	uint32_t len;
5508 	uint8_t byte2;
5509 	static uint8_t descr[4];
5510 	static uint8_t echo_descr[4] = { 0 };
5511 
5512 	CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5513 
5514 	switch (ctsio->cdb[0]) {
5515 	case READ_BUFFER: {
5516 		struct scsi_read_buffer *cdb;
5517 
5518 		cdb = (struct scsi_read_buffer *)ctsio->cdb;
5519 		buffer_offset = scsi_3btoul(cdb->offset);
5520 		len = scsi_3btoul(cdb->length);
5521 		byte2 = cdb->byte2;
5522 		break;
5523 	}
5524 	case READ_BUFFER_16: {
5525 		struct scsi_read_buffer_16 *cdb;
5526 
5527 		cdb = (struct scsi_read_buffer_16 *)ctsio->cdb;
5528 		buffer_offset = scsi_8btou64(cdb->offset);
5529 		len = scsi_4btoul(cdb->length);
5530 		byte2 = cdb->byte2;
5531 		break;
5532 	}
5533 	default: /* This shouldn't happen. */
5534 		ctl_set_invalid_opcode(ctsio);
5535 		ctl_done((union ctl_io *)ctsio);
5536 		return (CTL_RETVAL_COMPLETE);
5537 	}
5538 
5539 	if (buffer_offset > CTL_WRITE_BUFFER_SIZE ||
5540 	    buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5541 		ctl_set_invalid_field(ctsio,
5542 				      /*sks_valid*/ 1,
5543 				      /*command*/ 1,
5544 				      /*field*/ 6,
5545 				      /*bit_valid*/ 0,
5546 				      /*bit*/ 0);
5547 		ctl_done((union ctl_io *)ctsio);
5548 		return (CTL_RETVAL_COMPLETE);
5549 	}
5550 
5551 	if ((byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5552 		descr[0] = 0;
5553 		scsi_ulto3b(CTL_WRITE_BUFFER_SIZE, &descr[1]);
5554 		ctsio->kern_data_ptr = descr;
5555 		len = min(len, sizeof(descr));
5556 	} else if ((byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5557 		ctsio->kern_data_ptr = echo_descr;
5558 		len = min(len, sizeof(echo_descr));
5559 	} else {
5560 		if (lun->write_buffer == NULL) {
5561 			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5562 			    M_CTL, M_WAITOK);
5563 		}
5564 		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5565 	}
5566 	ctsio->kern_data_len = len;
5567 	ctsio->kern_total_len = len;
5568 	ctsio->kern_rel_offset = 0;
5569 	ctsio->kern_sg_entries = 0;
5570 	ctl_set_success(ctsio);
5571 	ctsio->be_move_done = ctl_config_move_done;
5572 	ctl_datamove((union ctl_io *)ctsio);
5573 	return (CTL_RETVAL_COMPLETE);
5574 }
5575 
5576 int
5577 ctl_write_buffer(struct ctl_scsiio *ctsio)
5578 {
5579 	struct ctl_lun *lun = CTL_LUN(ctsio);
5580 	struct scsi_write_buffer *cdb;
5581 	int buffer_offset, len;
5582 
5583 	CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5584 
5585 	cdb = (struct scsi_write_buffer *)ctsio->cdb;
5586 
5587 	len = scsi_3btoul(cdb->length);
5588 	buffer_offset = scsi_3btoul(cdb->offset);
5589 
5590 	if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5591 		ctl_set_invalid_field(ctsio,
5592 				      /*sks_valid*/ 1,
5593 				      /*command*/ 1,
5594 				      /*field*/ 6,
5595 				      /*bit_valid*/ 0,
5596 				      /*bit*/ 0);
5597 		ctl_done((union ctl_io *)ctsio);
5598 		return (CTL_RETVAL_COMPLETE);
5599 	}
5600 
5601 	/*
5602 	 * If we've got a kernel request that hasn't been malloced yet,
5603 	 * malloc it and tell the caller the data buffer is here.
5604 	 */
5605 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5606 		if (lun->write_buffer == NULL) {
5607 			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5608 			    M_CTL, M_WAITOK);
5609 		}
5610 		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5611 		ctsio->kern_data_len = len;
5612 		ctsio->kern_total_len = len;
5613 		ctsio->kern_rel_offset = 0;
5614 		ctsio->kern_sg_entries = 0;
5615 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5616 		ctsio->be_move_done = ctl_config_move_done;
5617 		ctl_datamove((union ctl_io *)ctsio);
5618 
5619 		return (CTL_RETVAL_COMPLETE);
5620 	}
5621 
5622 	ctl_set_success(ctsio);
5623 	ctl_done((union ctl_io *)ctsio);
5624 	return (CTL_RETVAL_COMPLETE);
5625 }
5626 
5627 static int
5628 ctl_write_same_cont(union ctl_io *io)
5629 {
5630 	struct ctl_lun *lun = CTL_LUN(io);
5631 	struct ctl_scsiio *ctsio;
5632 	struct ctl_lba_len_flags *lbalen;
5633 	int retval;
5634 
5635 	ctsio = &io->scsiio;
5636 	ctsio->io_hdr.status = CTL_STATUS_NONE;
5637 	lbalen = (struct ctl_lba_len_flags *)
5638 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5639 	lbalen->lba += lbalen->len;
5640 	if ((lun->be_lun->maxlba + 1) - lbalen->lba <= UINT32_MAX) {
5641 		ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
5642 		lbalen->len = (lun->be_lun->maxlba + 1) - lbalen->lba;
5643 	}
5644 
5645 	CTL_DEBUG_PRINT(("ctl_write_same_cont: calling config_write()\n"));
5646 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5647 	return (retval);
5648 }
5649 
5650 int
5651 ctl_write_same(struct ctl_scsiio *ctsio)
5652 {
5653 	struct ctl_lun *lun = CTL_LUN(ctsio);
5654 	struct ctl_lba_len_flags *lbalen;
5655 	const char *val;
5656 	uint64_t lba, ival;
5657 	uint32_t num_blocks;
5658 	int len, retval;
5659 	uint8_t byte2;
5660 
5661 	CTL_DEBUG_PRINT(("ctl_write_same\n"));
5662 
5663 	switch (ctsio->cdb[0]) {
5664 	case WRITE_SAME_10: {
5665 		struct scsi_write_same_10 *cdb;
5666 
5667 		cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5668 
5669 		lba = scsi_4btoul(cdb->addr);
5670 		num_blocks = scsi_2btoul(cdb->length);
5671 		byte2 = cdb->byte2;
5672 		break;
5673 	}
5674 	case WRITE_SAME_16: {
5675 		struct scsi_write_same_16 *cdb;
5676 
5677 		cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5678 
5679 		lba = scsi_8btou64(cdb->addr);
5680 		num_blocks = scsi_4btoul(cdb->length);
5681 		byte2 = cdb->byte2;
5682 		break;
5683 	}
5684 	default:
5685 		/*
5686 		 * We got a command we don't support.  This shouldn't
5687 		 * happen, commands should be filtered out above us.
5688 		 */
5689 		ctl_set_invalid_opcode(ctsio);
5690 		ctl_done((union ctl_io *)ctsio);
5691 
5692 		return (CTL_RETVAL_COMPLETE);
5693 		break; /* NOTREACHED */
5694 	}
5695 
5696 	/* ANCHOR flag can be used only together with UNMAP */
5697 	if ((byte2 & SWS_UNMAP) == 0 && (byte2 & SWS_ANCHOR) != 0) {
5698 		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
5699 		    /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
5700 		ctl_done((union ctl_io *)ctsio);
5701 		return (CTL_RETVAL_COMPLETE);
5702 	}
5703 
5704 	/*
5705 	 * The first check is to make sure we're in bounds, the second
5706 	 * check is to catch wrap-around problems.  If the lba + num blocks
5707 	 * is less than the lba, then we've wrapped around and the block
5708 	 * range is invalid anyway.
5709 	 */
5710 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5711 	 || ((lba + num_blocks) < lba)) {
5712 		ctl_set_lba_out_of_range(ctsio,
5713 		    MAX(lba, lun->be_lun->maxlba + 1));
5714 		ctl_done((union ctl_io *)ctsio);
5715 		return (CTL_RETVAL_COMPLETE);
5716 	}
5717 
5718 	/* Zero number of blocks means "to the last logical block" */
5719 	if (num_blocks == 0) {
5720 		ival = UINT64_MAX;
5721 		val = dnvlist_get_string(lun->be_lun->options,
5722 		    "write_same_max_lba", NULL);
5723 		if (val != NULL)
5724 			ctl_expand_number(val, &ival);
5725 		if ((lun->be_lun->maxlba + 1) - lba > ival) {
5726 			ctl_set_invalid_field(ctsio,
5727 			    /*sks_valid*/ 1, /*command*/ 1,
5728 			    /*field*/ ctsio->cdb[0] == WRITE_SAME_10 ? 7 : 10,
5729 			    /*bit_valid*/ 0, /*bit*/ 0);
5730 			ctl_done((union ctl_io *)ctsio);
5731 			return (CTL_RETVAL_COMPLETE);
5732 		}
5733 		if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5734 			ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
5735 			ctsio->io_cont = ctl_write_same_cont;
5736 			num_blocks = 1 << 31;
5737 		} else
5738 			num_blocks = (lun->be_lun->maxlba + 1) - lba;
5739 	}
5740 
5741 	len = lun->be_lun->blocksize;
5742 
5743 	/*
5744 	 * If we've got a kernel request that hasn't been malloced yet,
5745 	 * malloc it and tell the caller the data buffer is here.
5746 	 */
5747 	if ((byte2 & SWS_NDOB) == 0 &&
5748 	    (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5749 		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);
5750 		ctsio->kern_data_len = len;
5751 		ctsio->kern_total_len = len;
5752 		ctsio->kern_rel_offset = 0;
5753 		ctsio->kern_sg_entries = 0;
5754 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5755 		ctsio->be_move_done = ctl_config_move_done;
5756 		ctl_datamove((union ctl_io *)ctsio);
5757 
5758 		return (CTL_RETVAL_COMPLETE);
5759 	}
5760 
5761 	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5762 	lbalen->lba = lba;
5763 	lbalen->len = num_blocks;
5764 	lbalen->flags = byte2;
5765 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5766 
5767 	return (retval);
5768 }
5769 
5770 int
5771 ctl_unmap(struct ctl_scsiio *ctsio)
5772 {
5773 	struct ctl_lun *lun = CTL_LUN(ctsio);
5774 	struct scsi_unmap *cdb;
5775 	struct ctl_ptr_len_flags *ptrlen;
5776 	struct scsi_unmap_header *hdr;
5777 	struct scsi_unmap_desc *buf, *end, *endnz, *range;
5778 	uint64_t lba;
5779 	uint32_t num_blocks;
5780 	int len, retval;
5781 	uint8_t byte2;
5782 
5783 	CTL_DEBUG_PRINT(("ctl_unmap\n"));
5784 
5785 	cdb = (struct scsi_unmap *)ctsio->cdb;
5786 	len = scsi_2btoul(cdb->length);
5787 	byte2 = cdb->byte2;
5788 
5789 	/*
5790 	 * If we've got a kernel request that hasn't been malloced yet,
5791 	 * malloc it and tell the caller the data buffer is here.
5792 	 */
5793 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5794 		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);
5795 		ctsio->kern_data_len = len;
5796 		ctsio->kern_total_len = len;
5797 		ctsio->kern_rel_offset = 0;
5798 		ctsio->kern_sg_entries = 0;
5799 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5800 		ctsio->be_move_done = ctl_config_move_done;
5801 		ctl_datamove((union ctl_io *)ctsio);
5802 
5803 		return (CTL_RETVAL_COMPLETE);
5804 	}
5805 
5806 	len = ctsio->kern_total_len - ctsio->kern_data_resid;
5807 	hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
5808 	if (len < sizeof (*hdr) ||
5809 	    len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
5810 	    len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
5811 	    scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
5812 		ctl_set_invalid_field(ctsio,
5813 				      /*sks_valid*/ 0,
5814 				      /*command*/ 0,
5815 				      /*field*/ 0,
5816 				      /*bit_valid*/ 0,
5817 				      /*bit*/ 0);
5818 		goto done;
5819 	}
5820 	len = scsi_2btoul(hdr->desc_length);
5821 	buf = (struct scsi_unmap_desc *)(hdr + 1);
5822 	end = buf + len / sizeof(*buf);
5823 
5824 	endnz = buf;
5825 	for (range = buf; range < end; range++) {
5826 		lba = scsi_8btou64(range->lba);
5827 		num_blocks = scsi_4btoul(range->length);
5828 		if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5829 		 || ((lba + num_blocks) < lba)) {
5830 			ctl_set_lba_out_of_range(ctsio,
5831 			    MAX(lba, lun->be_lun->maxlba + 1));
5832 			ctl_done((union ctl_io *)ctsio);
5833 			return (CTL_RETVAL_COMPLETE);
5834 		}
5835 		if (num_blocks != 0)
5836 			endnz = range + 1;
5837 	}
5838 
5839 	/*
5840 	 * Block backend can not handle zero last range.
5841 	 * Filter it out and return if there is nothing left.
5842 	 */
5843 	len = (uint8_t *)endnz - (uint8_t *)buf;
5844 	if (len == 0) {
5845 		ctl_set_success(ctsio);
5846 		goto done;
5847 	}
5848 
5849 	mtx_lock(&lun->lun_lock);
5850 	ptrlen = (struct ctl_ptr_len_flags *)
5851 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5852 	ptrlen->ptr = (void *)buf;
5853 	ptrlen->len = len;
5854 	ptrlen->flags = byte2;
5855 	ctl_try_unblock_others(lun, (union ctl_io *)ctsio, FALSE);
5856 	mtx_unlock(&lun->lun_lock);
5857 
5858 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5859 	return (retval);
5860 
5861 done:
5862 	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5863 		free(ctsio->kern_data_ptr, M_CTL);
5864 		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5865 	}
5866 	ctl_done((union ctl_io *)ctsio);
5867 	return (CTL_RETVAL_COMPLETE);
5868 }
5869 
5870 int
5871 ctl_default_page_handler(struct ctl_scsiio *ctsio,
5872 			 struct ctl_page_index *page_index, uint8_t *page_ptr)
5873 {
5874 	struct ctl_lun *lun = CTL_LUN(ctsio);
5875 	uint8_t *current_cp;
5876 	int set_ua;
5877 	uint32_t initidx;
5878 
5879 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5880 	set_ua = 0;
5881 
5882 	current_cp = (page_index->page_data + (page_index->page_len *
5883 	    CTL_PAGE_CURRENT));
5884 
5885 	mtx_lock(&lun->lun_lock);
5886 	if (memcmp(current_cp, page_ptr, page_index->page_len)) {
5887 		memcpy(current_cp, page_ptr, page_index->page_len);
5888 		set_ua = 1;
5889 	}
5890 	if (set_ua != 0)
5891 		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
5892 	mtx_unlock(&lun->lun_lock);
5893 	if (set_ua) {
5894 		ctl_isc_announce_mode(lun,
5895 		    ctl_get_initindex(&ctsio->io_hdr.nexus),
5896 		    page_index->page_code, page_index->subpage);
5897 	}
5898 	return (CTL_RETVAL_COMPLETE);
5899 }
5900 
5901 static void
5902 ctl_ie_timer(void *arg)
5903 {
5904 	struct ctl_lun *lun = arg;
5905 	uint64_t t;
5906 
5907 	if (lun->ie_asc == 0)
5908 		return;
5909 
5910 	if (lun->MODE_IE.mrie == SIEP_MRIE_UA)
5911 		ctl_est_ua_all(lun, -1, CTL_UA_IE);
5912 	else
5913 		lun->ie_reported = 0;
5914 
5915 	if (lun->ie_reportcnt < scsi_4btoul(lun->MODE_IE.report_count)) {
5916 		lun->ie_reportcnt++;
5917 		t = scsi_4btoul(lun->MODE_IE.interval_timer);
5918 		if (t == 0 || t == UINT32_MAX)
5919 			t = 3000;  /* 5 min */
5920 		callout_schedule(&lun->ie_callout, t * hz / 10);
5921 	}
5922 }
5923 
5924 int
5925 ctl_ie_page_handler(struct ctl_scsiio *ctsio,
5926 			 struct ctl_page_index *page_index, uint8_t *page_ptr)
5927 {
5928 	struct ctl_lun *lun = CTL_LUN(ctsio);
5929 	struct scsi_info_exceptions_page *pg;
5930 	uint64_t t;
5931 
5932 	(void)ctl_default_page_handler(ctsio, page_index, page_ptr);
5933 
5934 	pg = (struct scsi_info_exceptions_page *)page_ptr;
5935 	mtx_lock(&lun->lun_lock);
5936 	if (pg->info_flags & SIEP_FLAGS_TEST) {
5937 		lun->ie_asc = 0x5d;
5938 		lun->ie_ascq = 0xff;
5939 		if (pg->mrie == SIEP_MRIE_UA) {
5940 			ctl_est_ua_all(lun, -1, CTL_UA_IE);
5941 			lun->ie_reported = 1;
5942 		} else {
5943 			ctl_clr_ua_all(lun, -1, CTL_UA_IE);
5944 			lun->ie_reported = -1;
5945 		}
5946 		lun->ie_reportcnt = 1;
5947 		if (lun->ie_reportcnt < scsi_4btoul(pg->report_count)) {
5948 			lun->ie_reportcnt++;
5949 			t = scsi_4btoul(pg->interval_timer);
5950 			if (t == 0 || t == UINT32_MAX)
5951 				t = 3000;  /* 5 min */
5952 			callout_reset(&lun->ie_callout, t * hz / 10,
5953 			    ctl_ie_timer, lun);
5954 		}
5955 	} else {
5956 		lun->ie_asc = 0;
5957 		lun->ie_ascq = 0;
5958 		lun->ie_reported = 1;
5959 		ctl_clr_ua_all(lun, -1, CTL_UA_IE);
5960 		lun->ie_reportcnt = UINT32_MAX;
5961 		callout_stop(&lun->ie_callout);
5962 	}
5963 	mtx_unlock(&lun->lun_lock);
5964 	return (CTL_RETVAL_COMPLETE);
5965 }
5966 
5967 static int
5968 ctl_do_mode_select(union ctl_io *io)
5969 {
5970 	struct ctl_lun *lun = CTL_LUN(io);
5971 	struct scsi_mode_page_header *page_header;
5972 	struct ctl_page_index *page_index;
5973 	struct ctl_scsiio *ctsio;
5974 	int page_len, page_len_offset, page_len_size;
5975 	union ctl_modepage_info *modepage_info;
5976 	uint16_t *len_left, *len_used;
5977 	int retval, i;
5978 
5979 	ctsio = &io->scsiio;
5980 	page_index = NULL;
5981 	page_len = 0;
5982 
5983 	modepage_info = (union ctl_modepage_info *)
5984 		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
5985 	len_left = &modepage_info->header.len_left;
5986 	len_used = &modepage_info->header.len_used;
5987 
5988 do_next_page:
5989 
5990 	page_header = (struct scsi_mode_page_header *)
5991 		(ctsio->kern_data_ptr + *len_used);
5992 
5993 	if (*len_left == 0) {
5994 		free(ctsio->kern_data_ptr, M_CTL);
5995 		ctl_set_success(ctsio);
5996 		ctl_done((union ctl_io *)ctsio);
5997 		return (CTL_RETVAL_COMPLETE);
5998 	} else if (*len_left < sizeof(struct scsi_mode_page_header)) {
5999 
6000 		free(ctsio->kern_data_ptr, M_CTL);
6001 		ctl_set_param_len_error(ctsio);
6002 		ctl_done((union ctl_io *)ctsio);
6003 		return (CTL_RETVAL_COMPLETE);
6004 
6005 	} else if ((page_header->page_code & SMPH_SPF)
6006 		&& (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
6007 
6008 		free(ctsio->kern_data_ptr, M_CTL);
6009 		ctl_set_param_len_error(ctsio);
6010 		ctl_done((union ctl_io *)ctsio);
6011 		return (CTL_RETVAL_COMPLETE);
6012 	}
6013 
6014 
6015 	/*
6016 	 * XXX KDM should we do something with the block descriptor?
6017 	 */
6018 	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6019 		page_index = &lun->mode_pages.index[i];
6020 		if (lun->be_lun->lun_type == T_DIRECT &&
6021 		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6022 			continue;
6023 		if (lun->be_lun->lun_type == T_PROCESSOR &&
6024 		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6025 			continue;
6026 		if (lun->be_lun->lun_type == T_CDROM &&
6027 		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6028 			continue;
6029 
6030 		if ((page_index->page_code & SMPH_PC_MASK) !=
6031 		    (page_header->page_code & SMPH_PC_MASK))
6032 			continue;
6033 
6034 		/*
6035 		 * If neither page has a subpage code, then we've got a
6036 		 * match.
6037 		 */
6038 		if (((page_index->page_code & SMPH_SPF) == 0)
6039 		 && ((page_header->page_code & SMPH_SPF) == 0)) {
6040 			page_len = page_header->page_length;
6041 			break;
6042 		}
6043 
6044 		/*
6045 		 * If both pages have subpages, then the subpage numbers
6046 		 * have to match.
6047 		 */
6048 		if ((page_index->page_code & SMPH_SPF)
6049 		  && (page_header->page_code & SMPH_SPF)) {
6050 			struct scsi_mode_page_header_sp *sph;
6051 
6052 			sph = (struct scsi_mode_page_header_sp *)page_header;
6053 			if (page_index->subpage == sph->subpage) {
6054 				page_len = scsi_2btoul(sph->page_length);
6055 				break;
6056 			}
6057 		}
6058 	}
6059 
6060 	/*
6061 	 * If we couldn't find the page, or if we don't have a mode select
6062 	 * handler for it, send back an error to the user.
6063 	 */
6064 	if ((i >= CTL_NUM_MODE_PAGES)
6065 	 || (page_index->select_handler == NULL)) {
6066 		ctl_set_invalid_field(ctsio,
6067 				      /*sks_valid*/ 1,
6068 				      /*command*/ 0,
6069 				      /*field*/ *len_used,
6070 				      /*bit_valid*/ 0,
6071 				      /*bit*/ 0);
6072 		free(ctsio->kern_data_ptr, M_CTL);
6073 		ctl_done((union ctl_io *)ctsio);
6074 		return (CTL_RETVAL_COMPLETE);
6075 	}
6076 
6077 	if (page_index->page_code & SMPH_SPF) {
6078 		page_len_offset = 2;
6079 		page_len_size = 2;
6080 	} else {
6081 		page_len_size = 1;
6082 		page_len_offset = 1;
6083 	}
6084 
6085 	/*
6086 	 * If the length the initiator gives us isn't the one we specify in
6087 	 * the mode page header, or if they didn't specify enough data in
6088 	 * the CDB to avoid truncating this page, kick out the request.
6089 	 */
6090 	if (page_len != page_index->page_len - page_len_offset - page_len_size) {
6091 		ctl_set_invalid_field(ctsio,
6092 				      /*sks_valid*/ 1,
6093 				      /*command*/ 0,
6094 				      /*field*/ *len_used + page_len_offset,
6095 				      /*bit_valid*/ 0,
6096 				      /*bit*/ 0);
6097 		free(ctsio->kern_data_ptr, M_CTL);
6098 		ctl_done((union ctl_io *)ctsio);
6099 		return (CTL_RETVAL_COMPLETE);
6100 	}
6101 	if (*len_left < page_index->page_len) {
6102 		free(ctsio->kern_data_ptr, M_CTL);
6103 		ctl_set_param_len_error(ctsio);
6104 		ctl_done((union ctl_io *)ctsio);
6105 		return (CTL_RETVAL_COMPLETE);
6106 	}
6107 
6108 	/*
6109 	 * Run through the mode page, checking to make sure that the bits
6110 	 * the user changed are actually legal for him to change.
6111 	 */
6112 	for (i = 0; i < page_index->page_len; i++) {
6113 		uint8_t *user_byte, *change_mask, *current_byte;
6114 		int bad_bit;
6115 		int j;
6116 
6117 		user_byte = (uint8_t *)page_header + i;
6118 		change_mask = page_index->page_data +
6119 			      (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6120 		current_byte = page_index->page_data +
6121 			       (page_index->page_len * CTL_PAGE_CURRENT) + i;
6122 
6123 		/*
6124 		 * Check to see whether the user set any bits in this byte
6125 		 * that he is not allowed to set.
6126 		 */
6127 		if ((*user_byte & ~(*change_mask)) ==
6128 		    (*current_byte & ~(*change_mask)))
6129 			continue;
6130 
6131 		/*
6132 		 * Go through bit by bit to determine which one is illegal.
6133 		 */
6134 		bad_bit = 0;
6135 		for (j = 7; j >= 0; j--) {
6136 			if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6137 			    (((1 << i) & ~(*change_mask)) & *current_byte)) {
6138 				bad_bit = i;
6139 				break;
6140 			}
6141 		}
6142 		ctl_set_invalid_field(ctsio,
6143 				      /*sks_valid*/ 1,
6144 				      /*command*/ 0,
6145 				      /*field*/ *len_used + i,
6146 				      /*bit_valid*/ 1,
6147 				      /*bit*/ bad_bit);
6148 		free(ctsio->kern_data_ptr, M_CTL);
6149 		ctl_done((union ctl_io *)ctsio);
6150 		return (CTL_RETVAL_COMPLETE);
6151 	}
6152 
6153 	/*
6154 	 * Decrement these before we call the page handler, since we may
6155 	 * end up getting called back one way or another before the handler
6156 	 * returns to this context.
6157 	 */
6158 	*len_left -= page_index->page_len;
6159 	*len_used += page_index->page_len;
6160 
6161 	retval = page_index->select_handler(ctsio, page_index,
6162 					    (uint8_t *)page_header);
6163 
6164 	/*
6165 	 * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6166 	 * wait until this queued command completes to finish processing
6167 	 * the mode page.  If it returns anything other than
6168 	 * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6169 	 * already set the sense information, freed the data pointer, and
6170 	 * completed the io for us.
6171 	 */
6172 	if (retval != CTL_RETVAL_COMPLETE)
6173 		goto bailout_no_done;
6174 
6175 	/*
6176 	 * If the initiator sent us more than one page, parse the next one.
6177 	 */
6178 	if (*len_left > 0)
6179 		goto do_next_page;
6180 
6181 	ctl_set_success(ctsio);
6182 	free(ctsio->kern_data_ptr, M_CTL);
6183 	ctl_done((union ctl_io *)ctsio);
6184 
6185 bailout_no_done:
6186 
6187 	return (CTL_RETVAL_COMPLETE);
6188 
6189 }
6190 
6191 int
6192 ctl_mode_select(struct ctl_scsiio *ctsio)
6193 {
6194 	struct ctl_lun *lun = CTL_LUN(ctsio);
6195 	union ctl_modepage_info *modepage_info;
6196 	int bd_len, i, header_size, param_len, rtd;
6197 	uint32_t initidx;
6198 
6199 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6200 	switch (ctsio->cdb[0]) {
6201 	case MODE_SELECT_6: {
6202 		struct scsi_mode_select_6 *cdb;
6203 
6204 		cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6205 
6206 		rtd = (cdb->byte2 & SMS_RTD) ? 1 : 0;
6207 		param_len = cdb->length;
6208 		header_size = sizeof(struct scsi_mode_header_6);
6209 		break;
6210 	}
6211 	case MODE_SELECT_10: {
6212 		struct scsi_mode_select_10 *cdb;
6213 
6214 		cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6215 
6216 		rtd = (cdb->byte2 & SMS_RTD) ? 1 : 0;
6217 		param_len = scsi_2btoul(cdb->length);
6218 		header_size = sizeof(struct scsi_mode_header_10);
6219 		break;
6220 	}
6221 	default:
6222 		ctl_set_invalid_opcode(ctsio);
6223 		ctl_done((union ctl_io *)ctsio);
6224 		return (CTL_RETVAL_COMPLETE);
6225 	}
6226 
6227 	if (rtd) {
6228 		if (param_len != 0) {
6229 			ctl_set_invalid_field(ctsio, /*sks_valid*/ 0,
6230 			    /*command*/ 1, /*field*/ 0,
6231 			    /*bit_valid*/ 0, /*bit*/ 0);
6232 			ctl_done((union ctl_io *)ctsio);
6233 			return (CTL_RETVAL_COMPLETE);
6234 		}
6235 
6236 		/* Revert to defaults. */
6237 		ctl_init_page_index(lun);
6238 		mtx_lock(&lun->lun_lock);
6239 		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
6240 		mtx_unlock(&lun->lun_lock);
6241 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6242 			ctl_isc_announce_mode(lun, -1,
6243 			    lun->mode_pages.index[i].page_code & SMPH_PC_MASK,
6244 			    lun->mode_pages.index[i].subpage);
6245 		}
6246 		ctl_set_success(ctsio);
6247 		ctl_done((union ctl_io *)ctsio);
6248 		return (CTL_RETVAL_COMPLETE);
6249 	}
6250 
6251 	/*
6252 	 * From SPC-3:
6253 	 * "A parameter list length of zero indicates that the Data-Out Buffer
6254 	 * shall be empty. This condition shall not be considered as an error."
6255 	 */
6256 	if (param_len == 0) {
6257 		ctl_set_success(ctsio);
6258 		ctl_done((union ctl_io *)ctsio);
6259 		return (CTL_RETVAL_COMPLETE);
6260 	}
6261 
6262 	/*
6263 	 * Since we'll hit this the first time through, prior to
6264 	 * allocation, we don't need to free a data buffer here.
6265 	 */
6266 	if (param_len < header_size) {
6267 		ctl_set_param_len_error(ctsio);
6268 		ctl_done((union ctl_io *)ctsio);
6269 		return (CTL_RETVAL_COMPLETE);
6270 	}
6271 
6272 	/*
6273 	 * Allocate the data buffer and grab the user's data.  In theory,
6274 	 * we shouldn't have to sanity check the parameter list length here
6275 	 * because the maximum size is 64K.  We should be able to malloc
6276 	 * that much without too many problems.
6277 	 */
6278 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6279 		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6280 		ctsio->kern_data_len = param_len;
6281 		ctsio->kern_total_len = param_len;
6282 		ctsio->kern_rel_offset = 0;
6283 		ctsio->kern_sg_entries = 0;
6284 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6285 		ctsio->be_move_done = ctl_config_move_done;
6286 		ctl_datamove((union ctl_io *)ctsio);
6287 
6288 		return (CTL_RETVAL_COMPLETE);
6289 	}
6290 
6291 	switch (ctsio->cdb[0]) {
6292 	case MODE_SELECT_6: {
6293 		struct scsi_mode_header_6 *mh6;
6294 
6295 		mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6296 		bd_len = mh6->blk_desc_len;
6297 		break;
6298 	}
6299 	case MODE_SELECT_10: {
6300 		struct scsi_mode_header_10 *mh10;
6301 
6302 		mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6303 		bd_len = scsi_2btoul(mh10->blk_desc_len);
6304 		break;
6305 	}
6306 	default:
6307 		panic("%s: Invalid CDB type %#x", __func__, ctsio->cdb[0]);
6308 	}
6309 
6310 	if (param_len < (header_size + bd_len)) {
6311 		free(ctsio->kern_data_ptr, M_CTL);
6312 		ctl_set_param_len_error(ctsio);
6313 		ctl_done((union ctl_io *)ctsio);
6314 		return (CTL_RETVAL_COMPLETE);
6315 	}
6316 
6317 	/*
6318 	 * Set the IO_CONT flag, so that if this I/O gets passed to
6319 	 * ctl_config_write_done(), it'll get passed back to
6320 	 * ctl_do_mode_select() for further processing, or completion if
6321 	 * we're all done.
6322 	 */
6323 	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6324 	ctsio->io_cont = ctl_do_mode_select;
6325 
6326 	modepage_info = (union ctl_modepage_info *)
6327 		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6328 	memset(modepage_info, 0, sizeof(*modepage_info));
6329 	modepage_info->header.len_left = param_len - header_size - bd_len;
6330 	modepage_info->header.len_used = header_size + bd_len;
6331 
6332 	return (ctl_do_mode_select((union ctl_io *)ctsio));
6333 }
6334 
6335 int
6336 ctl_mode_sense(struct ctl_scsiio *ctsio)
6337 {
6338 	struct ctl_lun *lun = CTL_LUN(ctsio);
6339 	int pc, page_code, llba, subpage;
6340 	int alloc_len, page_len, header_len, bd_len, total_len;
6341 	void *block_desc;
6342 	struct ctl_page_index *page_index;
6343 
6344 	llba = 0;
6345 
6346 	CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6347 
6348 	switch (ctsio->cdb[0]) {
6349 	case MODE_SENSE_6: {
6350 		struct scsi_mode_sense_6 *cdb;
6351 
6352 		cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6353 
6354 		header_len = sizeof(struct scsi_mode_hdr_6);
6355 		if (cdb->byte2 & SMS_DBD)
6356 			bd_len = 0;
6357 		else
6358 			bd_len = sizeof(struct scsi_mode_block_descr);
6359 		header_len += bd_len;
6360 
6361 		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6362 		page_code = cdb->page & SMS_PAGE_CODE;
6363 		subpage = cdb->subpage;
6364 		alloc_len = cdb->length;
6365 		break;
6366 	}
6367 	case MODE_SENSE_10: {
6368 		struct scsi_mode_sense_10 *cdb;
6369 
6370 		cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6371 
6372 		header_len = sizeof(struct scsi_mode_hdr_10);
6373 		if (cdb->byte2 & SMS_DBD) {
6374 			bd_len = 0;
6375 		} else if (lun->be_lun->lun_type == T_DIRECT) {
6376 			if (cdb->byte2 & SMS10_LLBAA) {
6377 				llba = 1;
6378 				bd_len = sizeof(struct scsi_mode_block_descr_dlong);
6379 			} else
6380 				bd_len = sizeof(struct scsi_mode_block_descr_dshort);
6381 		} else
6382 			bd_len = sizeof(struct scsi_mode_block_descr);
6383 		header_len += bd_len;
6384 
6385 		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6386 		page_code = cdb->page & SMS_PAGE_CODE;
6387 		subpage = cdb->subpage;
6388 		alloc_len = scsi_2btoul(cdb->length);
6389 		break;
6390 	}
6391 	default:
6392 		ctl_set_invalid_opcode(ctsio);
6393 		ctl_done((union ctl_io *)ctsio);
6394 		return (CTL_RETVAL_COMPLETE);
6395 		break; /* NOTREACHED */
6396 	}
6397 
6398 	/*
6399 	 * We have to make a first pass through to calculate the size of
6400 	 * the pages that match the user's query.  Then we allocate enough
6401 	 * memory to hold it, and actually copy the data into the buffer.
6402 	 */
6403 	switch (page_code) {
6404 	case SMS_ALL_PAGES_PAGE: {
6405 		u_int i;
6406 
6407 		page_len = 0;
6408 
6409 		/*
6410 		 * At the moment, values other than 0 and 0xff here are
6411 		 * reserved according to SPC-3.
6412 		 */
6413 		if ((subpage != SMS_SUBPAGE_PAGE_0)
6414 		 && (subpage != SMS_SUBPAGE_ALL)) {
6415 			ctl_set_invalid_field(ctsio,
6416 					      /*sks_valid*/ 1,
6417 					      /*command*/ 1,
6418 					      /*field*/ 3,
6419 					      /*bit_valid*/ 0,
6420 					      /*bit*/ 0);
6421 			ctl_done((union ctl_io *)ctsio);
6422 			return (CTL_RETVAL_COMPLETE);
6423 		}
6424 
6425 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6426 			page_index = &lun->mode_pages.index[i];
6427 
6428 			/* Make sure the page is supported for this dev type */
6429 			if (lun->be_lun->lun_type == T_DIRECT &&
6430 			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6431 				continue;
6432 			if (lun->be_lun->lun_type == T_PROCESSOR &&
6433 			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6434 				continue;
6435 			if (lun->be_lun->lun_type == T_CDROM &&
6436 			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6437 				continue;
6438 
6439 			/*
6440 			 * We don't use this subpage if the user didn't
6441 			 * request all subpages.
6442 			 */
6443 			if ((page_index->subpage != 0)
6444 			 && (subpage == SMS_SUBPAGE_PAGE_0))
6445 				continue;
6446 
6447 			page_len += page_index->page_len;
6448 		}
6449 		break;
6450 	}
6451 	default: {
6452 		u_int i;
6453 
6454 		page_len = 0;
6455 
6456 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6457 			page_index = &lun->mode_pages.index[i];
6458 
6459 			/* Make sure the page is supported for this dev type */
6460 			if (lun->be_lun->lun_type == T_DIRECT &&
6461 			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6462 				continue;
6463 			if (lun->be_lun->lun_type == T_PROCESSOR &&
6464 			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6465 				continue;
6466 			if (lun->be_lun->lun_type == T_CDROM &&
6467 			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6468 				continue;
6469 
6470 			/* Look for the right page code */
6471 			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6472 				continue;
6473 
6474 			/* Look for the right subpage or the subpage wildcard*/
6475 			if ((page_index->subpage != subpage)
6476 			 && (subpage != SMS_SUBPAGE_ALL))
6477 				continue;
6478 
6479 			page_len += page_index->page_len;
6480 		}
6481 
6482 		if (page_len == 0) {
6483 			ctl_set_invalid_field(ctsio,
6484 					      /*sks_valid*/ 1,
6485 					      /*command*/ 1,
6486 					      /*field*/ 2,
6487 					      /*bit_valid*/ 1,
6488 					      /*bit*/ 5);
6489 			ctl_done((union ctl_io *)ctsio);
6490 			return (CTL_RETVAL_COMPLETE);
6491 		}
6492 		break;
6493 	}
6494 	}
6495 
6496 	total_len = header_len + page_len;
6497 
6498 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6499 	ctsio->kern_sg_entries = 0;
6500 	ctsio->kern_rel_offset = 0;
6501 	ctsio->kern_data_len = min(total_len, alloc_len);
6502 	ctsio->kern_total_len = ctsio->kern_data_len;
6503 
6504 	switch (ctsio->cdb[0]) {
6505 	case MODE_SENSE_6: {
6506 		struct scsi_mode_hdr_6 *header;
6507 
6508 		header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6509 
6510 		header->datalen = MIN(total_len - 1, 254);
6511 		if (lun->be_lun->lun_type == T_DIRECT) {
6512 			header->dev_specific = 0x10; /* DPOFUA */
6513 			if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6514 			    (lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0)
6515 				header->dev_specific |= 0x80; /* WP */
6516 		}
6517 		header->block_descr_len = bd_len;
6518 		block_desc = &header[1];
6519 		break;
6520 	}
6521 	case MODE_SENSE_10: {
6522 		struct scsi_mode_hdr_10 *header;
6523 		int datalen;
6524 
6525 		header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6526 
6527 		datalen = MIN(total_len - 2, 65533);
6528 		scsi_ulto2b(datalen, header->datalen);
6529 		if (lun->be_lun->lun_type == T_DIRECT) {
6530 			header->dev_specific = 0x10; /* DPOFUA */
6531 			if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6532 			    (lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0)
6533 				header->dev_specific |= 0x80; /* WP */
6534 		}
6535 		if (llba)
6536 			header->flags |= SMH_LONGLBA;
6537 		scsi_ulto2b(bd_len, header->block_descr_len);
6538 		block_desc = &header[1];
6539 		break;
6540 	}
6541 	default:
6542 		panic("%s: Invalid CDB type %#x", __func__, ctsio->cdb[0]);
6543 	}
6544 
6545 	/*
6546 	 * If we've got a disk, use its blocksize in the block
6547 	 * descriptor.  Otherwise, just set it to 0.
6548 	 */
6549 	if (bd_len > 0) {
6550 		if (lun->be_lun->lun_type == T_DIRECT) {
6551 			if (llba) {
6552 				struct scsi_mode_block_descr_dlong *bd = block_desc;
6553 				if (lun->be_lun->maxlba != 0)
6554 					scsi_u64to8b(lun->be_lun->maxlba + 1,
6555 					    bd->num_blocks);
6556 				scsi_ulto4b(lun->be_lun->blocksize,
6557 				    bd->block_len);
6558 			} else {
6559 				struct scsi_mode_block_descr_dshort *bd = block_desc;
6560 				if (lun->be_lun->maxlba != 0)
6561 					scsi_ulto4b(MIN(lun->be_lun->maxlba+1,
6562 					    UINT32_MAX), bd->num_blocks);
6563 				scsi_ulto3b(lun->be_lun->blocksize,
6564 				    bd->block_len);
6565 			}
6566 		} else {
6567 			struct scsi_mode_block_descr *bd = block_desc;
6568 			scsi_ulto3b(0, bd->block_len);
6569 		}
6570 	}
6571 
6572 	switch (page_code) {
6573 	case SMS_ALL_PAGES_PAGE: {
6574 		int i, data_used;
6575 
6576 		data_used = header_len;
6577 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6578 			struct ctl_page_index *page_index;
6579 
6580 			page_index = &lun->mode_pages.index[i];
6581 			if (lun->be_lun->lun_type == T_DIRECT &&
6582 			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6583 				continue;
6584 			if (lun->be_lun->lun_type == T_PROCESSOR &&
6585 			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6586 				continue;
6587 			if (lun->be_lun->lun_type == T_CDROM &&
6588 			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6589 				continue;
6590 
6591 			/*
6592 			 * We don't use this subpage if the user didn't
6593 			 * request all subpages.  We already checked (above)
6594 			 * to make sure the user only specified a subpage
6595 			 * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
6596 			 */
6597 			if ((page_index->subpage != 0)
6598 			 && (subpage == SMS_SUBPAGE_PAGE_0))
6599 				continue;
6600 
6601 			/*
6602 			 * Call the handler, if it exists, to update the
6603 			 * page to the latest values.
6604 			 */
6605 			if (page_index->sense_handler != NULL)
6606 				page_index->sense_handler(ctsio, page_index,pc);
6607 
6608 			memcpy(ctsio->kern_data_ptr + data_used,
6609 			       page_index->page_data +
6610 			       (page_index->page_len * pc),
6611 			       page_index->page_len);
6612 			data_used += page_index->page_len;
6613 		}
6614 		break;
6615 	}
6616 	default: {
6617 		int i, data_used;
6618 
6619 		data_used = header_len;
6620 
6621 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6622 			struct ctl_page_index *page_index;
6623 
6624 			page_index = &lun->mode_pages.index[i];
6625 
6626 			/* Look for the right page code */
6627 			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6628 				continue;
6629 
6630 			/* Look for the right subpage or the subpage wildcard*/
6631 			if ((page_index->subpage != subpage)
6632 			 && (subpage != SMS_SUBPAGE_ALL))
6633 				continue;
6634 
6635 			/* Make sure the page is supported for this dev type */
6636 			if (lun->be_lun->lun_type == T_DIRECT &&
6637 			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6638 				continue;
6639 			if (lun->be_lun->lun_type == T_PROCESSOR &&
6640 			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6641 				continue;
6642 			if (lun->be_lun->lun_type == T_CDROM &&
6643 			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6644 				continue;
6645 
6646 			/*
6647 			 * Call the handler, if it exists, to update the
6648 			 * page to the latest values.
6649 			 */
6650 			if (page_index->sense_handler != NULL)
6651 				page_index->sense_handler(ctsio, page_index,pc);
6652 
6653 			memcpy(ctsio->kern_data_ptr + data_used,
6654 			       page_index->page_data +
6655 			       (page_index->page_len * pc),
6656 			       page_index->page_len);
6657 			data_used += page_index->page_len;
6658 		}
6659 		break;
6660 	}
6661 	}
6662 
6663 	ctl_set_success(ctsio);
6664 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6665 	ctsio->be_move_done = ctl_config_move_done;
6666 	ctl_datamove((union ctl_io *)ctsio);
6667 	return (CTL_RETVAL_COMPLETE);
6668 }
6669 
6670 int
6671 ctl_temp_log_sense_handler(struct ctl_scsiio *ctsio,
6672 			       struct ctl_page_index *page_index,
6673 			       int pc)
6674 {
6675 	struct ctl_lun *lun = CTL_LUN(ctsio);
6676 	struct scsi_log_temperature *data;
6677 	const char *value;
6678 
6679 	data = (struct scsi_log_temperature *)page_index->page_data;
6680 
6681 	scsi_ulto2b(SLP_TEMPERATURE, data->hdr.param_code);
6682 	data->hdr.param_control = SLP_LBIN;
6683 	data->hdr.param_len = sizeof(struct scsi_log_temperature) -
6684 	    sizeof(struct scsi_log_param_header);
6685 	if ((value = dnvlist_get_string(lun->be_lun->options, "temperature",
6686 	    NULL)) != NULL)
6687 		data->temperature = strtol(value, NULL, 0);
6688 	else
6689 		data->temperature = 0xff;
6690 	data++;
6691 
6692 	scsi_ulto2b(SLP_REFTEMPERATURE, data->hdr.param_code);
6693 	data->hdr.param_control = SLP_LBIN;
6694 	data->hdr.param_len = sizeof(struct scsi_log_temperature) -
6695 	    sizeof(struct scsi_log_param_header);
6696 	if ((value = dnvlist_get_string(lun->be_lun->options, "reftemperature",
6697 	    NULL)) != NULL)
6698 		data->temperature = strtol(value, NULL, 0);
6699 	else
6700 		data->temperature = 0xff;
6701 	return (0);
6702 }
6703 
6704 int
6705 ctl_lbp_log_sense_handler(struct ctl_scsiio *ctsio,
6706 			       struct ctl_page_index *page_index,
6707 			       int pc)
6708 {
6709 	struct ctl_lun *lun = CTL_LUN(ctsio);
6710 	struct scsi_log_param_header *phdr;
6711 	uint8_t *data;
6712 	uint64_t val;
6713 
6714 	data = page_index->page_data;
6715 
6716 	if (lun->backend->lun_attr != NULL &&
6717 	    (val = lun->backend->lun_attr(lun->be_lun, "blocksavail"))
6718 	     != UINT64_MAX) {
6719 		phdr = (struct scsi_log_param_header *)data;
6720 		scsi_ulto2b(0x0001, phdr->param_code);
6721 		phdr->param_control = SLP_LBIN | SLP_LP;
6722 		phdr->param_len = 8;
6723 		data = (uint8_t *)(phdr + 1);
6724 		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6725 		data[4] = 0x02; /* per-pool */
6726 		data += phdr->param_len;
6727 	}
6728 
6729 	if (lun->backend->lun_attr != NULL &&
6730 	    (val = lun->backend->lun_attr(lun->be_lun, "blocksused"))
6731 	     != UINT64_MAX) {
6732 		phdr = (struct scsi_log_param_header *)data;
6733 		scsi_ulto2b(0x0002, phdr->param_code);
6734 		phdr->param_control = SLP_LBIN | SLP_LP;
6735 		phdr->param_len = 8;
6736 		data = (uint8_t *)(phdr + 1);
6737 		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6738 		data[4] = 0x01; /* per-LUN */
6739 		data += phdr->param_len;
6740 	}
6741 
6742 	if (lun->backend->lun_attr != NULL &&
6743 	    (val = lun->backend->lun_attr(lun->be_lun, "poolblocksavail"))
6744 	     != UINT64_MAX) {
6745 		phdr = (struct scsi_log_param_header *)data;
6746 		scsi_ulto2b(0x00f1, phdr->param_code);
6747 		phdr->param_control = SLP_LBIN | SLP_LP;
6748 		phdr->param_len = 8;
6749 		data = (uint8_t *)(phdr + 1);
6750 		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6751 		data[4] = 0x02; /* per-pool */
6752 		data += phdr->param_len;
6753 	}
6754 
6755 	if (lun->backend->lun_attr != NULL &&
6756 	    (val = lun->backend->lun_attr(lun->be_lun, "poolblocksused"))
6757 	     != UINT64_MAX) {
6758 		phdr = (struct scsi_log_param_header *)data;
6759 		scsi_ulto2b(0x00f2, phdr->param_code);
6760 		phdr->param_control = SLP_LBIN | SLP_LP;
6761 		phdr->param_len = 8;
6762 		data = (uint8_t *)(phdr + 1);
6763 		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6764 		data[4] = 0x02; /* per-pool */
6765 		data += phdr->param_len;
6766 	}
6767 
6768 	page_index->page_len = data - page_index->page_data;
6769 	return (0);
6770 }
6771 
6772 int
6773 ctl_sap_log_sense_handler(struct ctl_scsiio *ctsio,
6774 			       struct ctl_page_index *page_index,
6775 			       int pc)
6776 {
6777 	struct ctl_lun *lun = CTL_LUN(ctsio);
6778 	struct stat_page *data;
6779 	struct bintime *t;
6780 
6781 	data = (struct stat_page *)page_index->page_data;
6782 
6783 	scsi_ulto2b(SLP_SAP, data->sap.hdr.param_code);
6784 	data->sap.hdr.param_control = SLP_LBIN;
6785 	data->sap.hdr.param_len = sizeof(struct scsi_log_stat_and_perf) -
6786 	    sizeof(struct scsi_log_param_header);
6787 	scsi_u64to8b(lun->stats.operations[CTL_STATS_READ],
6788 	    data->sap.read_num);
6789 	scsi_u64to8b(lun->stats.operations[CTL_STATS_WRITE],
6790 	    data->sap.write_num);
6791 	if (lun->be_lun->blocksize > 0) {
6792 		scsi_u64to8b(lun->stats.bytes[CTL_STATS_WRITE] /
6793 		    lun->be_lun->blocksize, data->sap.recvieved_lba);
6794 		scsi_u64to8b(lun->stats.bytes[CTL_STATS_READ] /
6795 		    lun->be_lun->blocksize, data->sap.transmitted_lba);
6796 	}
6797 	t = &lun->stats.time[CTL_STATS_READ];
6798 	scsi_u64to8b((uint64_t)t->sec * 1000 + t->frac / (UINT64_MAX / 1000),
6799 	    data->sap.read_int);
6800 	t = &lun->stats.time[CTL_STATS_WRITE];
6801 	scsi_u64to8b((uint64_t)t->sec * 1000 + t->frac / (UINT64_MAX / 1000),
6802 	    data->sap.write_int);
6803 	scsi_u64to8b(0, data->sap.weighted_num);
6804 	scsi_u64to8b(0, data->sap.weighted_int);
6805 	scsi_ulto2b(SLP_IT, data->it.hdr.param_code);
6806 	data->it.hdr.param_control = SLP_LBIN;
6807 	data->it.hdr.param_len = sizeof(struct scsi_log_idle_time) -
6808 	    sizeof(struct scsi_log_param_header);
6809 #ifdef CTL_TIME_IO
6810 	scsi_u64to8b(lun->idle_time / SBT_1MS, data->it.idle_int);
6811 #endif
6812 	scsi_ulto2b(SLP_TI, data->ti.hdr.param_code);
6813 	data->it.hdr.param_control = SLP_LBIN;
6814 	data->ti.hdr.param_len = sizeof(struct scsi_log_time_interval) -
6815 	    sizeof(struct scsi_log_param_header);
6816 	scsi_ulto4b(3, data->ti.exponent);
6817 	scsi_ulto4b(1, data->ti.integer);
6818 	return (0);
6819 }
6820 
6821 int
6822 ctl_ie_log_sense_handler(struct ctl_scsiio *ctsio,
6823 			       struct ctl_page_index *page_index,
6824 			       int pc)
6825 {
6826 	struct ctl_lun *lun = CTL_LUN(ctsio);
6827 	struct scsi_log_informational_exceptions *data;
6828 	const char *value;
6829 
6830 	data = (struct scsi_log_informational_exceptions *)page_index->page_data;
6831 
6832 	scsi_ulto2b(SLP_IE_GEN, data->hdr.param_code);
6833 	data->hdr.param_control = SLP_LBIN;
6834 	data->hdr.param_len = sizeof(struct scsi_log_informational_exceptions) -
6835 	    sizeof(struct scsi_log_param_header);
6836 	data->ie_asc = lun->ie_asc;
6837 	data->ie_ascq = lun->ie_ascq;
6838 	if ((value = dnvlist_get_string(lun->be_lun->options, "temperature",
6839 	    NULL)) != NULL)
6840 		data->temperature = strtol(value, NULL, 0);
6841 	else
6842 		data->temperature = 0xff;
6843 	return (0);
6844 }
6845 
6846 int
6847 ctl_log_sense(struct ctl_scsiio *ctsio)
6848 {
6849 	struct ctl_lun *lun = CTL_LUN(ctsio);
6850 	int i, pc, page_code, subpage;
6851 	int alloc_len, total_len;
6852 	struct ctl_page_index *page_index;
6853 	struct scsi_log_sense *cdb;
6854 	struct scsi_log_header *header;
6855 
6856 	CTL_DEBUG_PRINT(("ctl_log_sense\n"));
6857 
6858 	cdb = (struct scsi_log_sense *)ctsio->cdb;
6859 	pc = (cdb->page & SLS_PAGE_CTRL_MASK) >> 6;
6860 	page_code = cdb->page & SLS_PAGE_CODE;
6861 	subpage = cdb->subpage;
6862 	alloc_len = scsi_2btoul(cdb->length);
6863 
6864 	page_index = NULL;
6865 	for (i = 0; i < CTL_NUM_LOG_PAGES; i++) {
6866 		page_index = &lun->log_pages.index[i];
6867 
6868 		/* Look for the right page code */
6869 		if ((page_index->page_code & SL_PAGE_CODE) != page_code)
6870 			continue;
6871 
6872 		/* Look for the right subpage or the subpage wildcard*/
6873 		if (page_index->subpage != subpage)
6874 			continue;
6875 
6876 		break;
6877 	}
6878 	if (i >= CTL_NUM_LOG_PAGES) {
6879 		ctl_set_invalid_field(ctsio,
6880 				      /*sks_valid*/ 1,
6881 				      /*command*/ 1,
6882 				      /*field*/ 2,
6883 				      /*bit_valid*/ 0,
6884 				      /*bit*/ 0);
6885 		ctl_done((union ctl_io *)ctsio);
6886 		return (CTL_RETVAL_COMPLETE);
6887 	}
6888 
6889 	total_len = sizeof(struct scsi_log_header) + page_index->page_len;
6890 
6891 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6892 	ctsio->kern_sg_entries = 0;
6893 	ctsio->kern_rel_offset = 0;
6894 	ctsio->kern_data_len = min(total_len, alloc_len);
6895 	ctsio->kern_total_len = ctsio->kern_data_len;
6896 
6897 	header = (struct scsi_log_header *)ctsio->kern_data_ptr;
6898 	header->page = page_index->page_code;
6899 	if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING)
6900 		header->page |= SL_DS;
6901 	if (page_index->subpage) {
6902 		header->page |= SL_SPF;
6903 		header->subpage = page_index->subpage;
6904 	}
6905 	scsi_ulto2b(page_index->page_len, header->datalen);
6906 
6907 	/*
6908 	 * Call the handler, if it exists, to update the
6909 	 * page to the latest values.
6910 	 */
6911 	if (page_index->sense_handler != NULL)
6912 		page_index->sense_handler(ctsio, page_index, pc);
6913 
6914 	memcpy(header + 1, page_index->page_data, page_index->page_len);
6915 
6916 	ctl_set_success(ctsio);
6917 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6918 	ctsio->be_move_done = ctl_config_move_done;
6919 	ctl_datamove((union ctl_io *)ctsio);
6920 	return (CTL_RETVAL_COMPLETE);
6921 }
6922 
6923 int
6924 ctl_read_capacity(struct ctl_scsiio *ctsio)
6925 {
6926 	struct ctl_lun *lun = CTL_LUN(ctsio);
6927 	struct scsi_read_capacity *cdb;
6928 	struct scsi_read_capacity_data *data;
6929 	uint32_t lba;
6930 
6931 	CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
6932 
6933 	cdb = (struct scsi_read_capacity *)ctsio->cdb;
6934 
6935 	lba = scsi_4btoul(cdb->addr);
6936 	if (((cdb->pmi & SRC_PMI) == 0)
6937 	 && (lba != 0)) {
6938 		ctl_set_invalid_field(/*ctsio*/ ctsio,
6939 				      /*sks_valid*/ 1,
6940 				      /*command*/ 1,
6941 				      /*field*/ 2,
6942 				      /*bit_valid*/ 0,
6943 				      /*bit*/ 0);
6944 		ctl_done((union ctl_io *)ctsio);
6945 		return (CTL_RETVAL_COMPLETE);
6946 	}
6947 
6948 	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
6949 	data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
6950 	ctsio->kern_data_len = sizeof(*data);
6951 	ctsio->kern_total_len = sizeof(*data);
6952 	ctsio->kern_rel_offset = 0;
6953 	ctsio->kern_sg_entries = 0;
6954 
6955 	/*
6956 	 * If the maximum LBA is greater than 0xfffffffe, the user must
6957 	 * issue a SERVICE ACTION IN (16) command, with the read capacity
6958 	 * serivce action set.
6959 	 */
6960 	if (lun->be_lun->maxlba > 0xfffffffe)
6961 		scsi_ulto4b(0xffffffff, data->addr);
6962 	else
6963 		scsi_ulto4b(lun->be_lun->maxlba, data->addr);
6964 
6965 	/*
6966 	 * XXX KDM this may not be 512 bytes...
6967 	 */
6968 	scsi_ulto4b(lun->be_lun->blocksize, data->length);
6969 
6970 	ctl_set_success(ctsio);
6971 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6972 	ctsio->be_move_done = ctl_config_move_done;
6973 	ctl_datamove((union ctl_io *)ctsio);
6974 	return (CTL_RETVAL_COMPLETE);
6975 }
6976 
6977 int
6978 ctl_read_capacity_16(struct ctl_scsiio *ctsio)
6979 {
6980 	struct ctl_lun *lun = CTL_LUN(ctsio);
6981 	struct scsi_read_capacity_16 *cdb;
6982 	struct scsi_read_capacity_data_long *data;
6983 	uint64_t lba;
6984 	uint32_t alloc_len;
6985 
6986 	CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
6987 
6988 	cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
6989 
6990 	alloc_len = scsi_4btoul(cdb->alloc_len);
6991 	lba = scsi_8btou64(cdb->addr);
6992 
6993 	if ((cdb->reladr & SRC16_PMI)
6994 	 && (lba != 0)) {
6995 		ctl_set_invalid_field(/*ctsio*/ ctsio,
6996 				      /*sks_valid*/ 1,
6997 				      /*command*/ 1,
6998 				      /*field*/ 2,
6999 				      /*bit_valid*/ 0,
7000 				      /*bit*/ 0);
7001 		ctl_done((union ctl_io *)ctsio);
7002 		return (CTL_RETVAL_COMPLETE);
7003 	}
7004 
7005 	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7006 	data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
7007 	ctsio->kern_rel_offset = 0;
7008 	ctsio->kern_sg_entries = 0;
7009 	ctsio->kern_data_len = min(sizeof(*data), alloc_len);
7010 	ctsio->kern_total_len = ctsio->kern_data_len;
7011 
7012 	scsi_u64to8b(lun->be_lun->maxlba, data->addr);
7013 	/* XXX KDM this may not be 512 bytes... */
7014 	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7015 	data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
7016 	scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
7017 	if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
7018 		data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
7019 
7020 	ctl_set_success(ctsio);
7021 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7022 	ctsio->be_move_done = ctl_config_move_done;
7023 	ctl_datamove((union ctl_io *)ctsio);
7024 	return (CTL_RETVAL_COMPLETE);
7025 }
7026 
7027 int
7028 ctl_get_lba_status(struct ctl_scsiio *ctsio)
7029 {
7030 	struct ctl_lun *lun = CTL_LUN(ctsio);
7031 	struct scsi_get_lba_status *cdb;
7032 	struct scsi_get_lba_status_data *data;
7033 	struct ctl_lba_len_flags *lbalen;
7034 	uint64_t lba;
7035 	uint32_t alloc_len, total_len;
7036 	int retval;
7037 
7038 	CTL_DEBUG_PRINT(("ctl_get_lba_status\n"));
7039 
7040 	cdb = (struct scsi_get_lba_status *)ctsio->cdb;
7041 	lba = scsi_8btou64(cdb->addr);
7042 	alloc_len = scsi_4btoul(cdb->alloc_len);
7043 
7044 	if (lba > lun->be_lun->maxlba) {
7045 		ctl_set_lba_out_of_range(ctsio, lba);
7046 		ctl_done((union ctl_io *)ctsio);
7047 		return (CTL_RETVAL_COMPLETE);
7048 	}
7049 
7050 	total_len = sizeof(*data) + sizeof(data->descr[0]);
7051 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7052 	data = (struct scsi_get_lba_status_data *)ctsio->kern_data_ptr;
7053 	ctsio->kern_rel_offset = 0;
7054 	ctsio->kern_sg_entries = 0;
7055 	ctsio->kern_data_len = min(total_len, alloc_len);
7056 	ctsio->kern_total_len = ctsio->kern_data_len;
7057 
7058 	/* Fill dummy data in case backend can't tell anything. */
7059 	scsi_ulto4b(4 + sizeof(data->descr[0]), data->length);
7060 	scsi_u64to8b(lba, data->descr[0].addr);
7061 	scsi_ulto4b(MIN(UINT32_MAX, lun->be_lun->maxlba + 1 - lba),
7062 	    data->descr[0].length);
7063 	data->descr[0].status = 0; /* Mapped or unknown. */
7064 
7065 	ctl_set_success(ctsio);
7066 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7067 	ctsio->be_move_done = ctl_config_move_done;
7068 
7069 	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
7070 	lbalen->lba = lba;
7071 	lbalen->len = total_len;
7072 	lbalen->flags = 0;
7073 	retval = lun->backend->config_read((union ctl_io *)ctsio);
7074 	return (retval);
7075 }
7076 
7077 int
7078 ctl_read_defect(struct ctl_scsiio *ctsio)
7079 {
7080 	struct scsi_read_defect_data_10 *ccb10;
7081 	struct scsi_read_defect_data_12 *ccb12;
7082 	struct scsi_read_defect_data_hdr_10 *data10;
7083 	struct scsi_read_defect_data_hdr_12 *data12;
7084 	uint32_t alloc_len, data_len;
7085 	uint8_t format;
7086 
7087 	CTL_DEBUG_PRINT(("ctl_read_defect\n"));
7088 
7089 	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7090 		ccb10 = (struct scsi_read_defect_data_10 *)&ctsio->cdb;
7091 		format = ccb10->format;
7092 		alloc_len = scsi_2btoul(ccb10->alloc_length);
7093 		data_len = sizeof(*data10);
7094 	} else {
7095 		ccb12 = (struct scsi_read_defect_data_12 *)&ctsio->cdb;
7096 		format = ccb12->format;
7097 		alloc_len = scsi_4btoul(ccb12->alloc_length);
7098 		data_len = sizeof(*data12);
7099 	}
7100 	if (alloc_len == 0) {
7101 		ctl_set_success(ctsio);
7102 		ctl_done((union ctl_io *)ctsio);
7103 		return (CTL_RETVAL_COMPLETE);
7104 	}
7105 
7106 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
7107 	ctsio->kern_rel_offset = 0;
7108 	ctsio->kern_sg_entries = 0;
7109 	ctsio->kern_data_len = min(data_len, alloc_len);
7110 	ctsio->kern_total_len = ctsio->kern_data_len;
7111 
7112 	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7113 		data10 = (struct scsi_read_defect_data_hdr_10 *)
7114 		    ctsio->kern_data_ptr;
7115 		data10->format = format;
7116 		scsi_ulto2b(0, data10->length);
7117 	} else {
7118 		data12 = (struct scsi_read_defect_data_hdr_12 *)
7119 		    ctsio->kern_data_ptr;
7120 		data12->format = format;
7121 		scsi_ulto2b(0, data12->generation);
7122 		scsi_ulto4b(0, data12->length);
7123 	}
7124 
7125 	ctl_set_success(ctsio);
7126 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7127 	ctsio->be_move_done = ctl_config_move_done;
7128 	ctl_datamove((union ctl_io *)ctsio);
7129 	return (CTL_RETVAL_COMPLETE);
7130 }
7131 
7132 int
7133 ctl_report_ident_info(struct ctl_scsiio *ctsio)
7134 {
7135 	struct ctl_lun *lun = CTL_LUN(ctsio);
7136 	struct scsi_report_ident_info *cdb;
7137 	struct scsi_report_ident_info_data *rii_ptr;
7138 	struct scsi_report_ident_info_descr *riid_ptr;
7139 	const char *oii, *otii;
7140 	int retval, alloc_len, total_len = 0, len = 0;
7141 
7142 	CTL_DEBUG_PRINT(("ctl_report_ident_info\n"));
7143 
7144 	cdb = (struct scsi_report_ident_info *)ctsio->cdb;
7145 	retval = CTL_RETVAL_COMPLETE;
7146 
7147 	total_len = sizeof(struct scsi_report_ident_info_data);
7148 	switch (cdb->type) {
7149 	case RII_LUII:
7150 		oii = dnvlist_get_string(lun->be_lun->options,
7151 		    "ident_info", NULL);
7152 		if (oii)
7153 			len = strlen(oii);	/* Approximately */
7154 		break;
7155 	case RII_LUTII:
7156 		otii = dnvlist_get_string(lun->be_lun->options,
7157 		    "text_ident_info", NULL);
7158 		if (otii)
7159 			len = strlen(otii) + 1;	/* NULL-terminated */
7160 		break;
7161 	case RII_IIS:
7162 		len = 2 * sizeof(struct scsi_report_ident_info_descr);
7163 		break;
7164 	default:
7165 		ctl_set_invalid_field(/*ctsio*/ ctsio,
7166 				      /*sks_valid*/ 1,
7167 				      /*command*/ 1,
7168 				      /*field*/ 11,
7169 				      /*bit_valid*/ 1,
7170 				      /*bit*/ 2);
7171 		ctl_done((union ctl_io *)ctsio);
7172 		return(retval);
7173 	}
7174 	total_len += len;
7175 	alloc_len = scsi_4btoul(cdb->length);
7176 
7177 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7178 	ctsio->kern_sg_entries = 0;
7179 	ctsio->kern_rel_offset = 0;
7180 	ctsio->kern_data_len = min(total_len, alloc_len);
7181 	ctsio->kern_total_len = ctsio->kern_data_len;
7182 
7183 	rii_ptr = (struct scsi_report_ident_info_data *)ctsio->kern_data_ptr;
7184 	switch (cdb->type) {
7185 	case RII_LUII:
7186 		if (oii) {
7187 			if (oii[0] == '0' && oii[1] == 'x')
7188 				len = hex2bin(oii, (uint8_t *)(rii_ptr + 1), len);
7189 			else
7190 				strncpy((uint8_t *)(rii_ptr + 1), oii, len);
7191 		}
7192 		break;
7193 	case RII_LUTII:
7194 		if (otii)
7195 			strlcpy((uint8_t *)(rii_ptr + 1), otii, len);
7196 		break;
7197 	case RII_IIS:
7198 		riid_ptr = (struct scsi_report_ident_info_descr *)(rii_ptr + 1);
7199 		riid_ptr->type = RII_LUII;
7200 		scsi_ulto2b(0xffff, riid_ptr->length);
7201 		riid_ptr++;
7202 		riid_ptr->type = RII_LUTII;
7203 		scsi_ulto2b(0xffff, riid_ptr->length);
7204 	}
7205 	scsi_ulto2b(len, rii_ptr->length);
7206 
7207 	ctl_set_success(ctsio);
7208 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7209 	ctsio->be_move_done = ctl_config_move_done;
7210 	ctl_datamove((union ctl_io *)ctsio);
7211 	return(retval);
7212 }
7213 
7214 int
7215 ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7216 {
7217 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
7218 	struct ctl_lun *lun = CTL_LUN(ctsio);
7219 	struct scsi_maintenance_in *cdb;
7220 	int retval;
7221 	int alloc_len, ext, total_len = 0, g, pc, pg, ts, os;
7222 	int num_ha_groups, num_target_ports, shared_group;
7223 	struct ctl_port *port;
7224 	struct scsi_target_group_data *rtg_ptr;
7225 	struct scsi_target_group_data_extended *rtg_ext_ptr;
7226 	struct scsi_target_port_group_descriptor *tpg_desc;
7227 
7228 	CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7229 
7230 	cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7231 	retval = CTL_RETVAL_COMPLETE;
7232 
7233 	switch (cdb->byte2 & STG_PDF_MASK) {
7234 	case STG_PDF_LENGTH:
7235 		ext = 0;
7236 		break;
7237 	case STG_PDF_EXTENDED:
7238 		ext = 1;
7239 		break;
7240 	default:
7241 		ctl_set_invalid_field(/*ctsio*/ ctsio,
7242 				      /*sks_valid*/ 1,
7243 				      /*command*/ 1,
7244 				      /*field*/ 2,
7245 				      /*bit_valid*/ 1,
7246 				      /*bit*/ 5);
7247 		ctl_done((union ctl_io *)ctsio);
7248 		return(retval);
7249 	}
7250 
7251 	num_target_ports = 0;
7252 	shared_group = (softc->is_single != 0);
7253 	mtx_lock(&softc->ctl_lock);
7254 	STAILQ_FOREACH(port, &softc->port_list, links) {
7255 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7256 			continue;
7257 		if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7258 			continue;
7259 		num_target_ports++;
7260 		if (port->status & CTL_PORT_STATUS_HA_SHARED)
7261 			shared_group = 1;
7262 	}
7263 	mtx_unlock(&softc->ctl_lock);
7264 	num_ha_groups = (softc->is_single) ? 0 : NUM_HA_SHELVES;
7265 
7266 	if (ext)
7267 		total_len = sizeof(struct scsi_target_group_data_extended);
7268 	else
7269 		total_len = sizeof(struct scsi_target_group_data);
7270 	total_len += sizeof(struct scsi_target_port_group_descriptor) *
7271 		(shared_group + num_ha_groups) +
7272 	    sizeof(struct scsi_target_port_descriptor) * num_target_ports;
7273 
7274 	alloc_len = scsi_4btoul(cdb->length);
7275 
7276 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7277 	ctsio->kern_sg_entries = 0;
7278 	ctsio->kern_rel_offset = 0;
7279 	ctsio->kern_data_len = min(total_len, alloc_len);
7280 	ctsio->kern_total_len = ctsio->kern_data_len;
7281 
7282 	if (ext) {
7283 		rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7284 		    ctsio->kern_data_ptr;
7285 		scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7286 		rtg_ext_ptr->format_type = 0x10;
7287 		rtg_ext_ptr->implicit_transition_time = 0;
7288 		tpg_desc = &rtg_ext_ptr->groups[0];
7289 	} else {
7290 		rtg_ptr = (struct scsi_target_group_data *)
7291 		    ctsio->kern_data_ptr;
7292 		scsi_ulto4b(total_len - 4, rtg_ptr->length);
7293 		tpg_desc = &rtg_ptr->groups[0];
7294 	}
7295 
7296 	mtx_lock(&softc->ctl_lock);
7297 	pg = softc->port_min / softc->port_cnt;
7298 	if (lun->flags & (CTL_LUN_PRIMARY_SC | CTL_LUN_PEER_SC_PRIMARY)) {
7299 		/* Some shelf is known to be primary. */
7300 		if (softc->ha_link == CTL_HA_LINK_OFFLINE)
7301 			os = TPG_ASYMMETRIC_ACCESS_UNAVAILABLE;
7302 		else if (softc->ha_link == CTL_HA_LINK_UNKNOWN)
7303 			os = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7304 		else if (softc->ha_mode == CTL_HA_MODE_ACT_STBY)
7305 			os = TPG_ASYMMETRIC_ACCESS_STANDBY;
7306 		else
7307 			os = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7308 		if (lun->flags & CTL_LUN_PRIMARY_SC) {
7309 			ts = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7310 		} else {
7311 			ts = os;
7312 			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7313 		}
7314 	} else {
7315 		/* No known primary shelf. */
7316 		if (softc->ha_link == CTL_HA_LINK_OFFLINE) {
7317 			ts = TPG_ASYMMETRIC_ACCESS_UNAVAILABLE;
7318 			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7319 		} else if (softc->ha_link == CTL_HA_LINK_UNKNOWN) {
7320 			ts = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7321 			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7322 		} else {
7323 			ts = os = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7324 		}
7325 	}
7326 	if (shared_group) {
7327 		tpg_desc->pref_state = ts;
7328 		tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP |
7329 		    TPG_U_SUP | TPG_T_SUP;
7330 		scsi_ulto2b(1, tpg_desc->target_port_group);
7331 		tpg_desc->status = TPG_IMPLICIT;
7332 		pc = 0;
7333 		STAILQ_FOREACH(port, &softc->port_list, links) {
7334 			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7335 				continue;
7336 			if (!softc->is_single &&
7337 			    (port->status & CTL_PORT_STATUS_HA_SHARED) == 0)
7338 				continue;
7339 			if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7340 				continue;
7341 			scsi_ulto2b(port->targ_port, tpg_desc->descriptors[pc].
7342 			    relative_target_port_identifier);
7343 			pc++;
7344 		}
7345 		tpg_desc->target_port_count = pc;
7346 		tpg_desc = (struct scsi_target_port_group_descriptor *)
7347 		    &tpg_desc->descriptors[pc];
7348 	}
7349 	for (g = 0; g < num_ha_groups; g++) {
7350 		tpg_desc->pref_state = (g == pg) ? ts : os;
7351 		tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP |
7352 		    TPG_U_SUP | TPG_T_SUP;
7353 		scsi_ulto2b(2 + g, tpg_desc->target_port_group);
7354 		tpg_desc->status = TPG_IMPLICIT;
7355 		pc = 0;
7356 		STAILQ_FOREACH(port, &softc->port_list, links) {
7357 			if (port->targ_port < g * softc->port_cnt ||
7358 			    port->targ_port >= (g + 1) * softc->port_cnt)
7359 				continue;
7360 			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7361 				continue;
7362 			if (port->status & CTL_PORT_STATUS_HA_SHARED)
7363 				continue;
7364 			if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7365 				continue;
7366 			scsi_ulto2b(port->targ_port, tpg_desc->descriptors[pc].
7367 			    relative_target_port_identifier);
7368 			pc++;
7369 		}
7370 		tpg_desc->target_port_count = pc;
7371 		tpg_desc = (struct scsi_target_port_group_descriptor *)
7372 		    &tpg_desc->descriptors[pc];
7373 	}
7374 	mtx_unlock(&softc->ctl_lock);
7375 
7376 	ctl_set_success(ctsio);
7377 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7378 	ctsio->be_move_done = ctl_config_move_done;
7379 	ctl_datamove((union ctl_io *)ctsio);
7380 	return(retval);
7381 }
7382 
7383 int
7384 ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7385 {
7386 	struct ctl_lun *lun = CTL_LUN(ctsio);
7387 	struct scsi_report_supported_opcodes *cdb;
7388 	const struct ctl_cmd_entry *entry, *sentry;
7389 	struct scsi_report_supported_opcodes_all *all;
7390 	struct scsi_report_supported_opcodes_descr *descr;
7391 	struct scsi_report_supported_opcodes_one *one;
7392 	int retval;
7393 	int alloc_len, total_len;
7394 	int opcode, service_action, i, j, num;
7395 
7396 	CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7397 
7398 	cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7399 	retval = CTL_RETVAL_COMPLETE;
7400 
7401 	opcode = cdb->requested_opcode;
7402 	service_action = scsi_2btoul(cdb->requested_service_action);
7403 	switch (cdb->options & RSO_OPTIONS_MASK) {
7404 	case RSO_OPTIONS_ALL:
7405 		num = 0;
7406 		for (i = 0; i < 256; i++) {
7407 			entry = &ctl_cmd_table[i];
7408 			if (entry->flags & CTL_CMD_FLAG_SA5) {
7409 				for (j = 0; j < 32; j++) {
7410 					sentry = &((const struct ctl_cmd_entry *)
7411 					    entry->execute)[j];
7412 					if (ctl_cmd_applicable(
7413 					    lun->be_lun->lun_type, sentry))
7414 						num++;
7415 				}
7416 			} else {
7417 				if (ctl_cmd_applicable(lun->be_lun->lun_type,
7418 				    entry))
7419 					num++;
7420 			}
7421 		}
7422 		total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7423 		    num * sizeof(struct scsi_report_supported_opcodes_descr);
7424 		break;
7425 	case RSO_OPTIONS_OC:
7426 		if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7427 			ctl_set_invalid_field(/*ctsio*/ ctsio,
7428 					      /*sks_valid*/ 1,
7429 					      /*command*/ 1,
7430 					      /*field*/ 2,
7431 					      /*bit_valid*/ 1,
7432 					      /*bit*/ 2);
7433 			ctl_done((union ctl_io *)ctsio);
7434 			return (CTL_RETVAL_COMPLETE);
7435 		}
7436 		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7437 		break;
7438 	case RSO_OPTIONS_OC_SA:
7439 		if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7440 		    service_action >= 32) {
7441 			ctl_set_invalid_field(/*ctsio*/ ctsio,
7442 					      /*sks_valid*/ 1,
7443 					      /*command*/ 1,
7444 					      /*field*/ 2,
7445 					      /*bit_valid*/ 1,
7446 					      /*bit*/ 2);
7447 			ctl_done((union ctl_io *)ctsio);
7448 			return (CTL_RETVAL_COMPLETE);
7449 		}
7450 		/* FALLTHROUGH */
7451 	case RSO_OPTIONS_OC_ASA:
7452 		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7453 		break;
7454 	default:
7455 		ctl_set_invalid_field(/*ctsio*/ ctsio,
7456 				      /*sks_valid*/ 1,
7457 				      /*command*/ 1,
7458 				      /*field*/ 2,
7459 				      /*bit_valid*/ 1,
7460 				      /*bit*/ 2);
7461 		ctl_done((union ctl_io *)ctsio);
7462 		return (CTL_RETVAL_COMPLETE);
7463 	}
7464 
7465 	alloc_len = scsi_4btoul(cdb->length);
7466 
7467 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7468 	ctsio->kern_sg_entries = 0;
7469 	ctsio->kern_rel_offset = 0;
7470 	ctsio->kern_data_len = min(total_len, alloc_len);
7471 	ctsio->kern_total_len = ctsio->kern_data_len;
7472 
7473 	switch (cdb->options & RSO_OPTIONS_MASK) {
7474 	case RSO_OPTIONS_ALL:
7475 		all = (struct scsi_report_supported_opcodes_all *)
7476 		    ctsio->kern_data_ptr;
7477 		num = 0;
7478 		for (i = 0; i < 256; i++) {
7479 			entry = &ctl_cmd_table[i];
7480 			if (entry->flags & CTL_CMD_FLAG_SA5) {
7481 				for (j = 0; j < 32; j++) {
7482 					sentry = &((const struct ctl_cmd_entry *)
7483 					    entry->execute)[j];
7484 					if (!ctl_cmd_applicable(
7485 					    lun->be_lun->lun_type, sentry))
7486 						continue;
7487 					descr = &all->descr[num++];
7488 					descr->opcode = i;
7489 					scsi_ulto2b(j, descr->service_action);
7490 					descr->flags = RSO_SERVACTV;
7491 					scsi_ulto2b(sentry->length,
7492 					    descr->cdb_length);
7493 				}
7494 			} else {
7495 				if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7496 				    entry))
7497 					continue;
7498 				descr = &all->descr[num++];
7499 				descr->opcode = i;
7500 				scsi_ulto2b(0, descr->service_action);
7501 				descr->flags = 0;
7502 				scsi_ulto2b(entry->length, descr->cdb_length);
7503 			}
7504 		}
7505 		scsi_ulto4b(
7506 		    num * sizeof(struct scsi_report_supported_opcodes_descr),
7507 		    all->length);
7508 		break;
7509 	case RSO_OPTIONS_OC:
7510 		one = (struct scsi_report_supported_opcodes_one *)
7511 		    ctsio->kern_data_ptr;
7512 		entry = &ctl_cmd_table[opcode];
7513 		goto fill_one;
7514 	case RSO_OPTIONS_OC_SA:
7515 		one = (struct scsi_report_supported_opcodes_one *)
7516 		    ctsio->kern_data_ptr;
7517 		entry = &ctl_cmd_table[opcode];
7518 		entry = &((const struct ctl_cmd_entry *)
7519 		    entry->execute)[service_action];
7520 fill_one:
7521 		if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7522 			one->support = 3;
7523 			scsi_ulto2b(entry->length, one->cdb_length);
7524 			one->cdb_usage[0] = opcode;
7525 			memcpy(&one->cdb_usage[1], entry->usage,
7526 			    entry->length - 1);
7527 		} else
7528 			one->support = 1;
7529 		break;
7530 	case RSO_OPTIONS_OC_ASA:
7531 		one = (struct scsi_report_supported_opcodes_one *)
7532 		    ctsio->kern_data_ptr;
7533 		entry = &ctl_cmd_table[opcode];
7534 		if (entry->flags & CTL_CMD_FLAG_SA5) {
7535 			entry = &((const struct ctl_cmd_entry *)
7536 			    entry->execute)[service_action];
7537 		} else if (service_action != 0) {
7538 			one->support = 1;
7539 			break;
7540 		}
7541 		goto fill_one;
7542 	}
7543 
7544 	ctl_set_success(ctsio);
7545 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7546 	ctsio->be_move_done = ctl_config_move_done;
7547 	ctl_datamove((union ctl_io *)ctsio);
7548 	return(retval);
7549 }
7550 
7551 int
7552 ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7553 {
7554 	struct scsi_report_supported_tmf *cdb;
7555 	struct scsi_report_supported_tmf_ext_data *data;
7556 	int retval;
7557 	int alloc_len, total_len;
7558 
7559 	CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7560 
7561 	cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7562 
7563 	retval = CTL_RETVAL_COMPLETE;
7564 
7565 	if (cdb->options & RST_REPD)
7566 		total_len = sizeof(struct scsi_report_supported_tmf_ext_data);
7567 	else
7568 		total_len = sizeof(struct scsi_report_supported_tmf_data);
7569 	alloc_len = scsi_4btoul(cdb->length);
7570 
7571 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7572 	ctsio->kern_sg_entries = 0;
7573 	ctsio->kern_rel_offset = 0;
7574 	ctsio->kern_data_len = min(total_len, alloc_len);
7575 	ctsio->kern_total_len = ctsio->kern_data_len;
7576 
7577 	data = (struct scsi_report_supported_tmf_ext_data *)ctsio->kern_data_ptr;
7578 	data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_QTS |
7579 	    RST_TRS;
7580 	data->byte2 |= RST_QAES | RST_QTSS | RST_ITNRS;
7581 	data->length = total_len - 4;
7582 
7583 	ctl_set_success(ctsio);
7584 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7585 	ctsio->be_move_done = ctl_config_move_done;
7586 	ctl_datamove((union ctl_io *)ctsio);
7587 	return (retval);
7588 }
7589 
7590 int
7591 ctl_report_timestamp(struct ctl_scsiio *ctsio)
7592 {
7593 	struct scsi_report_timestamp *cdb;
7594 	struct scsi_report_timestamp_data *data;
7595 	struct timeval tv;
7596 	int64_t timestamp;
7597 	int retval;
7598 	int alloc_len, total_len;
7599 
7600 	CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7601 
7602 	cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7603 
7604 	retval = CTL_RETVAL_COMPLETE;
7605 
7606 	total_len = sizeof(struct scsi_report_timestamp_data);
7607 	alloc_len = scsi_4btoul(cdb->length);
7608 
7609 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7610 	ctsio->kern_sg_entries = 0;
7611 	ctsio->kern_rel_offset = 0;
7612 	ctsio->kern_data_len = min(total_len, alloc_len);
7613 	ctsio->kern_total_len = ctsio->kern_data_len;
7614 
7615 	data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7616 	scsi_ulto2b(sizeof(*data) - 2, data->length);
7617 	data->origin = RTS_ORIG_OUTSIDE;
7618 	getmicrotime(&tv);
7619 	timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7620 	scsi_ulto4b(timestamp >> 16, data->timestamp);
7621 	scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7622 
7623 	ctl_set_success(ctsio);
7624 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7625 	ctsio->be_move_done = ctl_config_move_done;
7626 	ctl_datamove((union ctl_io *)ctsio);
7627 	return (retval);
7628 }
7629 
7630 int
7631 ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7632 {
7633 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
7634 	struct ctl_lun *lun = CTL_LUN(ctsio);
7635 	struct scsi_per_res_in *cdb;
7636 	int alloc_len, total_len = 0;
7637 	/* struct scsi_per_res_in_rsrv in_data; */
7638 	uint64_t key;
7639 
7640 	CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7641 
7642 	cdb = (struct scsi_per_res_in *)ctsio->cdb;
7643 
7644 	alloc_len = scsi_2btoul(cdb->length);
7645 
7646 retry:
7647 	mtx_lock(&lun->lun_lock);
7648 	switch (cdb->action) {
7649 	case SPRI_RK: /* read keys */
7650 		total_len = sizeof(struct scsi_per_res_in_keys) +
7651 			lun->pr_key_count *
7652 			sizeof(struct scsi_per_res_key);
7653 		break;
7654 	case SPRI_RR: /* read reservation */
7655 		if (lun->flags & CTL_LUN_PR_RESERVED)
7656 			total_len = sizeof(struct scsi_per_res_in_rsrv);
7657 		else
7658 			total_len = sizeof(struct scsi_per_res_in_header);
7659 		break;
7660 	case SPRI_RC: /* report capabilities */
7661 		total_len = sizeof(struct scsi_per_res_cap);
7662 		break;
7663 	case SPRI_RS: /* read full status */
7664 		total_len = sizeof(struct scsi_per_res_in_header) +
7665 		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7666 		    lun->pr_key_count;
7667 		break;
7668 	default:
7669 		panic("%s: Invalid PR type %#x", __func__, cdb->action);
7670 	}
7671 	mtx_unlock(&lun->lun_lock);
7672 
7673 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7674 	ctsio->kern_rel_offset = 0;
7675 	ctsio->kern_sg_entries = 0;
7676 	ctsio->kern_data_len = min(total_len, alloc_len);
7677 	ctsio->kern_total_len = ctsio->kern_data_len;
7678 
7679 	mtx_lock(&lun->lun_lock);
7680 	switch (cdb->action) {
7681 	case SPRI_RK: { // read keys
7682         struct scsi_per_res_in_keys *res_keys;
7683 		int i, key_count;
7684 
7685 		res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7686 
7687 		/*
7688 		 * We had to drop the lock to allocate our buffer, which
7689 		 * leaves time for someone to come in with another
7690 		 * persistent reservation.  (That is unlikely, though,
7691 		 * since this should be the only persistent reservation
7692 		 * command active right now.)
7693 		 */
7694 		if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7695 		    (lun->pr_key_count *
7696 		     sizeof(struct scsi_per_res_key)))){
7697 			mtx_unlock(&lun->lun_lock);
7698 			free(ctsio->kern_data_ptr, M_CTL);
7699 			printf("%s: reservation length changed, retrying\n",
7700 			       __func__);
7701 			goto retry;
7702 		}
7703 
7704 		scsi_ulto4b(lun->pr_generation, res_keys->header.generation);
7705 
7706 		scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7707 			     lun->pr_key_count, res_keys->header.length);
7708 
7709 		for (i = 0, key_count = 0; i < CTL_MAX_INITIATORS; i++) {
7710 			if ((key = ctl_get_prkey(lun, i)) == 0)
7711 				continue;
7712 
7713 			/*
7714 			 * We used lun->pr_key_count to calculate the
7715 			 * size to allocate.  If it turns out the number of
7716 			 * initiators with the registered flag set is
7717 			 * larger than that (i.e. they haven't been kept in
7718 			 * sync), we've got a problem.
7719 			 */
7720 			if (key_count >= lun->pr_key_count) {
7721 				key_count++;
7722 				continue;
7723 			}
7724 			scsi_u64to8b(key, res_keys->keys[key_count].key);
7725 			key_count++;
7726 		}
7727 		break;
7728 	}
7729 	case SPRI_RR: { // read reservation
7730 		struct scsi_per_res_in_rsrv *res;
7731 		int tmp_len, header_only;
7732 
7733 		res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7734 
7735 		scsi_ulto4b(lun->pr_generation, res->header.generation);
7736 
7737 		if (lun->flags & CTL_LUN_PR_RESERVED)
7738 		{
7739 			tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7740 			scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7741 				    res->header.length);
7742 			header_only = 0;
7743 		} else {
7744 			tmp_len = sizeof(struct scsi_per_res_in_header);
7745 			scsi_ulto4b(0, res->header.length);
7746 			header_only = 1;
7747 		}
7748 
7749 		/*
7750 		 * We had to drop the lock to allocate our buffer, which
7751 		 * leaves time for someone to come in with another
7752 		 * persistent reservation.  (That is unlikely, though,
7753 		 * since this should be the only persistent reservation
7754 		 * command active right now.)
7755 		 */
7756 		if (tmp_len != total_len) {
7757 			mtx_unlock(&lun->lun_lock);
7758 			free(ctsio->kern_data_ptr, M_CTL);
7759 			printf("%s: reservation status changed, retrying\n",
7760 			       __func__);
7761 			goto retry;
7762 		}
7763 
7764 		/*
7765 		 * No reservation held, so we're done.
7766 		 */
7767 		if (header_only != 0)
7768 			break;
7769 
7770 		/*
7771 		 * If the registration is an All Registrants type, the key
7772 		 * is 0, since it doesn't really matter.
7773 		 */
7774 		if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7775 			scsi_u64to8b(ctl_get_prkey(lun, lun->pr_res_idx),
7776 			    res->data.reservation);
7777 		}
7778 		res->data.scopetype = lun->pr_res_type;
7779 		break;
7780 	}
7781 	case SPRI_RC:     //report capabilities
7782 	{
7783 		struct scsi_per_res_cap *res_cap;
7784 		uint16_t type_mask;
7785 
7786 		res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7787 		scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7788 		res_cap->flags1 = SPRI_CRH;
7789 		res_cap->flags2 = SPRI_TMV | SPRI_ALLOW_5;
7790 		type_mask = SPRI_TM_WR_EX_AR |
7791 			    SPRI_TM_EX_AC_RO |
7792 			    SPRI_TM_WR_EX_RO |
7793 			    SPRI_TM_EX_AC |
7794 			    SPRI_TM_WR_EX |
7795 			    SPRI_TM_EX_AC_AR;
7796 		scsi_ulto2b(type_mask, res_cap->type_mask);
7797 		break;
7798 	}
7799 	case SPRI_RS: { // read full status
7800 		struct scsi_per_res_in_full *res_status;
7801 		struct scsi_per_res_in_full_desc *res_desc;
7802 		struct ctl_port *port;
7803 		int i, len;
7804 
7805 		res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7806 
7807 		/*
7808 		 * We had to drop the lock to allocate our buffer, which
7809 		 * leaves time for someone to come in with another
7810 		 * persistent reservation.  (That is unlikely, though,
7811 		 * since this should be the only persistent reservation
7812 		 * command active right now.)
7813 		 */
7814 		if (total_len < (sizeof(struct scsi_per_res_in_header) +
7815 		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7816 		     lun->pr_key_count)){
7817 			mtx_unlock(&lun->lun_lock);
7818 			free(ctsio->kern_data_ptr, M_CTL);
7819 			printf("%s: reservation length changed, retrying\n",
7820 			       __func__);
7821 			goto retry;
7822 		}
7823 
7824 		scsi_ulto4b(lun->pr_generation, res_status->header.generation);
7825 
7826 		res_desc = &res_status->desc[0];
7827 		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7828 			if ((key = ctl_get_prkey(lun, i)) == 0)
7829 				continue;
7830 
7831 			scsi_u64to8b(key, res_desc->res_key.key);
7832 			if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7833 			    (lun->pr_res_idx == i ||
7834 			     lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7835 				res_desc->flags = SPRI_FULL_R_HOLDER;
7836 				res_desc->scopetype = lun->pr_res_type;
7837 			}
7838 			scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7839 			    res_desc->rel_trgt_port_id);
7840 			len = 0;
7841 			port = softc->ctl_ports[i / CTL_MAX_INIT_PER_PORT];
7842 			if (port != NULL)
7843 				len = ctl_create_iid(port,
7844 				    i % CTL_MAX_INIT_PER_PORT,
7845 				    res_desc->transport_id);
7846 			scsi_ulto4b(len, res_desc->additional_length);
7847 			res_desc = (struct scsi_per_res_in_full_desc *)
7848 			    &res_desc->transport_id[len];
7849 		}
7850 		scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7851 		    res_status->header.length);
7852 		break;
7853 	}
7854 	default:
7855 		panic("%s: Invalid PR type %#x", __func__, cdb->action);
7856 	}
7857 	mtx_unlock(&lun->lun_lock);
7858 
7859 	ctl_set_success(ctsio);
7860 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7861 	ctsio->be_move_done = ctl_config_move_done;
7862 	ctl_datamove((union ctl_io *)ctsio);
7863 	return (CTL_RETVAL_COMPLETE);
7864 }
7865 
7866 /*
7867  * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
7868  * it should return.
7869  */
7870 static int
7871 ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
7872 		uint64_t sa_res_key, uint8_t type, uint32_t residx,
7873 		struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
7874 		struct scsi_per_res_out_parms* param)
7875 {
7876 	union ctl_ha_msg persis_io;
7877 	int i;
7878 
7879 	mtx_lock(&lun->lun_lock);
7880 	if (sa_res_key == 0) {
7881 		if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
7882 			/* validate scope and type */
7883 			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7884 			     SPR_LU_SCOPE) {
7885 				mtx_unlock(&lun->lun_lock);
7886 				ctl_set_invalid_field(/*ctsio*/ ctsio,
7887 						      /*sks_valid*/ 1,
7888 						      /*command*/ 1,
7889 						      /*field*/ 2,
7890 						      /*bit_valid*/ 1,
7891 						      /*bit*/ 4);
7892 				ctl_done((union ctl_io *)ctsio);
7893 				return (1);
7894 			}
7895 
7896 		        if (type>8 || type==2 || type==4 || type==0) {
7897 				mtx_unlock(&lun->lun_lock);
7898 				ctl_set_invalid_field(/*ctsio*/ ctsio,
7899        	           				      /*sks_valid*/ 1,
7900 						      /*command*/ 1,
7901 						      /*field*/ 2,
7902 						      /*bit_valid*/ 1,
7903 						      /*bit*/ 0);
7904 				ctl_done((union ctl_io *)ctsio);
7905 				return (1);
7906 		        }
7907 
7908 			/*
7909 			 * Unregister everybody else and build UA for
7910 			 * them
7911 			 */
7912 			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
7913 				if (i == residx || ctl_get_prkey(lun, i) == 0)
7914 					continue;
7915 
7916 				ctl_clr_prkey(lun, i);
7917 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7918 			}
7919 			lun->pr_key_count = 1;
7920 			lun->pr_res_type = type;
7921 			if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
7922 			    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
7923 				lun->pr_res_idx = residx;
7924 			lun->pr_generation++;
7925 			mtx_unlock(&lun->lun_lock);
7926 
7927 			/* send msg to other side */
7928 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7929 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7930 			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7931 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
7932 			persis_io.pr.pr_info.res_type = type;
7933 			memcpy(persis_io.pr.pr_info.sa_res_key,
7934 			       param->serv_act_res_key,
7935 			       sizeof(param->serv_act_res_key));
7936 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7937 			    sizeof(persis_io.pr), M_WAITOK);
7938 		} else {
7939 			/* not all registrants */
7940 			mtx_unlock(&lun->lun_lock);
7941 			free(ctsio->kern_data_ptr, M_CTL);
7942 			ctl_set_invalid_field(ctsio,
7943 					      /*sks_valid*/ 1,
7944 					      /*command*/ 0,
7945 					      /*field*/ 8,
7946 					      /*bit_valid*/ 0,
7947 					      /*bit*/ 0);
7948 			ctl_done((union ctl_io *)ctsio);
7949 			return (1);
7950 		}
7951 	} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
7952 		|| !(lun->flags & CTL_LUN_PR_RESERVED)) {
7953 		int found = 0;
7954 
7955 		if (res_key == sa_res_key) {
7956 			/* special case */
7957 			/*
7958 			 * The spec implies this is not good but doesn't
7959 			 * say what to do. There are two choices either
7960 			 * generate a res conflict or check condition
7961 			 * with illegal field in parameter data. Since
7962 			 * that is what is done when the sa_res_key is
7963 			 * zero I'll take that approach since this has
7964 			 * to do with the sa_res_key.
7965 			 */
7966 			mtx_unlock(&lun->lun_lock);
7967 			free(ctsio->kern_data_ptr, M_CTL);
7968 			ctl_set_invalid_field(ctsio,
7969 					      /*sks_valid*/ 1,
7970 					      /*command*/ 0,
7971 					      /*field*/ 8,
7972 					      /*bit_valid*/ 0,
7973 					      /*bit*/ 0);
7974 			ctl_done((union ctl_io *)ctsio);
7975 			return (1);
7976 		}
7977 
7978 		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7979 			if (ctl_get_prkey(lun, i) != sa_res_key)
7980 				continue;
7981 
7982 			found = 1;
7983 			ctl_clr_prkey(lun, i);
7984 			lun->pr_key_count--;
7985 			ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7986 		}
7987 		if (!found) {
7988 			mtx_unlock(&lun->lun_lock);
7989 			free(ctsio->kern_data_ptr, M_CTL);
7990 			ctl_set_reservation_conflict(ctsio);
7991 			ctl_done((union ctl_io *)ctsio);
7992 			return (CTL_RETVAL_COMPLETE);
7993 		}
7994 		lun->pr_generation++;
7995 		mtx_unlock(&lun->lun_lock);
7996 
7997 		/* send msg to other side */
7998 		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7999 		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8000 		persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8001 		persis_io.pr.pr_info.residx = lun->pr_res_idx;
8002 		persis_io.pr.pr_info.res_type = type;
8003 		memcpy(persis_io.pr.pr_info.sa_res_key,
8004 		       param->serv_act_res_key,
8005 		       sizeof(param->serv_act_res_key));
8006 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8007 		    sizeof(persis_io.pr), M_WAITOK);
8008 	} else {
8009 		/* Reserved but not all registrants */
8010 		/* sa_res_key is res holder */
8011 		if (sa_res_key == ctl_get_prkey(lun, lun->pr_res_idx)) {
8012 			/* validate scope and type */
8013 			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8014 			     SPR_LU_SCOPE) {
8015 				mtx_unlock(&lun->lun_lock);
8016 				ctl_set_invalid_field(/*ctsio*/ ctsio,
8017 						      /*sks_valid*/ 1,
8018 						      /*command*/ 1,
8019 						      /*field*/ 2,
8020 						      /*bit_valid*/ 1,
8021 						      /*bit*/ 4);
8022 				ctl_done((union ctl_io *)ctsio);
8023 				return (1);
8024 			}
8025 
8026 			if (type>8 || type==2 || type==4 || type==0) {
8027 				mtx_unlock(&lun->lun_lock);
8028 				ctl_set_invalid_field(/*ctsio*/ ctsio,
8029 						      /*sks_valid*/ 1,
8030 						      /*command*/ 1,
8031 						      /*field*/ 2,
8032 						      /*bit_valid*/ 1,
8033 						      /*bit*/ 0);
8034 				ctl_done((union ctl_io *)ctsio);
8035 				return (1);
8036 			}
8037 
8038 			/*
8039 			 * Do the following:
8040 			 * if sa_res_key != res_key remove all
8041 			 * registrants w/sa_res_key and generate UA
8042 			 * for these registrants(Registrations
8043 			 * Preempted) if it wasn't an exclusive
8044 			 * reservation generate UA(Reservations
8045 			 * Preempted) for all other registered nexuses
8046 			 * if the type has changed. Establish the new
8047 			 * reservation and holder. If res_key and
8048 			 * sa_res_key are the same do the above
8049 			 * except don't unregister the res holder.
8050 			 */
8051 
8052 			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
8053 				if (i == residx || ctl_get_prkey(lun, i) == 0)
8054 					continue;
8055 
8056 				if (sa_res_key == ctl_get_prkey(lun, i)) {
8057 					ctl_clr_prkey(lun, i);
8058 					lun->pr_key_count--;
8059 					ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8060 				} else if (type != lun->pr_res_type &&
8061 				    (lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8062 				     lun->pr_res_type == SPR_TYPE_EX_AC_RO)) {
8063 					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8064 				}
8065 			}
8066 			lun->pr_res_type = type;
8067 			if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8068 			    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8069 				lun->pr_res_idx = residx;
8070 			else
8071 				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8072 			lun->pr_generation++;
8073 			mtx_unlock(&lun->lun_lock);
8074 
8075 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8076 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8077 			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8078 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8079 			persis_io.pr.pr_info.res_type = type;
8080 			memcpy(persis_io.pr.pr_info.sa_res_key,
8081 			       param->serv_act_res_key,
8082 			       sizeof(param->serv_act_res_key));
8083 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8084 			    sizeof(persis_io.pr), M_WAITOK);
8085 		} else {
8086 			/*
8087 			 * sa_res_key is not the res holder just
8088 			 * remove registrants
8089 			 */
8090 			int found=0;
8091 
8092 			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8093 				if (sa_res_key != ctl_get_prkey(lun, i))
8094 					continue;
8095 
8096 				found = 1;
8097 				ctl_clr_prkey(lun, i);
8098 				lun->pr_key_count--;
8099 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8100 			}
8101 
8102 			if (!found) {
8103 				mtx_unlock(&lun->lun_lock);
8104 				free(ctsio->kern_data_ptr, M_CTL);
8105 				ctl_set_reservation_conflict(ctsio);
8106 				ctl_done((union ctl_io *)ctsio);
8107 		        	return (1);
8108 			}
8109 			lun->pr_generation++;
8110 			mtx_unlock(&lun->lun_lock);
8111 
8112 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8113 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8114 			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8115 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8116 			persis_io.pr.pr_info.res_type = type;
8117 			memcpy(persis_io.pr.pr_info.sa_res_key,
8118 			       param->serv_act_res_key,
8119 			       sizeof(param->serv_act_res_key));
8120 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8121 			    sizeof(persis_io.pr), M_WAITOK);
8122 		}
8123 	}
8124 	return (0);
8125 }
8126 
8127 static void
8128 ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8129 {
8130 	uint64_t sa_res_key;
8131 	int i;
8132 
8133 	sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8134 
8135 	if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8136 	 || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8137 	 || sa_res_key != ctl_get_prkey(lun, lun->pr_res_idx)) {
8138 		if (sa_res_key == 0) {
8139 			/*
8140 			 * Unregister everybody else and build UA for
8141 			 * them
8142 			 */
8143 			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
8144 				if (i == msg->pr.pr_info.residx ||
8145 				    ctl_get_prkey(lun, i) == 0)
8146 					continue;
8147 
8148 				ctl_clr_prkey(lun, i);
8149 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8150 			}
8151 
8152 			lun->pr_key_count = 1;
8153 			lun->pr_res_type = msg->pr.pr_info.res_type;
8154 			if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8155 			    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8156 				lun->pr_res_idx = msg->pr.pr_info.residx;
8157 		} else {
8158 		        for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8159 				if (sa_res_key == ctl_get_prkey(lun, i))
8160 					continue;
8161 
8162 				ctl_clr_prkey(lun, i);
8163 				lun->pr_key_count--;
8164 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8165 			}
8166 		}
8167 	} else {
8168 		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8169 			if (i == msg->pr.pr_info.residx ||
8170 			    ctl_get_prkey(lun, i) == 0)
8171 				continue;
8172 
8173 			if (sa_res_key == ctl_get_prkey(lun, i)) {
8174 				ctl_clr_prkey(lun, i);
8175 				lun->pr_key_count--;
8176 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8177 			} else if (msg->pr.pr_info.res_type != lun->pr_res_type
8178 			    && (lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8179 			     lun->pr_res_type == SPR_TYPE_EX_AC_RO)) {
8180 				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8181 			}
8182 		}
8183 		lun->pr_res_type = msg->pr.pr_info.res_type;
8184 		if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8185 		    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8186 			lun->pr_res_idx = msg->pr.pr_info.residx;
8187 		else
8188 			lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8189 	}
8190 	lun->pr_generation++;
8191 
8192 }
8193 
8194 
8195 int
8196 ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8197 {
8198 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
8199 	struct ctl_lun *lun = CTL_LUN(ctsio);
8200 	int retval;
8201 	u_int32_t param_len;
8202 	struct scsi_per_res_out *cdb;
8203 	struct scsi_per_res_out_parms* param;
8204 	uint32_t residx;
8205 	uint64_t res_key, sa_res_key, key;
8206 	uint8_t type;
8207 	union ctl_ha_msg persis_io;
8208 	int    i;
8209 
8210 	CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8211 
8212 	cdb = (struct scsi_per_res_out *)ctsio->cdb;
8213 	retval = CTL_RETVAL_COMPLETE;
8214 
8215 	/*
8216 	 * We only support whole-LUN scope.  The scope & type are ignored for
8217 	 * register, register and ignore existing key and clear.
8218 	 * We sometimes ignore scope and type on preempts too!!
8219 	 * Verify reservation type here as well.
8220 	 */
8221 	type = cdb->scope_type & SPR_TYPE_MASK;
8222 	if ((cdb->action == SPRO_RESERVE)
8223 	 || (cdb->action == SPRO_RELEASE)) {
8224 		if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8225 			ctl_set_invalid_field(/*ctsio*/ ctsio,
8226 					      /*sks_valid*/ 1,
8227 					      /*command*/ 1,
8228 					      /*field*/ 2,
8229 					      /*bit_valid*/ 1,
8230 					      /*bit*/ 4);
8231 			ctl_done((union ctl_io *)ctsio);
8232 			return (CTL_RETVAL_COMPLETE);
8233 		}
8234 
8235 		if (type>8 || type==2 || type==4 || type==0) {
8236 			ctl_set_invalid_field(/*ctsio*/ ctsio,
8237 					      /*sks_valid*/ 1,
8238 					      /*command*/ 1,
8239 					      /*field*/ 2,
8240 					      /*bit_valid*/ 1,
8241 					      /*bit*/ 0);
8242 			ctl_done((union ctl_io *)ctsio);
8243 			return (CTL_RETVAL_COMPLETE);
8244 		}
8245 	}
8246 
8247 	param_len = scsi_4btoul(cdb->length);
8248 
8249 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8250 		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8251 		ctsio->kern_data_len = param_len;
8252 		ctsio->kern_total_len = param_len;
8253 		ctsio->kern_rel_offset = 0;
8254 		ctsio->kern_sg_entries = 0;
8255 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8256 		ctsio->be_move_done = ctl_config_move_done;
8257 		ctl_datamove((union ctl_io *)ctsio);
8258 
8259 		return (CTL_RETVAL_COMPLETE);
8260 	}
8261 
8262 	param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8263 
8264 	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
8265 	res_key = scsi_8btou64(param->res_key.key);
8266 	sa_res_key = scsi_8btou64(param->serv_act_res_key);
8267 
8268 	/*
8269 	 * Validate the reservation key here except for SPRO_REG_IGNO
8270 	 * This must be done for all other service actions
8271 	 */
8272 	if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8273 		mtx_lock(&lun->lun_lock);
8274 		if ((key = ctl_get_prkey(lun, residx)) != 0) {
8275 			if (res_key != key) {
8276 				/*
8277 				 * The current key passed in doesn't match
8278 				 * the one the initiator previously
8279 				 * registered.
8280 				 */
8281 				mtx_unlock(&lun->lun_lock);
8282 				free(ctsio->kern_data_ptr, M_CTL);
8283 				ctl_set_reservation_conflict(ctsio);
8284 				ctl_done((union ctl_io *)ctsio);
8285 				return (CTL_RETVAL_COMPLETE);
8286 			}
8287 		} else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8288 			/*
8289 			 * We are not registered
8290 			 */
8291 			mtx_unlock(&lun->lun_lock);
8292 			free(ctsio->kern_data_ptr, M_CTL);
8293 			ctl_set_reservation_conflict(ctsio);
8294 			ctl_done((union ctl_io *)ctsio);
8295 			return (CTL_RETVAL_COMPLETE);
8296 		} else if (res_key != 0) {
8297 			/*
8298 			 * We are not registered and trying to register but
8299 			 * the register key isn't zero.
8300 			 */
8301 			mtx_unlock(&lun->lun_lock);
8302 			free(ctsio->kern_data_ptr, M_CTL);
8303 			ctl_set_reservation_conflict(ctsio);
8304 			ctl_done((union ctl_io *)ctsio);
8305 			return (CTL_RETVAL_COMPLETE);
8306 		}
8307 		mtx_unlock(&lun->lun_lock);
8308 	}
8309 
8310 	switch (cdb->action & SPRO_ACTION_MASK) {
8311 	case SPRO_REGISTER:
8312 	case SPRO_REG_IGNO: {
8313 
8314 		/*
8315 		 * We don't support any of these options, as we report in
8316 		 * the read capabilities request (see
8317 		 * ctl_persistent_reserve_in(), above).
8318 		 */
8319 		if ((param->flags & SPR_SPEC_I_PT)
8320 		 || (param->flags & SPR_ALL_TG_PT)
8321 		 || (param->flags & SPR_APTPL)) {
8322 			int bit_ptr;
8323 
8324 			if (param->flags & SPR_APTPL)
8325 				bit_ptr = 0;
8326 			else if (param->flags & SPR_ALL_TG_PT)
8327 				bit_ptr = 2;
8328 			else /* SPR_SPEC_I_PT */
8329 				bit_ptr = 3;
8330 
8331 			free(ctsio->kern_data_ptr, M_CTL);
8332 			ctl_set_invalid_field(ctsio,
8333 					      /*sks_valid*/ 1,
8334 					      /*command*/ 0,
8335 					      /*field*/ 20,
8336 					      /*bit_valid*/ 1,
8337 					      /*bit*/ bit_ptr);
8338 			ctl_done((union ctl_io *)ctsio);
8339 			return (CTL_RETVAL_COMPLETE);
8340 		}
8341 
8342 		mtx_lock(&lun->lun_lock);
8343 
8344 		/*
8345 		 * The initiator wants to clear the
8346 		 * key/unregister.
8347 		 */
8348 		if (sa_res_key == 0) {
8349 			if ((res_key == 0
8350 			  && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8351 			 || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8352 			  && ctl_get_prkey(lun, residx) == 0)) {
8353 				mtx_unlock(&lun->lun_lock);
8354 				goto done;
8355 			}
8356 
8357 			ctl_clr_prkey(lun, residx);
8358 			lun->pr_key_count--;
8359 
8360 			if (residx == lun->pr_res_idx) {
8361 				lun->flags &= ~CTL_LUN_PR_RESERVED;
8362 				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8363 
8364 				if ((lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8365 				     lun->pr_res_type == SPR_TYPE_EX_AC_RO) &&
8366 				    lun->pr_key_count) {
8367 					/*
8368 					 * If the reservation is a registrants
8369 					 * only type we need to generate a UA
8370 					 * for other registered inits.  The
8371 					 * sense code should be RESERVATIONS
8372 					 * RELEASED
8373 					 */
8374 
8375 					for (i = softc->init_min; i < softc->init_max; i++){
8376 						if (ctl_get_prkey(lun, i) == 0)
8377 							continue;
8378 						ctl_est_ua(lun, i,
8379 						    CTL_UA_RES_RELEASE);
8380 					}
8381 				}
8382 				lun->pr_res_type = 0;
8383 			} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8384 				if (lun->pr_key_count==0) {
8385 					lun->flags &= ~CTL_LUN_PR_RESERVED;
8386 					lun->pr_res_type = 0;
8387 					lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8388 				}
8389 			}
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_UNREG_KEY;
8396 			persis_io.pr.pr_info.residx = residx;
8397 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8398 			    sizeof(persis_io.pr), M_WAITOK);
8399 		} else /* sa_res_key != 0 */ {
8400 
8401 			/*
8402 			 * If we aren't registered currently then increment
8403 			 * the key count and set the registered flag.
8404 			 */
8405 			ctl_alloc_prkey(lun, residx);
8406 			if (ctl_get_prkey(lun, residx) == 0)
8407 				lun->pr_key_count++;
8408 			ctl_set_prkey(lun, residx, sa_res_key);
8409 			lun->pr_generation++;
8410 			mtx_unlock(&lun->lun_lock);
8411 
8412 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8413 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8414 			persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8415 			persis_io.pr.pr_info.residx = residx;
8416 			memcpy(persis_io.pr.pr_info.sa_res_key,
8417 			       param->serv_act_res_key,
8418 			       sizeof(param->serv_act_res_key));
8419 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8420 			    sizeof(persis_io.pr), M_WAITOK);
8421 		}
8422 
8423 		break;
8424 	}
8425 	case SPRO_RESERVE:
8426 		mtx_lock(&lun->lun_lock);
8427 		if (lun->flags & CTL_LUN_PR_RESERVED) {
8428 			/*
8429 			 * if this isn't the reservation holder and it's
8430 			 * not a "all registrants" type or if the type is
8431 			 * different then we have a conflict
8432 			 */
8433 			if ((lun->pr_res_idx != residx
8434 			  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8435 			 || lun->pr_res_type != type) {
8436 				mtx_unlock(&lun->lun_lock);
8437 				free(ctsio->kern_data_ptr, M_CTL);
8438 				ctl_set_reservation_conflict(ctsio);
8439 				ctl_done((union ctl_io *)ctsio);
8440 				return (CTL_RETVAL_COMPLETE);
8441 			}
8442 			mtx_unlock(&lun->lun_lock);
8443 		} else /* create a reservation */ {
8444 			/*
8445 			 * If it's not an "all registrants" type record
8446 			 * reservation holder
8447 			 */
8448 			if (type != SPR_TYPE_WR_EX_AR
8449 			 && type != SPR_TYPE_EX_AC_AR)
8450 				lun->pr_res_idx = residx; /* Res holder */
8451 			else
8452 				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8453 
8454 			lun->flags |= CTL_LUN_PR_RESERVED;
8455 			lun->pr_res_type = type;
8456 
8457 			mtx_unlock(&lun->lun_lock);
8458 
8459 			/* send msg to other side */
8460 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8461 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8462 			persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8463 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8464 			persis_io.pr.pr_info.res_type = type;
8465 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8466 			    sizeof(persis_io.pr), M_WAITOK);
8467 		}
8468 		break;
8469 
8470 	case SPRO_RELEASE:
8471 		mtx_lock(&lun->lun_lock);
8472 		if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8473 			/* No reservation exists return good status */
8474 			mtx_unlock(&lun->lun_lock);
8475 			goto done;
8476 		}
8477 		/*
8478 		 * Is this nexus a reservation holder?
8479 		 */
8480 		if (lun->pr_res_idx != residx
8481 		 && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8482 			/*
8483 			 * not a res holder return good status but
8484 			 * do nothing
8485 			 */
8486 			mtx_unlock(&lun->lun_lock);
8487 			goto done;
8488 		}
8489 
8490 		if (lun->pr_res_type != type) {
8491 			mtx_unlock(&lun->lun_lock);
8492 			free(ctsio->kern_data_ptr, M_CTL);
8493 			ctl_set_illegal_pr_release(ctsio);
8494 			ctl_done((union ctl_io *)ctsio);
8495 			return (CTL_RETVAL_COMPLETE);
8496 		}
8497 
8498 		/* okay to release */
8499 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8500 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8501 		lun->pr_res_type = 0;
8502 
8503 		/*
8504 		 * If this isn't an exclusive access reservation and NUAR
8505 		 * is not set, generate UA for all other registrants.
8506 		 */
8507 		if (type != SPR_TYPE_EX_AC && type != SPR_TYPE_WR_EX &&
8508 		    (lun->MODE_CTRL.queue_flags & SCP_NUAR) == 0) {
8509 			for (i = softc->init_min; i < softc->init_max; i++) {
8510 				if (i == residx || ctl_get_prkey(lun, i) == 0)
8511 					continue;
8512 				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8513 			}
8514 		}
8515 		mtx_unlock(&lun->lun_lock);
8516 
8517 		/* Send msg to other side */
8518 		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8519 		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8520 		persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8521 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8522 		     sizeof(persis_io.pr), M_WAITOK);
8523 		break;
8524 
8525 	case SPRO_CLEAR:
8526 		/* send msg to other side */
8527 
8528 		mtx_lock(&lun->lun_lock);
8529 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8530 		lun->pr_res_type = 0;
8531 		lun->pr_key_count = 0;
8532 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8533 
8534 		ctl_clr_prkey(lun, residx);
8535 		for (i = 0; i < CTL_MAX_INITIATORS; i++)
8536 			if (ctl_get_prkey(lun, i) != 0) {
8537 				ctl_clr_prkey(lun, i);
8538 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8539 			}
8540 		lun->pr_generation++;
8541 		mtx_unlock(&lun->lun_lock);
8542 
8543 		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8544 		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8545 		persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8546 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8547 		     sizeof(persis_io.pr), M_WAITOK);
8548 		break;
8549 
8550 	case SPRO_PREEMPT:
8551 	case SPRO_PRE_ABO: {
8552 		int nretval;
8553 
8554 		nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8555 					  residx, ctsio, cdb, param);
8556 		if (nretval != 0)
8557 			return (CTL_RETVAL_COMPLETE);
8558 		break;
8559 	}
8560 	default:
8561 		panic("%s: Invalid PR type %#x", __func__, cdb->action);
8562 	}
8563 
8564 done:
8565 	free(ctsio->kern_data_ptr, M_CTL);
8566 	ctl_set_success(ctsio);
8567 	ctl_done((union ctl_io *)ctsio);
8568 
8569 	return (retval);
8570 }
8571 
8572 /*
8573  * This routine is for handling a message from the other SC pertaining to
8574  * persistent reserve out. All the error checking will have been done
8575  * so only perorming the action need be done here to keep the two
8576  * in sync.
8577  */
8578 static void
8579 ctl_hndl_per_res_out_on_other_sc(union ctl_io *io)
8580 {
8581 	struct ctl_softc *softc = CTL_SOFTC(io);
8582 	union ctl_ha_msg *msg = (union ctl_ha_msg *)&io->presio.pr_msg;
8583 	struct ctl_lun *lun;
8584 	int i;
8585 	uint32_t residx, targ_lun;
8586 
8587 	targ_lun = msg->hdr.nexus.targ_mapped_lun;
8588 	mtx_lock(&softc->ctl_lock);
8589 	if (targ_lun >= ctl_max_luns ||
8590 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
8591 		mtx_unlock(&softc->ctl_lock);
8592 		return;
8593 	}
8594 	mtx_lock(&lun->lun_lock);
8595 	mtx_unlock(&softc->ctl_lock);
8596 	if (lun->flags & CTL_LUN_DISABLED) {
8597 		mtx_unlock(&lun->lun_lock);
8598 		return;
8599 	}
8600 	residx = ctl_get_initindex(&msg->hdr.nexus);
8601 	switch(msg->pr.pr_info.action) {
8602 	case CTL_PR_REG_KEY:
8603 		ctl_alloc_prkey(lun, msg->pr.pr_info.residx);
8604 		if (ctl_get_prkey(lun, msg->pr.pr_info.residx) == 0)
8605 			lun->pr_key_count++;
8606 		ctl_set_prkey(lun, msg->pr.pr_info.residx,
8607 		    scsi_8btou64(msg->pr.pr_info.sa_res_key));
8608 		lun->pr_generation++;
8609 		break;
8610 
8611 	case CTL_PR_UNREG_KEY:
8612 		ctl_clr_prkey(lun, msg->pr.pr_info.residx);
8613 		lun->pr_key_count--;
8614 
8615 		/* XXX Need to see if the reservation has been released */
8616 		/* if so do we need to generate UA? */
8617 		if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8618 			lun->flags &= ~CTL_LUN_PR_RESERVED;
8619 			lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8620 
8621 			if ((lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8622 			     lun->pr_res_type == SPR_TYPE_EX_AC_RO) &&
8623 			    lun->pr_key_count) {
8624 				/*
8625 				 * If the reservation is a registrants
8626 				 * only type we need to generate a UA
8627 				 * for other registered inits.  The
8628 				 * sense code should be RESERVATIONS
8629 				 * RELEASED
8630 				 */
8631 
8632 				for (i = softc->init_min; i < softc->init_max; i++) {
8633 					if (ctl_get_prkey(lun, i) == 0)
8634 						continue;
8635 
8636 					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8637 				}
8638 			}
8639 			lun->pr_res_type = 0;
8640 		} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8641 			if (lun->pr_key_count==0) {
8642 				lun->flags &= ~CTL_LUN_PR_RESERVED;
8643 				lun->pr_res_type = 0;
8644 				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8645 			}
8646 		}
8647 		lun->pr_generation++;
8648 		break;
8649 
8650 	case CTL_PR_RESERVE:
8651 		lun->flags |= CTL_LUN_PR_RESERVED;
8652 		lun->pr_res_type = msg->pr.pr_info.res_type;
8653 		lun->pr_res_idx = msg->pr.pr_info.residx;
8654 
8655 		break;
8656 
8657 	case CTL_PR_RELEASE:
8658 		/*
8659 		 * If this isn't an exclusive access reservation and NUAR
8660 		 * is not set, generate UA for all other registrants.
8661 		 */
8662 		if (lun->pr_res_type != SPR_TYPE_EX_AC &&
8663 		    lun->pr_res_type != SPR_TYPE_WR_EX &&
8664 		    (lun->MODE_CTRL.queue_flags & SCP_NUAR) == 0) {
8665 			for (i = softc->init_min; i < softc->init_max; i++) {
8666 				if (i == residx || ctl_get_prkey(lun, i) == 0)
8667 					continue;
8668 				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8669 			}
8670 		}
8671 
8672 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8673 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8674 		lun->pr_res_type = 0;
8675 		break;
8676 
8677 	case CTL_PR_PREEMPT:
8678 		ctl_pro_preempt_other(lun, msg);
8679 		break;
8680 	case CTL_PR_CLEAR:
8681 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8682 		lun->pr_res_type = 0;
8683 		lun->pr_key_count = 0;
8684 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8685 
8686 		for (i=0; i < CTL_MAX_INITIATORS; i++) {
8687 			if (ctl_get_prkey(lun, i) == 0)
8688 				continue;
8689 			ctl_clr_prkey(lun, i);
8690 			ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8691 		}
8692 		lun->pr_generation++;
8693 		break;
8694 	}
8695 
8696 	mtx_unlock(&lun->lun_lock);
8697 }
8698 
8699 int
8700 ctl_read_write(struct ctl_scsiio *ctsio)
8701 {
8702 	struct ctl_lun *lun = CTL_LUN(ctsio);
8703 	struct ctl_lba_len_flags *lbalen;
8704 	uint64_t lba;
8705 	uint32_t num_blocks;
8706 	int flags, retval;
8707 	int isread;
8708 
8709 	CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8710 
8711 	flags = 0;
8712 	isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8713 	      || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8714 	switch (ctsio->cdb[0]) {
8715 	case READ_6:
8716 	case WRITE_6: {
8717 		struct scsi_rw_6 *cdb;
8718 
8719 		cdb = (struct scsi_rw_6 *)ctsio->cdb;
8720 
8721 		lba = scsi_3btoul(cdb->addr);
8722 		/* only 5 bits are valid in the most significant address byte */
8723 		lba &= 0x1fffff;
8724 		num_blocks = cdb->length;
8725 		/*
8726 		 * This is correct according to SBC-2.
8727 		 */
8728 		if (num_blocks == 0)
8729 			num_blocks = 256;
8730 		break;
8731 	}
8732 	case READ_10:
8733 	case WRITE_10: {
8734 		struct scsi_rw_10 *cdb;
8735 
8736 		cdb = (struct scsi_rw_10 *)ctsio->cdb;
8737 		if (cdb->byte2 & SRW10_FUA)
8738 			flags |= CTL_LLF_FUA;
8739 		if (cdb->byte2 & SRW10_DPO)
8740 			flags |= CTL_LLF_DPO;
8741 		lba = scsi_4btoul(cdb->addr);
8742 		num_blocks = scsi_2btoul(cdb->length);
8743 		break;
8744 	}
8745 	case WRITE_VERIFY_10: {
8746 		struct scsi_write_verify_10 *cdb;
8747 
8748 		cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
8749 		flags |= CTL_LLF_FUA;
8750 		if (cdb->byte2 & SWV_DPO)
8751 			flags |= CTL_LLF_DPO;
8752 		lba = scsi_4btoul(cdb->addr);
8753 		num_blocks = scsi_2btoul(cdb->length);
8754 		break;
8755 	}
8756 	case READ_12:
8757 	case WRITE_12: {
8758 		struct scsi_rw_12 *cdb;
8759 
8760 		cdb = (struct scsi_rw_12 *)ctsio->cdb;
8761 		if (cdb->byte2 & SRW12_FUA)
8762 			flags |= CTL_LLF_FUA;
8763 		if (cdb->byte2 & SRW12_DPO)
8764 			flags |= CTL_LLF_DPO;
8765 		lba = scsi_4btoul(cdb->addr);
8766 		num_blocks = scsi_4btoul(cdb->length);
8767 		break;
8768 	}
8769 	case WRITE_VERIFY_12: {
8770 		struct scsi_write_verify_12 *cdb;
8771 
8772 		cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
8773 		flags |= CTL_LLF_FUA;
8774 		if (cdb->byte2 & SWV_DPO)
8775 			flags |= CTL_LLF_DPO;
8776 		lba = scsi_4btoul(cdb->addr);
8777 		num_blocks = scsi_4btoul(cdb->length);
8778 		break;
8779 	}
8780 	case READ_16:
8781 	case WRITE_16: {
8782 		struct scsi_rw_16 *cdb;
8783 
8784 		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8785 		if (cdb->byte2 & SRW12_FUA)
8786 			flags |= CTL_LLF_FUA;
8787 		if (cdb->byte2 & SRW12_DPO)
8788 			flags |= CTL_LLF_DPO;
8789 		lba = scsi_8btou64(cdb->addr);
8790 		num_blocks = scsi_4btoul(cdb->length);
8791 		break;
8792 	}
8793 	case WRITE_ATOMIC_16: {
8794 		struct scsi_write_atomic_16 *cdb;
8795 
8796 		if (lun->be_lun->atomicblock == 0) {
8797 			ctl_set_invalid_opcode(ctsio);
8798 			ctl_done((union ctl_io *)ctsio);
8799 			return (CTL_RETVAL_COMPLETE);
8800 		}
8801 
8802 		cdb = (struct scsi_write_atomic_16 *)ctsio->cdb;
8803 		if (cdb->byte2 & SRW12_FUA)
8804 			flags |= CTL_LLF_FUA;
8805 		if (cdb->byte2 & SRW12_DPO)
8806 			flags |= CTL_LLF_DPO;
8807 		lba = scsi_8btou64(cdb->addr);
8808 		num_blocks = scsi_2btoul(cdb->length);
8809 		if (num_blocks > lun->be_lun->atomicblock) {
8810 			ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
8811 			    /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
8812 			    /*bit*/ 0);
8813 			ctl_done((union ctl_io *)ctsio);
8814 			return (CTL_RETVAL_COMPLETE);
8815 		}
8816 		break;
8817 	}
8818 	case WRITE_VERIFY_16: {
8819 		struct scsi_write_verify_16 *cdb;
8820 
8821 		cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
8822 		flags |= CTL_LLF_FUA;
8823 		if (cdb->byte2 & SWV_DPO)
8824 			flags |= CTL_LLF_DPO;
8825 		lba = scsi_8btou64(cdb->addr);
8826 		num_blocks = scsi_4btoul(cdb->length);
8827 		break;
8828 	}
8829 	default:
8830 		/*
8831 		 * We got a command we don't support.  This shouldn't
8832 		 * happen, commands should be filtered out above us.
8833 		 */
8834 		ctl_set_invalid_opcode(ctsio);
8835 		ctl_done((union ctl_io *)ctsio);
8836 
8837 		return (CTL_RETVAL_COMPLETE);
8838 		break; /* NOTREACHED */
8839 	}
8840 
8841 	/*
8842 	 * The first check is to make sure we're in bounds, the second
8843 	 * check is to catch wrap-around problems.  If the lba + num blocks
8844 	 * is less than the lba, then we've wrapped around and the block
8845 	 * range is invalid anyway.
8846 	 */
8847 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8848 	 || ((lba + num_blocks) < lba)) {
8849 		ctl_set_lba_out_of_range(ctsio,
8850 		    MAX(lba, lun->be_lun->maxlba + 1));
8851 		ctl_done((union ctl_io *)ctsio);
8852 		return (CTL_RETVAL_COMPLETE);
8853 	}
8854 
8855 	/*
8856 	 * According to SBC-3, a transfer length of 0 is not an error.
8857 	 * Note that this cannot happen with WRITE(6) or READ(6), since 0
8858 	 * translates to 256 blocks for those commands.
8859 	 */
8860 	if (num_blocks == 0) {
8861 		ctl_set_success(ctsio);
8862 		ctl_done((union ctl_io *)ctsio);
8863 		return (CTL_RETVAL_COMPLETE);
8864 	}
8865 
8866 	/* Set FUA and/or DPO if caches are disabled. */
8867 	if (isread) {
8868 		if ((lun->MODE_CACHING.flags1 & SCP_RCD) != 0)
8869 			flags |= CTL_LLF_FUA | CTL_LLF_DPO;
8870 	} else {
8871 		if ((lun->MODE_CACHING.flags1 & SCP_WCE) == 0)
8872 			flags |= CTL_LLF_FUA;
8873 	}
8874 
8875 	lbalen = (struct ctl_lba_len_flags *)
8876 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8877 	lbalen->lba = lba;
8878 	lbalen->len = num_blocks;
8879 	lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
8880 
8881 	ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
8882 	ctsio->kern_rel_offset = 0;
8883 
8884 	CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
8885 
8886 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8887 	return (retval);
8888 }
8889 
8890 static int
8891 ctl_cnw_cont(union ctl_io *io)
8892 {
8893 	struct ctl_lun *lun = CTL_LUN(io);
8894 	struct ctl_scsiio *ctsio;
8895 	struct ctl_lba_len_flags *lbalen;
8896 	int retval;
8897 
8898 	ctsio = &io->scsiio;
8899 	ctsio->io_hdr.status = CTL_STATUS_NONE;
8900 	ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
8901 	lbalen = (struct ctl_lba_len_flags *)
8902 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8903 	lbalen->flags &= ~CTL_LLF_COMPARE;
8904 	lbalen->flags |= CTL_LLF_WRITE;
8905 
8906 	CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
8907 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8908 	return (retval);
8909 }
8910 
8911 int
8912 ctl_cnw(struct ctl_scsiio *ctsio)
8913 {
8914 	struct ctl_lun *lun = CTL_LUN(ctsio);
8915 	struct ctl_lba_len_flags *lbalen;
8916 	uint64_t lba;
8917 	uint32_t num_blocks;
8918 	int flags, retval;
8919 
8920 	CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
8921 
8922 	flags = 0;
8923 	switch (ctsio->cdb[0]) {
8924 	case COMPARE_AND_WRITE: {
8925 		struct scsi_compare_and_write *cdb;
8926 
8927 		cdb = (struct scsi_compare_and_write *)ctsio->cdb;
8928 		if (cdb->byte2 & SRW10_FUA)
8929 			flags |= CTL_LLF_FUA;
8930 		if (cdb->byte2 & SRW10_DPO)
8931 			flags |= CTL_LLF_DPO;
8932 		lba = scsi_8btou64(cdb->addr);
8933 		num_blocks = cdb->length;
8934 		break;
8935 	}
8936 	default:
8937 		/*
8938 		 * We got a command we don't support.  This shouldn't
8939 		 * happen, commands should be filtered out above us.
8940 		 */
8941 		ctl_set_invalid_opcode(ctsio);
8942 		ctl_done((union ctl_io *)ctsio);
8943 
8944 		return (CTL_RETVAL_COMPLETE);
8945 		break; /* NOTREACHED */
8946 	}
8947 
8948 	/*
8949 	 * The first check is to make sure we're in bounds, the second
8950 	 * check is to catch wrap-around problems.  If the lba + num blocks
8951 	 * is less than the lba, then we've wrapped around and the block
8952 	 * range is invalid anyway.
8953 	 */
8954 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8955 	 || ((lba + num_blocks) < lba)) {
8956 		ctl_set_lba_out_of_range(ctsio,
8957 		    MAX(lba, lun->be_lun->maxlba + 1));
8958 		ctl_done((union ctl_io *)ctsio);
8959 		return (CTL_RETVAL_COMPLETE);
8960 	}
8961 
8962 	/*
8963 	 * According to SBC-3, a transfer length of 0 is not an error.
8964 	 */
8965 	if (num_blocks == 0) {
8966 		ctl_set_success(ctsio);
8967 		ctl_done((union ctl_io *)ctsio);
8968 		return (CTL_RETVAL_COMPLETE);
8969 	}
8970 
8971 	/* Set FUA if write cache is disabled. */
8972 	if ((lun->MODE_CACHING.flags1 & SCP_WCE) == 0)
8973 		flags |= CTL_LLF_FUA;
8974 
8975 	ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
8976 	ctsio->kern_rel_offset = 0;
8977 
8978 	/*
8979 	 * Set the IO_CONT flag, so that if this I/O gets passed to
8980 	 * ctl_data_submit_done(), it'll get passed back to
8981 	 * ctl_ctl_cnw_cont() for further processing.
8982 	 */
8983 	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
8984 	ctsio->io_cont = ctl_cnw_cont;
8985 
8986 	lbalen = (struct ctl_lba_len_flags *)
8987 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8988 	lbalen->lba = lba;
8989 	lbalen->len = num_blocks;
8990 	lbalen->flags = CTL_LLF_COMPARE | flags;
8991 
8992 	CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
8993 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8994 	return (retval);
8995 }
8996 
8997 int
8998 ctl_verify(struct ctl_scsiio *ctsio)
8999 {
9000 	struct ctl_lun *lun = CTL_LUN(ctsio);
9001 	struct ctl_lba_len_flags *lbalen;
9002 	uint64_t lba;
9003 	uint32_t num_blocks;
9004 	int bytchk, flags;
9005 	int retval;
9006 
9007 	CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
9008 
9009 	bytchk = 0;
9010 	flags = CTL_LLF_FUA;
9011 	switch (ctsio->cdb[0]) {
9012 	case VERIFY_10: {
9013 		struct scsi_verify_10 *cdb;
9014 
9015 		cdb = (struct scsi_verify_10 *)ctsio->cdb;
9016 		if (cdb->byte2 & SVFY_BYTCHK)
9017 			bytchk = 1;
9018 		if (cdb->byte2 & SVFY_DPO)
9019 			flags |= CTL_LLF_DPO;
9020 		lba = scsi_4btoul(cdb->addr);
9021 		num_blocks = scsi_2btoul(cdb->length);
9022 		break;
9023 	}
9024 	case VERIFY_12: {
9025 		struct scsi_verify_12 *cdb;
9026 
9027 		cdb = (struct scsi_verify_12 *)ctsio->cdb;
9028 		if (cdb->byte2 & SVFY_BYTCHK)
9029 			bytchk = 1;
9030 		if (cdb->byte2 & SVFY_DPO)
9031 			flags |= CTL_LLF_DPO;
9032 		lba = scsi_4btoul(cdb->addr);
9033 		num_blocks = scsi_4btoul(cdb->length);
9034 		break;
9035 	}
9036 	case VERIFY_16: {
9037 		struct scsi_rw_16 *cdb;
9038 
9039 		cdb = (struct scsi_rw_16 *)ctsio->cdb;
9040 		if (cdb->byte2 & SVFY_BYTCHK)
9041 			bytchk = 1;
9042 		if (cdb->byte2 & SVFY_DPO)
9043 			flags |= CTL_LLF_DPO;
9044 		lba = scsi_8btou64(cdb->addr);
9045 		num_blocks = scsi_4btoul(cdb->length);
9046 		break;
9047 	}
9048 	default:
9049 		/*
9050 		 * We got a command we don't support.  This shouldn't
9051 		 * happen, commands should be filtered out above us.
9052 		 */
9053 		ctl_set_invalid_opcode(ctsio);
9054 		ctl_done((union ctl_io *)ctsio);
9055 		return (CTL_RETVAL_COMPLETE);
9056 	}
9057 
9058 	/*
9059 	 * The first check is to make sure we're in bounds, the second
9060 	 * check is to catch wrap-around problems.  If the lba + num blocks
9061 	 * is less than the lba, then we've wrapped around and the block
9062 	 * range is invalid anyway.
9063 	 */
9064 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9065 	 || ((lba + num_blocks) < lba)) {
9066 		ctl_set_lba_out_of_range(ctsio,
9067 		    MAX(lba, lun->be_lun->maxlba + 1));
9068 		ctl_done((union ctl_io *)ctsio);
9069 		return (CTL_RETVAL_COMPLETE);
9070 	}
9071 
9072 	/*
9073 	 * According to SBC-3, a transfer length of 0 is not an error.
9074 	 */
9075 	if (num_blocks == 0) {
9076 		ctl_set_success(ctsio);
9077 		ctl_done((union ctl_io *)ctsio);
9078 		return (CTL_RETVAL_COMPLETE);
9079 	}
9080 
9081 	lbalen = (struct ctl_lba_len_flags *)
9082 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9083 	lbalen->lba = lba;
9084 	lbalen->len = num_blocks;
9085 	if (bytchk) {
9086 		lbalen->flags = CTL_LLF_COMPARE | flags;
9087 		ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9088 	} else {
9089 		lbalen->flags = CTL_LLF_VERIFY | flags;
9090 		ctsio->kern_total_len = 0;
9091 	}
9092 	ctsio->kern_rel_offset = 0;
9093 
9094 	CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9095 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9096 	return (retval);
9097 }
9098 
9099 int
9100 ctl_report_luns(struct ctl_scsiio *ctsio)
9101 {
9102 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9103 	struct ctl_port *port = CTL_PORT(ctsio);
9104 	struct ctl_lun *lun, *request_lun = CTL_LUN(ctsio);
9105 	struct scsi_report_luns *cdb;
9106 	struct scsi_report_luns_data *lun_data;
9107 	int num_filled, num_luns, num_port_luns, retval;
9108 	uint32_t alloc_len, lun_datalen;
9109 	uint32_t initidx, targ_lun_id, lun_id;
9110 
9111 	retval = CTL_RETVAL_COMPLETE;
9112 	cdb = (struct scsi_report_luns *)ctsio->cdb;
9113 
9114 	CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9115 
9116 	num_luns = 0;
9117 	num_port_luns = port->lun_map ? port->lun_map_size : ctl_max_luns;
9118 	mtx_lock(&softc->ctl_lock);
9119 	for (targ_lun_id = 0; targ_lun_id < num_port_luns; targ_lun_id++) {
9120 		if (ctl_lun_map_from_port(port, targ_lun_id) != UINT32_MAX)
9121 			num_luns++;
9122 	}
9123 	mtx_unlock(&softc->ctl_lock);
9124 
9125 	switch (cdb->select_report) {
9126 	case RPL_REPORT_DEFAULT:
9127 	case RPL_REPORT_ALL:
9128 	case RPL_REPORT_NONSUBSID:
9129 		break;
9130 	case RPL_REPORT_WELLKNOWN:
9131 	case RPL_REPORT_ADMIN:
9132 	case RPL_REPORT_CONGLOM:
9133 		num_luns = 0;
9134 		break;
9135 	default:
9136 		ctl_set_invalid_field(ctsio,
9137 				      /*sks_valid*/ 1,
9138 				      /*command*/ 1,
9139 				      /*field*/ 2,
9140 				      /*bit_valid*/ 0,
9141 				      /*bit*/ 0);
9142 		ctl_done((union ctl_io *)ctsio);
9143 		return (retval);
9144 		break; /* NOTREACHED */
9145 	}
9146 
9147 	alloc_len = scsi_4btoul(cdb->length);
9148 	/*
9149 	 * The initiator has to allocate at least 16 bytes for this request,
9150 	 * so he can at least get the header and the first LUN.  Otherwise
9151 	 * we reject the request (per SPC-3 rev 14, section 6.21).
9152 	 */
9153 	if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9154 	    sizeof(struct scsi_report_luns_lundata))) {
9155 		ctl_set_invalid_field(ctsio,
9156 				      /*sks_valid*/ 1,
9157 				      /*command*/ 1,
9158 				      /*field*/ 6,
9159 				      /*bit_valid*/ 0,
9160 				      /*bit*/ 0);
9161 		ctl_done((union ctl_io *)ctsio);
9162 		return (retval);
9163 	}
9164 
9165 	lun_datalen = sizeof(*lun_data) +
9166 		(num_luns * sizeof(struct scsi_report_luns_lundata));
9167 
9168 	ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9169 	lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9170 	ctsio->kern_sg_entries = 0;
9171 
9172 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9173 
9174 	mtx_lock(&softc->ctl_lock);
9175 	for (targ_lun_id = 0, num_filled = 0;
9176 	    targ_lun_id < num_port_luns && num_filled < num_luns;
9177 	    targ_lun_id++) {
9178 		lun_id = ctl_lun_map_from_port(port, targ_lun_id);
9179 		if (lun_id == UINT32_MAX)
9180 			continue;
9181 		lun = softc->ctl_luns[lun_id];
9182 		if (lun == NULL)
9183 			continue;
9184 
9185 		be64enc(lun_data->luns[num_filled++].lundata,
9186 		    ctl_encode_lun(targ_lun_id));
9187 
9188 		/*
9189 		 * According to SPC-3, rev 14 section 6.21:
9190 		 *
9191 		 * "The execution of a REPORT LUNS command to any valid and
9192 		 * installed logical unit shall clear the REPORTED LUNS DATA
9193 		 * HAS CHANGED unit attention condition for all logical
9194 		 * units of that target with respect to the requesting
9195 		 * initiator. A valid and installed logical unit is one
9196 		 * having a PERIPHERAL QUALIFIER of 000b in the standard
9197 		 * INQUIRY data (see 6.4.2)."
9198 		 *
9199 		 * If request_lun is NULL, the LUN this report luns command
9200 		 * was issued to is either disabled or doesn't exist. In that
9201 		 * case, we shouldn't clear any pending lun change unit
9202 		 * attention.
9203 		 */
9204 		if (request_lun != NULL) {
9205 			mtx_lock(&lun->lun_lock);
9206 			ctl_clr_ua(lun, initidx, CTL_UA_LUN_CHANGE);
9207 			mtx_unlock(&lun->lun_lock);
9208 		}
9209 	}
9210 	mtx_unlock(&softc->ctl_lock);
9211 
9212 	/*
9213 	 * It's quite possible that we've returned fewer LUNs than we allocated
9214 	 * space for.  Trim it.
9215 	 */
9216 	lun_datalen = sizeof(*lun_data) +
9217 		(num_filled * sizeof(struct scsi_report_luns_lundata));
9218 	ctsio->kern_rel_offset = 0;
9219 	ctsio->kern_sg_entries = 0;
9220 	ctsio->kern_data_len = min(lun_datalen, alloc_len);
9221 	ctsio->kern_total_len = ctsio->kern_data_len;
9222 
9223 	/*
9224 	 * We set this to the actual data length, regardless of how much
9225 	 * space we actually have to return results.  If the user looks at
9226 	 * this value, he'll know whether or not he allocated enough space
9227 	 * and reissue the command if necessary.  We don't support well
9228 	 * known logical units, so if the user asks for that, return none.
9229 	 */
9230 	scsi_ulto4b(lun_datalen - 8, lun_data->length);
9231 
9232 	/*
9233 	 * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9234 	 * this request.
9235 	 */
9236 	ctl_set_success(ctsio);
9237 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9238 	ctsio->be_move_done = ctl_config_move_done;
9239 	ctl_datamove((union ctl_io *)ctsio);
9240 	return (retval);
9241 }
9242 
9243 int
9244 ctl_request_sense(struct ctl_scsiio *ctsio)
9245 {
9246 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9247 	struct ctl_lun *lun = CTL_LUN(ctsio);
9248 	struct scsi_request_sense *cdb;
9249 	struct scsi_sense_data *sense_ptr, *ps;
9250 	uint32_t initidx;
9251 	int have_error;
9252 	u_int sense_len = SSD_FULL_SIZE;
9253 	scsi_sense_data_type sense_format;
9254 	ctl_ua_type ua_type;
9255 	uint8_t asc = 0, ascq = 0;
9256 
9257 	cdb = (struct scsi_request_sense *)ctsio->cdb;
9258 
9259 	CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9260 
9261 	/*
9262 	 * Determine which sense format the user wants.
9263 	 */
9264 	if (cdb->byte2 & SRS_DESC)
9265 		sense_format = SSD_TYPE_DESC;
9266 	else
9267 		sense_format = SSD_TYPE_FIXED;
9268 
9269 	ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9270 	sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9271 	ctsio->kern_sg_entries = 0;
9272 	ctsio->kern_rel_offset = 0;
9273 
9274 	/*
9275 	 * struct scsi_sense_data, which is currently set to 256 bytes, is
9276 	 * larger than the largest allowed value for the length field in the
9277 	 * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9278 	 */
9279 	ctsio->kern_data_len = cdb->length;
9280 	ctsio->kern_total_len = cdb->length;
9281 
9282 	/*
9283 	 * If we don't have a LUN, we don't have any pending sense.
9284 	 */
9285 	if (lun == NULL ||
9286 	    ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
9287 	     softc->ha_link < CTL_HA_LINK_UNKNOWN)) {
9288 		/* "Logical unit not supported" */
9289 		ctl_set_sense_data(sense_ptr, &sense_len, NULL, sense_format,
9290 		    /*current_error*/ 1,
9291 		    /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
9292 		    /*asc*/ 0x25,
9293 		    /*ascq*/ 0x00,
9294 		    SSD_ELEM_NONE);
9295 		goto send;
9296 	}
9297 
9298 	have_error = 0;
9299 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9300 	/*
9301 	 * Check for pending sense, and then for pending unit attentions.
9302 	 * Pending sense gets returned first, then pending unit attentions.
9303 	 */
9304 	mtx_lock(&lun->lun_lock);
9305 	ps = lun->pending_sense[initidx / CTL_MAX_INIT_PER_PORT];
9306 	if (ps != NULL)
9307 		ps += initidx % CTL_MAX_INIT_PER_PORT;
9308 	if (ps != NULL && ps->error_code != 0) {
9309 		scsi_sense_data_type stored_format;
9310 
9311 		/*
9312 		 * Check to see which sense format was used for the stored
9313 		 * sense data.
9314 		 */
9315 		stored_format = scsi_sense_type(ps);
9316 
9317 		/*
9318 		 * If the user requested a different sense format than the
9319 		 * one we stored, then we need to convert it to the other
9320 		 * format.  If we're going from descriptor to fixed format
9321 		 * sense data, we may lose things in translation, depending
9322 		 * on what options were used.
9323 		 *
9324 		 * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9325 		 * for some reason we'll just copy it out as-is.
9326 		 */
9327 		if ((stored_format == SSD_TYPE_FIXED)
9328 		 && (sense_format == SSD_TYPE_DESC))
9329 			ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9330 			    ps, (struct scsi_sense_data_desc *)sense_ptr);
9331 		else if ((stored_format == SSD_TYPE_DESC)
9332 		      && (sense_format == SSD_TYPE_FIXED))
9333 			ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9334 			    ps, (struct scsi_sense_data_fixed *)sense_ptr);
9335 		else
9336 			memcpy(sense_ptr, ps, sizeof(*sense_ptr));
9337 
9338 		ps->error_code = 0;
9339 		have_error = 1;
9340 	} else {
9341 		ua_type = ctl_build_ua(lun, initidx, sense_ptr, &sense_len,
9342 		    sense_format);
9343 		if (ua_type != CTL_UA_NONE)
9344 			have_error = 1;
9345 	}
9346 	if (have_error == 0) {
9347 		/*
9348 		 * Report informational exception if have one and allowed.
9349 		 */
9350 		if (lun->MODE_IE.mrie != SIEP_MRIE_NO) {
9351 			asc = lun->ie_asc;
9352 			ascq = lun->ie_ascq;
9353 		}
9354 		ctl_set_sense_data(sense_ptr, &sense_len, lun, sense_format,
9355 		    /*current_error*/ 1,
9356 		    /*sense_key*/ SSD_KEY_NO_SENSE,
9357 		    /*asc*/ asc,
9358 		    /*ascq*/ ascq,
9359 		    SSD_ELEM_NONE);
9360 	}
9361 	mtx_unlock(&lun->lun_lock);
9362 
9363 send:
9364 	/*
9365 	 * We report the SCSI status as OK, since the status of the command
9366 	 * itself is OK.  We're reporting sense as parameter data.
9367 	 */
9368 	ctl_set_success(ctsio);
9369 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9370 	ctsio->be_move_done = ctl_config_move_done;
9371 	ctl_datamove((union ctl_io *)ctsio);
9372 	return (CTL_RETVAL_COMPLETE);
9373 }
9374 
9375 int
9376 ctl_tur(struct ctl_scsiio *ctsio)
9377 {
9378 
9379 	CTL_DEBUG_PRINT(("ctl_tur\n"));
9380 
9381 	ctl_set_success(ctsio);
9382 	ctl_done((union ctl_io *)ctsio);
9383 
9384 	return (CTL_RETVAL_COMPLETE);
9385 }
9386 
9387 /*
9388  * SCSI VPD page 0x00, the Supported VPD Pages page.
9389  */
9390 static int
9391 ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9392 {
9393 	struct ctl_lun *lun = CTL_LUN(ctsio);
9394 	struct scsi_vpd_supported_pages *pages;
9395 	int sup_page_size;
9396 	int p;
9397 
9398 	sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9399 	    SCSI_EVPD_NUM_SUPPORTED_PAGES;
9400 	ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9401 	pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9402 	ctsio->kern_rel_offset = 0;
9403 	ctsio->kern_sg_entries = 0;
9404 	ctsio->kern_data_len = min(sup_page_size, alloc_len);
9405 	ctsio->kern_total_len = ctsio->kern_data_len;
9406 
9407 	/*
9408 	 * The control device is always connected.  The disk device, on the
9409 	 * other hand, may not be online all the time.  Need to change this
9410 	 * to figure out whether the disk device is actually online or not.
9411 	 */
9412 	if (lun != NULL)
9413 		pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9414 				lun->be_lun->lun_type;
9415 	else
9416 		pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9417 
9418 	p = 0;
9419 	/* Supported VPD pages */
9420 	pages->page_list[p++] = SVPD_SUPPORTED_PAGES;
9421 	/* Serial Number */
9422 	pages->page_list[p++] = SVPD_UNIT_SERIAL_NUMBER;
9423 	/* Device Identification */
9424 	pages->page_list[p++] = SVPD_DEVICE_ID;
9425 	/* Extended INQUIRY Data */
9426 	pages->page_list[p++] = SVPD_EXTENDED_INQUIRY_DATA;
9427 	/* Mode Page Policy */
9428 	pages->page_list[p++] = SVPD_MODE_PAGE_POLICY;
9429 	/* SCSI Ports */
9430 	pages->page_list[p++] = SVPD_SCSI_PORTS;
9431 	/* Third-party Copy */
9432 	pages->page_list[p++] = SVPD_SCSI_TPC;
9433 	/* SCSI Feature Sets */
9434 	pages->page_list[p++] = SVPD_SCSI_SFS;
9435 	if (lun != NULL && lun->be_lun->lun_type == T_DIRECT) {
9436 		/* Block limits */
9437 		pages->page_list[p++] = SVPD_BLOCK_LIMITS;
9438 		/* Block Device Characteristics */
9439 		pages->page_list[p++] = SVPD_BDC;
9440 		/* Logical Block Provisioning */
9441 		pages->page_list[p++] = SVPD_LBP;
9442 	}
9443 	pages->length = p;
9444 
9445 	ctl_set_success(ctsio);
9446 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9447 	ctsio->be_move_done = ctl_config_move_done;
9448 	ctl_datamove((union ctl_io *)ctsio);
9449 	return (CTL_RETVAL_COMPLETE);
9450 }
9451 
9452 /*
9453  * SCSI VPD page 0x80, the Unit Serial Number page.
9454  */
9455 static int
9456 ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9457 {
9458 	struct ctl_lun *lun = CTL_LUN(ctsio);
9459 	struct scsi_vpd_unit_serial_number *sn_ptr;
9460 	int data_len;
9461 
9462 	data_len = 4 + CTL_SN_LEN;
9463 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9464 	sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9465 	ctsio->kern_rel_offset = 0;
9466 	ctsio->kern_sg_entries = 0;
9467 	ctsio->kern_data_len = min(data_len, alloc_len);
9468 	ctsio->kern_total_len = ctsio->kern_data_len;
9469 
9470 	/*
9471 	 * The control device is always connected.  The disk device, on the
9472 	 * other hand, may not be online all the time.  Need to change this
9473 	 * to figure out whether the disk device is actually online or not.
9474 	 */
9475 	if (lun != NULL)
9476 		sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9477 				  lun->be_lun->lun_type;
9478 	else
9479 		sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9480 
9481 	sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9482 	sn_ptr->length = CTL_SN_LEN;
9483 	/*
9484 	 * If we don't have a LUN, we just leave the serial number as
9485 	 * all spaces.
9486 	 */
9487 	if (lun != NULL) {
9488 		strncpy((char *)sn_ptr->serial_num,
9489 			(char *)lun->be_lun->serial_num, CTL_SN_LEN);
9490 	} else
9491 		memset(sn_ptr->serial_num, 0x20, CTL_SN_LEN);
9492 
9493 	ctl_set_success(ctsio);
9494 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9495 	ctsio->be_move_done = ctl_config_move_done;
9496 	ctl_datamove((union ctl_io *)ctsio);
9497 	return (CTL_RETVAL_COMPLETE);
9498 }
9499 
9500 
9501 /*
9502  * SCSI VPD page 0x86, the Extended INQUIRY Data page.
9503  */
9504 static int
9505 ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9506 {
9507 	struct ctl_lun *lun = CTL_LUN(ctsio);
9508 	struct scsi_vpd_extended_inquiry_data *eid_ptr;
9509 	int data_len;
9510 
9511 	data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
9512 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9513 	eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9514 	ctsio->kern_sg_entries = 0;
9515 	ctsio->kern_rel_offset = 0;
9516 	ctsio->kern_data_len = min(data_len, alloc_len);
9517 	ctsio->kern_total_len = ctsio->kern_data_len;
9518 
9519 	/*
9520 	 * The control device is always connected.  The disk device, on the
9521 	 * other hand, may not be online all the time.
9522 	 */
9523 	if (lun != NULL)
9524 		eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9525 				     lun->be_lun->lun_type;
9526 	else
9527 		eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9528 	eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9529 	scsi_ulto2b(data_len - 4, eid_ptr->page_length);
9530 	/*
9531 	 * We support head of queue, ordered and simple tags.
9532 	 */
9533 	eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9534 	/*
9535 	 * Volatile cache supported.
9536 	 */
9537 	eid_ptr->flags3 = SVPD_EID_V_SUP;
9538 
9539 	/*
9540 	 * This means that we clear the REPORTED LUNS DATA HAS CHANGED unit
9541 	 * attention for a particular IT nexus on all LUNs once we report
9542 	 * it to that nexus once.  This bit is required as of SPC-4.
9543 	 */
9544 	eid_ptr->flags4 = SVPD_EID_LUICLR;
9545 
9546 	/*
9547 	 * We support revert to defaults (RTD) bit in MODE SELECT.
9548 	 */
9549 	eid_ptr->flags5 = SVPD_EID_RTD_SUP;
9550 
9551 	/*
9552 	 * XXX KDM in order to correctly answer this, we would need
9553 	 * information from the SIM to determine how much sense data it
9554 	 * can send.  So this would really be a path inquiry field, most
9555 	 * likely.  This can be set to a maximum of 252 according to SPC-4,
9556 	 * but the hardware may or may not be able to support that much.
9557 	 * 0 just means that the maximum sense data length is not reported.
9558 	 */
9559 	eid_ptr->max_sense_length = 0;
9560 
9561 	ctl_set_success(ctsio);
9562 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9563 	ctsio->be_move_done = ctl_config_move_done;
9564 	ctl_datamove((union ctl_io *)ctsio);
9565 	return (CTL_RETVAL_COMPLETE);
9566 }
9567 
9568 static int
9569 ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
9570 {
9571 	struct ctl_lun *lun = CTL_LUN(ctsio);
9572 	struct scsi_vpd_mode_page_policy *mpp_ptr;
9573 	int data_len;
9574 
9575 	data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9576 	    sizeof(struct scsi_vpd_mode_page_policy_descr);
9577 
9578 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9579 	mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
9580 	ctsio->kern_rel_offset = 0;
9581 	ctsio->kern_sg_entries = 0;
9582 	ctsio->kern_data_len = min(data_len, alloc_len);
9583 	ctsio->kern_total_len = ctsio->kern_data_len;
9584 
9585 	/*
9586 	 * The control device is always connected.  The disk device, on the
9587 	 * other hand, may not be online all the time.
9588 	 */
9589 	if (lun != NULL)
9590 		mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9591 				     lun->be_lun->lun_type;
9592 	else
9593 		mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9594 	mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
9595 	scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
9596 	mpp_ptr->descr[0].page_code = 0x3f;
9597 	mpp_ptr->descr[0].subpage_code = 0xff;
9598 	mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
9599 
9600 	ctl_set_success(ctsio);
9601 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9602 	ctsio->be_move_done = ctl_config_move_done;
9603 	ctl_datamove((union ctl_io *)ctsio);
9604 	return (CTL_RETVAL_COMPLETE);
9605 }
9606 
9607 /*
9608  * SCSI VPD page 0x83, the Device Identification page.
9609  */
9610 static int
9611 ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9612 {
9613 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9614 	struct ctl_port *port = CTL_PORT(ctsio);
9615 	struct ctl_lun *lun = CTL_LUN(ctsio);
9616 	struct scsi_vpd_device_id *devid_ptr;
9617 	struct scsi_vpd_id_descriptor *desc;
9618 	int data_len, g;
9619 	uint8_t proto;
9620 
9621 	data_len = sizeof(struct scsi_vpd_device_id) +
9622 	    sizeof(struct scsi_vpd_id_descriptor) +
9623 		sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9624 	    sizeof(struct scsi_vpd_id_descriptor) +
9625 		sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9626 	if (lun && lun->lun_devid)
9627 		data_len += lun->lun_devid->len;
9628 	if (port && port->port_devid)
9629 		data_len += port->port_devid->len;
9630 	if (port && port->target_devid)
9631 		data_len += port->target_devid->len;
9632 
9633 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9634 	devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9635 	ctsio->kern_sg_entries = 0;
9636 	ctsio->kern_rel_offset = 0;
9637 	ctsio->kern_sg_entries = 0;
9638 	ctsio->kern_data_len = min(data_len, alloc_len);
9639 	ctsio->kern_total_len = ctsio->kern_data_len;
9640 
9641 	/*
9642 	 * The control device is always connected.  The disk device, on the
9643 	 * other hand, may not be online all the time.
9644 	 */
9645 	if (lun != NULL)
9646 		devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9647 				     lun->be_lun->lun_type;
9648 	else
9649 		devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9650 	devid_ptr->page_code = SVPD_DEVICE_ID;
9651 	scsi_ulto2b(data_len - 4, devid_ptr->length);
9652 
9653 	if (port && port->port_type == CTL_PORT_FC)
9654 		proto = SCSI_PROTO_FC << 4;
9655 	else if (port && port->port_type == CTL_PORT_SAS)
9656 		proto = SCSI_PROTO_SAS << 4;
9657 	else if (port && port->port_type == CTL_PORT_ISCSI)
9658 		proto = SCSI_PROTO_ISCSI << 4;
9659 	else
9660 		proto = SCSI_PROTO_SPI << 4;
9661 	desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
9662 
9663 	/*
9664 	 * We're using a LUN association here.  i.e., this device ID is a
9665 	 * per-LUN identifier.
9666 	 */
9667 	if (lun && lun->lun_devid) {
9668 		memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
9669 		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9670 		    lun->lun_devid->len);
9671 	}
9672 
9673 	/*
9674 	 * This is for the WWPN which is a port association.
9675 	 */
9676 	if (port && port->port_devid) {
9677 		memcpy(desc, port->port_devid->data, port->port_devid->len);
9678 		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9679 		    port->port_devid->len);
9680 	}
9681 
9682 	/*
9683 	 * This is for the Relative Target Port(type 4h) identifier
9684 	 */
9685 	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9686 	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9687 	    SVPD_ID_TYPE_RELTARG;
9688 	desc->length = 4;
9689 	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
9690 	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9691 	    sizeof(struct scsi_vpd_id_rel_trgt_port_id));
9692 
9693 	/*
9694 	 * This is for the Target Port Group(type 5h) identifier
9695 	 */
9696 	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9697 	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9698 	    SVPD_ID_TYPE_TPORTGRP;
9699 	desc->length = 4;
9700 	if (softc->is_single ||
9701 	    (port && port->status & CTL_PORT_STATUS_HA_SHARED))
9702 		g = 1;
9703 	else
9704 		g = 2 + ctsio->io_hdr.nexus.targ_port / softc->port_cnt;
9705 	scsi_ulto2b(g, &desc->identifier[2]);
9706 	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9707 	    sizeof(struct scsi_vpd_id_trgt_port_grp_id));
9708 
9709 	/*
9710 	 * This is for the Target identifier
9711 	 */
9712 	if (port && port->target_devid) {
9713 		memcpy(desc, port->target_devid->data, port->target_devid->len);
9714 	}
9715 
9716 	ctl_set_success(ctsio);
9717 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9718 	ctsio->be_move_done = ctl_config_move_done;
9719 	ctl_datamove((union ctl_io *)ctsio);
9720 	return (CTL_RETVAL_COMPLETE);
9721 }
9722 
9723 static int
9724 ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
9725 {
9726 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9727 	struct ctl_lun *lun = CTL_LUN(ctsio);
9728 	struct scsi_vpd_scsi_ports *sp;
9729 	struct scsi_vpd_port_designation *pd;
9730 	struct scsi_vpd_port_designation_cont *pdc;
9731 	struct ctl_port *port;
9732 	int data_len, num_target_ports, iid_len, id_len;
9733 
9734 	num_target_ports = 0;
9735 	iid_len = 0;
9736 	id_len = 0;
9737 	mtx_lock(&softc->ctl_lock);
9738 	STAILQ_FOREACH(port, &softc->port_list, links) {
9739 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9740 			continue;
9741 		if (lun != NULL &&
9742 		    ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
9743 			continue;
9744 		num_target_ports++;
9745 		if (port->init_devid)
9746 			iid_len += port->init_devid->len;
9747 		if (port->port_devid)
9748 			id_len += port->port_devid->len;
9749 	}
9750 	mtx_unlock(&softc->ctl_lock);
9751 
9752 	data_len = sizeof(struct scsi_vpd_scsi_ports) +
9753 	    num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
9754 	     sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
9755 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9756 	sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
9757 	ctsio->kern_sg_entries = 0;
9758 	ctsio->kern_rel_offset = 0;
9759 	ctsio->kern_sg_entries = 0;
9760 	ctsio->kern_data_len = min(data_len, alloc_len);
9761 	ctsio->kern_total_len = ctsio->kern_data_len;
9762 
9763 	/*
9764 	 * The control device is always connected.  The disk device, on the
9765 	 * other hand, may not be online all the time.  Need to change this
9766 	 * to figure out whether the disk device is actually online or not.
9767 	 */
9768 	if (lun != NULL)
9769 		sp->device = (SID_QUAL_LU_CONNECTED << 5) |
9770 				  lun->be_lun->lun_type;
9771 	else
9772 		sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9773 
9774 	sp->page_code = SVPD_SCSI_PORTS;
9775 	scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
9776 	    sp->page_length);
9777 	pd = &sp->design[0];
9778 
9779 	mtx_lock(&softc->ctl_lock);
9780 	STAILQ_FOREACH(port, &softc->port_list, links) {
9781 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9782 			continue;
9783 		if (lun != NULL &&
9784 		    ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
9785 			continue;
9786 		scsi_ulto2b(port->targ_port, pd->relative_port_id);
9787 		if (port->init_devid) {
9788 			iid_len = port->init_devid->len;
9789 			memcpy(pd->initiator_transportid,
9790 			    port->init_devid->data, port->init_devid->len);
9791 		} else
9792 			iid_len = 0;
9793 		scsi_ulto2b(iid_len, pd->initiator_transportid_length);
9794 		pdc = (struct scsi_vpd_port_designation_cont *)
9795 		    (&pd->initiator_transportid[iid_len]);
9796 		if (port->port_devid) {
9797 			id_len = port->port_devid->len;
9798 			memcpy(pdc->target_port_descriptors,
9799 			    port->port_devid->data, port->port_devid->len);
9800 		} else
9801 			id_len = 0;
9802 		scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
9803 		pd = (struct scsi_vpd_port_designation *)
9804 		    ((uint8_t *)pdc->target_port_descriptors + id_len);
9805 	}
9806 	mtx_unlock(&softc->ctl_lock);
9807 
9808 	ctl_set_success(ctsio);
9809 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9810 	ctsio->be_move_done = ctl_config_move_done;
9811 	ctl_datamove((union ctl_io *)ctsio);
9812 	return (CTL_RETVAL_COMPLETE);
9813 }
9814 
9815 static int
9816 ctl_inquiry_evpd_sfs(struct ctl_scsiio *ctsio, int alloc_len)
9817 {
9818 	struct ctl_lun *lun = CTL_LUN(ctsio);
9819 	struct scsi_vpd_sfs *sfs_ptr;
9820 	int sfs_page_size, n;
9821 
9822 	sfs_page_size = sizeof(*sfs_ptr) + 5 * 2;
9823 	ctsio->kern_data_ptr = malloc(sfs_page_size, M_CTL, M_WAITOK | M_ZERO);
9824 	sfs_ptr = (struct scsi_vpd_sfs *)ctsio->kern_data_ptr;
9825 	ctsio->kern_sg_entries = 0;
9826 	ctsio->kern_rel_offset = 0;
9827 	ctsio->kern_sg_entries = 0;
9828 	ctsio->kern_data_len = min(sfs_page_size, alloc_len);
9829 	ctsio->kern_total_len = ctsio->kern_data_len;
9830 
9831 	/*
9832 	 * The control device is always connected.  The disk device, on the
9833 	 * other hand, may not be online all the time.  Need to change this
9834 	 * to figure out whether the disk device is actually online or not.
9835 	 */
9836 	if (lun != NULL)
9837 		sfs_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9838 				  lun->be_lun->lun_type;
9839 	else
9840 		sfs_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9841 
9842 	sfs_ptr->page_code = SVPD_SCSI_SFS;
9843 	n = 0;
9844 	/* Discovery 2016 */
9845 	scsi_ulto2b(0x0001, &sfs_ptr->codes[2 * n++]);
9846 	if (lun != NULL && lun->be_lun->lun_type == T_DIRECT) {
9847 		 /* SBC Base 2016 */
9848 		scsi_ulto2b(0x0101, &sfs_ptr->codes[2 * n++]);
9849 		 /* SBC Base 2010 */
9850 		scsi_ulto2b(0x0102, &sfs_ptr->codes[2 * n++]);
9851 		if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9852 			/* Basic Provisioning 2016 */
9853 			scsi_ulto2b(0x0103, &sfs_ptr->codes[2 * n++]);
9854 		}
9855 		/* Drive Maintenance 2016 */
9856 		//scsi_ulto2b(0x0104, &sfs_ptr->codes[2 * n++]);
9857 	}
9858 	scsi_ulto2b(4 + 2 * n, sfs_ptr->page_length);
9859 
9860 	ctl_set_success(ctsio);
9861 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9862 	ctsio->be_move_done = ctl_config_move_done;
9863 	ctl_datamove((union ctl_io *)ctsio);
9864 	return (CTL_RETVAL_COMPLETE);
9865 }
9866 
9867 static int
9868 ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
9869 {
9870 	struct ctl_lun *lun = CTL_LUN(ctsio);
9871 	struct scsi_vpd_block_limits *bl_ptr;
9872 	const char *val;
9873 	uint64_t ival;
9874 
9875 	ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
9876 	bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
9877 	ctsio->kern_sg_entries = 0;
9878 	ctsio->kern_rel_offset = 0;
9879 	ctsio->kern_sg_entries = 0;
9880 	ctsio->kern_data_len = min(sizeof(*bl_ptr), alloc_len);
9881 	ctsio->kern_total_len = ctsio->kern_data_len;
9882 
9883 	/*
9884 	 * The control device is always connected.  The disk device, on the
9885 	 * other hand, may not be online all the time.  Need to change this
9886 	 * to figure out whether the disk device is actually online or not.
9887 	 */
9888 	if (lun != NULL)
9889 		bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9890 				  lun->be_lun->lun_type;
9891 	else
9892 		bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9893 
9894 	bl_ptr->page_code = SVPD_BLOCK_LIMITS;
9895 	scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
9896 	bl_ptr->max_cmp_write_len = 0xff;
9897 	scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
9898 	if (lun != NULL) {
9899 		scsi_ulto4b(lun->be_lun->opttxferlen, bl_ptr->opt_txfer_len);
9900 		if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9901 			ival = 0xffffffff;
9902 			val = dnvlist_get_string(lun->be_lun->options,
9903 			    "unmap_max_lba", NULL);
9904 			if (val != NULL)
9905 				ctl_expand_number(val, &ival);
9906 			scsi_ulto4b(ival, bl_ptr->max_unmap_lba_cnt);
9907 			ival = 0xffffffff;
9908 			val = dnvlist_get_string(lun->be_lun->options,
9909 			    "unmap_max_descr", NULL);
9910 			if (val != NULL)
9911 				ctl_expand_number(val, &ival);
9912 			scsi_ulto4b(ival, bl_ptr->max_unmap_blk_cnt);
9913 			if (lun->be_lun->ublockexp != 0) {
9914 				scsi_ulto4b((1 << lun->be_lun->ublockexp),
9915 				    bl_ptr->opt_unmap_grain);
9916 				scsi_ulto4b(0x80000000 | lun->be_lun->ublockoff,
9917 				    bl_ptr->unmap_grain_align);
9918 			}
9919 		}
9920 		scsi_ulto4b(lun->be_lun->atomicblock,
9921 		    bl_ptr->max_atomic_transfer_length);
9922 		scsi_ulto4b(0, bl_ptr->atomic_alignment);
9923 		scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
9924 		scsi_ulto4b(0, bl_ptr->max_atomic_transfer_length_with_atomic_boundary);
9925 		scsi_ulto4b(0, bl_ptr->max_atomic_boundary_size);
9926 		ival = UINT64_MAX;
9927 		val = dnvlist_get_string(lun->be_lun->options,
9928 		    "write_same_max_lba", NULL);
9929 		if (val != NULL)
9930 			ctl_expand_number(val, &ival);
9931 		scsi_u64to8b(ival, bl_ptr->max_write_same_length);
9932 		if (lun->be_lun->maxlba + 1 > ival)
9933 			bl_ptr->flags |= SVPD_BL_WSNZ;
9934 	}
9935 
9936 	ctl_set_success(ctsio);
9937 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9938 	ctsio->be_move_done = ctl_config_move_done;
9939 	ctl_datamove((union ctl_io *)ctsio);
9940 	return (CTL_RETVAL_COMPLETE);
9941 }
9942 
9943 static int
9944 ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
9945 {
9946 	struct ctl_lun *lun = CTL_LUN(ctsio);
9947 	struct scsi_vpd_block_device_characteristics *bdc_ptr;
9948 	const char *value;
9949 	u_int i;
9950 
9951 	ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
9952 	bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
9953 	ctsio->kern_sg_entries = 0;
9954 	ctsio->kern_rel_offset = 0;
9955 	ctsio->kern_data_len = min(sizeof(*bdc_ptr), alloc_len);
9956 	ctsio->kern_total_len = ctsio->kern_data_len;
9957 
9958 	/*
9959 	 * The control device is always connected.  The disk device, on the
9960 	 * other hand, may not be online all the time.  Need to change this
9961 	 * to figure out whether the disk device is actually online or not.
9962 	 */
9963 	if (lun != NULL)
9964 		bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9965 				  lun->be_lun->lun_type;
9966 	else
9967 		bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9968 	bdc_ptr->page_code = SVPD_BDC;
9969 	scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
9970 	if (lun != NULL &&
9971 	    (value = dnvlist_get_string(lun->be_lun->options, "rpm", NULL)) != NULL)
9972 		i = strtol(value, NULL, 0);
9973 	else
9974 		i = CTL_DEFAULT_ROTATION_RATE;
9975 	scsi_ulto2b(i, bdc_ptr->medium_rotation_rate);
9976 	if (lun != NULL &&
9977 	    (value = dnvlist_get_string(lun->be_lun->options, "formfactor", NULL)) != NULL)
9978 		i = strtol(value, NULL, 0);
9979 	else
9980 		i = 0;
9981 	bdc_ptr->wab_wac_ff = (i & 0x0f);
9982 	bdc_ptr->flags = SVPD_RBWZ | SVPD_FUAB | SVPD_VBULS;
9983 
9984 	ctl_set_success(ctsio);
9985 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9986 	ctsio->be_move_done = ctl_config_move_done;
9987 	ctl_datamove((union ctl_io *)ctsio);
9988 	return (CTL_RETVAL_COMPLETE);
9989 }
9990 
9991 static int
9992 ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
9993 {
9994 	struct ctl_lun *lun = CTL_LUN(ctsio);
9995 	struct scsi_vpd_logical_block_prov *lbp_ptr;
9996 	const char *value;
9997 
9998 	ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
9999 	lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
10000 	ctsio->kern_sg_entries = 0;
10001 	ctsio->kern_rel_offset = 0;
10002 	ctsio->kern_data_len = min(sizeof(*lbp_ptr), alloc_len);
10003 	ctsio->kern_total_len = ctsio->kern_data_len;
10004 
10005 	/*
10006 	 * The control device is always connected.  The disk device, on the
10007 	 * other hand, may not be online all the time.  Need to change this
10008 	 * to figure out whether the disk device is actually online or not.
10009 	 */
10010 	if (lun != NULL)
10011 		lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10012 				  lun->be_lun->lun_type;
10013 	else
10014 		lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10015 
10016 	lbp_ptr->page_code = SVPD_LBP;
10017 	scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
10018 	lbp_ptr->threshold_exponent = CTL_LBP_EXPONENT;
10019 	if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10020 		lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
10021 		    SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
10022 		value = dnvlist_get_string(lun->be_lun->options,
10023 		    "provisioning_type", NULL);
10024 		if (value != NULL) {
10025 			if (strcmp(value, "resource") == 0)
10026 				lbp_ptr->prov_type = SVPD_LBP_RESOURCE;
10027 			else if (strcmp(value, "thin") == 0)
10028 				lbp_ptr->prov_type = SVPD_LBP_THIN;
10029 		} else
10030 			lbp_ptr->prov_type = SVPD_LBP_THIN;
10031 	}
10032 
10033 	ctl_set_success(ctsio);
10034 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10035 	ctsio->be_move_done = ctl_config_move_done;
10036 	ctl_datamove((union ctl_io *)ctsio);
10037 	return (CTL_RETVAL_COMPLETE);
10038 }
10039 
10040 /*
10041  * INQUIRY with the EVPD bit set.
10042  */
10043 static int
10044 ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
10045 {
10046 	struct ctl_lun *lun = CTL_LUN(ctsio);
10047 	struct scsi_inquiry *cdb;
10048 	int alloc_len, retval;
10049 
10050 	cdb = (struct scsi_inquiry *)ctsio->cdb;
10051 	alloc_len = scsi_2btoul(cdb->length);
10052 
10053 	switch (cdb->page_code) {
10054 	case SVPD_SUPPORTED_PAGES:
10055 		retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
10056 		break;
10057 	case SVPD_UNIT_SERIAL_NUMBER:
10058 		retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
10059 		break;
10060 	case SVPD_DEVICE_ID:
10061 		retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
10062 		break;
10063 	case SVPD_EXTENDED_INQUIRY_DATA:
10064 		retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
10065 		break;
10066 	case SVPD_MODE_PAGE_POLICY:
10067 		retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
10068 		break;
10069 	case SVPD_SCSI_PORTS:
10070 		retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10071 		break;
10072 	case SVPD_SCSI_TPC:
10073 		retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
10074 		break;
10075 	case SVPD_SCSI_SFS:
10076 		retval = ctl_inquiry_evpd_sfs(ctsio, alloc_len);
10077 		break;
10078 	case SVPD_BLOCK_LIMITS:
10079 		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10080 			goto err;
10081 		retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10082 		break;
10083 	case SVPD_BDC:
10084 		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10085 			goto err;
10086 		retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
10087 		break;
10088 	case SVPD_LBP:
10089 		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10090 			goto err;
10091 		retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10092 		break;
10093 	default:
10094 err:
10095 		ctl_set_invalid_field(ctsio,
10096 				      /*sks_valid*/ 1,
10097 				      /*command*/ 1,
10098 				      /*field*/ 2,
10099 				      /*bit_valid*/ 0,
10100 				      /*bit*/ 0);
10101 		ctl_done((union ctl_io *)ctsio);
10102 		retval = CTL_RETVAL_COMPLETE;
10103 		break;
10104 	}
10105 
10106 	return (retval);
10107 }
10108 
10109 /*
10110  * Standard INQUIRY data.
10111  */
10112 static int
10113 ctl_inquiry_std(struct ctl_scsiio *ctsio)
10114 {
10115 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
10116 	struct ctl_port *port = CTL_PORT(ctsio);
10117 	struct ctl_lun *lun = CTL_LUN(ctsio);
10118 	struct scsi_inquiry_data *inq_ptr;
10119 	struct scsi_inquiry *cdb;
10120 	const char *val;
10121 	uint32_t alloc_len, data_len;
10122 	ctl_port_type port_type;
10123 
10124 	port_type = port->port_type;
10125 	if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10126 		port_type = CTL_PORT_SCSI;
10127 
10128 	cdb = (struct scsi_inquiry *)ctsio->cdb;
10129 	alloc_len = scsi_2btoul(cdb->length);
10130 
10131 	/*
10132 	 * We malloc the full inquiry data size here and fill it
10133 	 * in.  If the user only asks for less, we'll give him
10134 	 * that much.
10135 	 */
10136 	data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
10137 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10138 	inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10139 	ctsio->kern_sg_entries = 0;
10140 	ctsio->kern_rel_offset = 0;
10141 	ctsio->kern_data_len = min(data_len, alloc_len);
10142 	ctsio->kern_total_len = ctsio->kern_data_len;
10143 
10144 	if (lun != NULL) {
10145 		if ((lun->flags & CTL_LUN_PRIMARY_SC) ||
10146 		    softc->ha_link >= CTL_HA_LINK_UNKNOWN) {
10147 			inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10148 			    lun->be_lun->lun_type;
10149 		} else {
10150 			inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) |
10151 			    lun->be_lun->lun_type;
10152 		}
10153 		if (lun->flags & CTL_LUN_REMOVABLE)
10154 			inq_ptr->dev_qual2 |= SID_RMB;
10155 	} else
10156 		inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10157 
10158 	/* RMB in byte 2 is 0 */
10159 	inq_ptr->version = SCSI_REV_SPC5;
10160 
10161 	/*
10162 	 * According to SAM-3, even if a device only supports a single
10163 	 * level of LUN addressing, it should still set the HISUP bit:
10164 	 *
10165 	 * 4.9.1 Logical unit numbers overview
10166 	 *
10167 	 * All logical unit number formats described in this standard are
10168 	 * hierarchical in structure even when only a single level in that
10169 	 * hierarchy is used. The HISUP bit shall be set to one in the
10170 	 * standard INQUIRY data (see SPC-2) when any logical unit number
10171 	 * format described in this standard is used.  Non-hierarchical
10172 	 * formats are outside the scope of this standard.
10173 	 *
10174 	 * Therefore we set the HiSup bit here.
10175 	 *
10176 	 * The response format is 2, per SPC-3.
10177 	 */
10178 	inq_ptr->response_format = SID_HiSup | 2;
10179 
10180 	inq_ptr->additional_length = data_len -
10181 	    (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10182 	CTL_DEBUG_PRINT(("additional_length = %d\n",
10183 			 inq_ptr->additional_length));
10184 
10185 	inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10186 	if (port_type == CTL_PORT_SCSI)
10187 		inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10188 	inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10189 	inq_ptr->flags = SID_CmdQue;
10190 	if (port_type == CTL_PORT_SCSI)
10191 		inq_ptr->flags |= SID_WBus16 | SID_Sync;
10192 
10193 	/*
10194 	 * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10195 	 * We have 8 bytes for the vendor name, and 16 bytes for the device
10196 	 * name and 4 bytes for the revision.
10197 	 */
10198 	if (lun == NULL || (val = dnvlist_get_string(lun->be_lun->options,
10199 	    "vendor", NULL)) == NULL) {
10200 		strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10201 	} else {
10202 		memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10203 		strncpy(inq_ptr->vendor, val,
10204 		    min(sizeof(inq_ptr->vendor), strlen(val)));
10205 	}
10206 	if (lun == NULL) {
10207 		strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10208 		    sizeof(inq_ptr->product));
10209 	} else if ((val = dnvlist_get_string(lun->be_lun->options, "product",
10210 	    NULL)) == NULL) {
10211 		switch (lun->be_lun->lun_type) {
10212 		case T_DIRECT:
10213 			strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10214 			    sizeof(inq_ptr->product));
10215 			break;
10216 		case T_PROCESSOR:
10217 			strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10218 			    sizeof(inq_ptr->product));
10219 			break;
10220 		case T_CDROM:
10221 			strncpy(inq_ptr->product, CTL_CDROM_PRODUCT,
10222 			    sizeof(inq_ptr->product));
10223 			break;
10224 		default:
10225 			strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10226 			    sizeof(inq_ptr->product));
10227 			break;
10228 		}
10229 	} else {
10230 		memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10231 		strncpy(inq_ptr->product, val,
10232 		    min(sizeof(inq_ptr->product), strlen(val)));
10233 	}
10234 
10235 	/*
10236 	 * XXX make this a macro somewhere so it automatically gets
10237 	 * incremented when we make changes.
10238 	 */
10239 	if (lun == NULL || (val = dnvlist_get_string(lun->be_lun->options,
10240 	    "revision", NULL)) == NULL) {
10241 		strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10242 	} else {
10243 		memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10244 		strncpy(inq_ptr->revision, val,
10245 		    min(sizeof(inq_ptr->revision), strlen(val)));
10246 	}
10247 
10248 	/*
10249 	 * For parallel SCSI, we support double transition and single
10250 	 * transition clocking.  We also support QAS (Quick Arbitration
10251 	 * and Selection) and Information Unit transfers on both the
10252 	 * control and array devices.
10253 	 */
10254 	if (port_type == CTL_PORT_SCSI)
10255 		inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10256 				    SID_SPI_IUS;
10257 
10258 	/* SAM-6 (no version claimed) */
10259 	scsi_ulto2b(0x00C0, inq_ptr->version1);
10260 	/* SPC-5 (no version claimed) */
10261 	scsi_ulto2b(0x05C0, inq_ptr->version2);
10262 	if (port_type == CTL_PORT_FC) {
10263 		/* FCP-2 ANSI INCITS.350:2003 */
10264 		scsi_ulto2b(0x0917, inq_ptr->version3);
10265 	} else if (port_type == CTL_PORT_SCSI) {
10266 		/* SPI-4 ANSI INCITS.362:200x */
10267 		scsi_ulto2b(0x0B56, inq_ptr->version3);
10268 	} else if (port_type == CTL_PORT_ISCSI) {
10269 		/* iSCSI (no version claimed) */
10270 		scsi_ulto2b(0x0960, inq_ptr->version3);
10271 	} else if (port_type == CTL_PORT_SAS) {
10272 		/* SAS (no version claimed) */
10273 		scsi_ulto2b(0x0BE0, inq_ptr->version3);
10274 	} else if (port_type == CTL_PORT_UMASS) {
10275 		/* USB Mass Storage Class Bulk-Only Transport, Revision 1.0 */
10276 		scsi_ulto2b(0x1730, inq_ptr->version3);
10277 	}
10278 
10279 	if (lun == NULL) {
10280 		/* SBC-4 (no version claimed) */
10281 		scsi_ulto2b(0x0600, inq_ptr->version4);
10282 	} else {
10283 		switch (lun->be_lun->lun_type) {
10284 		case T_DIRECT:
10285 			/* SBC-4 (no version claimed) */
10286 			scsi_ulto2b(0x0600, inq_ptr->version4);
10287 			break;
10288 		case T_PROCESSOR:
10289 			break;
10290 		case T_CDROM:
10291 			/* MMC-6 (no version claimed) */
10292 			scsi_ulto2b(0x04E0, inq_ptr->version4);
10293 			break;
10294 		default:
10295 			break;
10296 		}
10297 	}
10298 
10299 	ctl_set_success(ctsio);
10300 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10301 	ctsio->be_move_done = ctl_config_move_done;
10302 	ctl_datamove((union ctl_io *)ctsio);
10303 	return (CTL_RETVAL_COMPLETE);
10304 }
10305 
10306 int
10307 ctl_inquiry(struct ctl_scsiio *ctsio)
10308 {
10309 	struct scsi_inquiry *cdb;
10310 	int retval;
10311 
10312 	CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10313 
10314 	cdb = (struct scsi_inquiry *)ctsio->cdb;
10315 	if (cdb->byte2 & SI_EVPD)
10316 		retval = ctl_inquiry_evpd(ctsio);
10317 	else if (cdb->page_code == 0)
10318 		retval = ctl_inquiry_std(ctsio);
10319 	else {
10320 		ctl_set_invalid_field(ctsio,
10321 				      /*sks_valid*/ 1,
10322 				      /*command*/ 1,
10323 				      /*field*/ 2,
10324 				      /*bit_valid*/ 0,
10325 				      /*bit*/ 0);
10326 		ctl_done((union ctl_io *)ctsio);
10327 		return (CTL_RETVAL_COMPLETE);
10328 	}
10329 
10330 	return (retval);
10331 }
10332 
10333 int
10334 ctl_get_config(struct ctl_scsiio *ctsio)
10335 {
10336 	struct ctl_lun *lun = CTL_LUN(ctsio);
10337 	struct scsi_get_config_header *hdr;
10338 	struct scsi_get_config_feature *feature;
10339 	struct scsi_get_config *cdb;
10340 	uint32_t alloc_len, data_len;
10341 	int rt, starting;
10342 
10343 	cdb = (struct scsi_get_config *)ctsio->cdb;
10344 	rt = (cdb->rt & SGC_RT_MASK);
10345 	starting = scsi_2btoul(cdb->starting_feature);
10346 	alloc_len = scsi_2btoul(cdb->length);
10347 
10348 	data_len = sizeof(struct scsi_get_config_header) +
10349 	    sizeof(struct scsi_get_config_feature) + 8 +
10350 	    sizeof(struct scsi_get_config_feature) + 8 +
10351 	    sizeof(struct scsi_get_config_feature) + 4 +
10352 	    sizeof(struct scsi_get_config_feature) + 4 +
10353 	    sizeof(struct scsi_get_config_feature) + 8 +
10354 	    sizeof(struct scsi_get_config_feature) +
10355 	    sizeof(struct scsi_get_config_feature) + 4 +
10356 	    sizeof(struct scsi_get_config_feature) + 4 +
10357 	    sizeof(struct scsi_get_config_feature) + 4 +
10358 	    sizeof(struct scsi_get_config_feature) + 4 +
10359 	    sizeof(struct scsi_get_config_feature) + 4 +
10360 	    sizeof(struct scsi_get_config_feature) + 4;
10361 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10362 	ctsio->kern_sg_entries = 0;
10363 	ctsio->kern_rel_offset = 0;
10364 
10365 	hdr = (struct scsi_get_config_header *)ctsio->kern_data_ptr;
10366 	if (lun->flags & CTL_LUN_NO_MEDIA)
10367 		scsi_ulto2b(0x0000, hdr->current_profile);
10368 	else
10369 		scsi_ulto2b(0x0010, hdr->current_profile);
10370 	feature = (struct scsi_get_config_feature *)(hdr + 1);
10371 
10372 	if (starting > 0x003b)
10373 		goto done;
10374 	if (starting > 0x003a)
10375 		goto f3b;
10376 	if (starting > 0x002b)
10377 		goto f3a;
10378 	if (starting > 0x002a)
10379 		goto f2b;
10380 	if (starting > 0x001f)
10381 		goto f2a;
10382 	if (starting > 0x001e)
10383 		goto f1f;
10384 	if (starting > 0x001d)
10385 		goto f1e;
10386 	if (starting > 0x0010)
10387 		goto f1d;
10388 	if (starting > 0x0003)
10389 		goto f10;
10390 	if (starting > 0x0002)
10391 		goto f3;
10392 	if (starting > 0x0001)
10393 		goto f2;
10394 	if (starting > 0x0000)
10395 		goto f1;
10396 
10397 	/* Profile List */
10398 	scsi_ulto2b(0x0000, feature->feature_code);
10399 	feature->flags = SGC_F_PERSISTENT | SGC_F_CURRENT;
10400 	feature->add_length = 8;
10401 	scsi_ulto2b(0x0008, &feature->feature_data[0]);	/* CD-ROM */
10402 	feature->feature_data[2] = 0x00;
10403 	scsi_ulto2b(0x0010, &feature->feature_data[4]);	/* DVD-ROM */
10404 	feature->feature_data[6] = 0x01;
10405 	feature = (struct scsi_get_config_feature *)
10406 	    &feature->feature_data[feature->add_length];
10407 
10408 f1:	/* Core */
10409 	scsi_ulto2b(0x0001, feature->feature_code);
10410 	feature->flags = 0x08 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10411 	feature->add_length = 8;
10412 	scsi_ulto4b(0x00000000, &feature->feature_data[0]);
10413 	feature->feature_data[4] = 0x03;
10414 	feature = (struct scsi_get_config_feature *)
10415 	    &feature->feature_data[feature->add_length];
10416 
10417 f2:	/* Morphing */
10418 	scsi_ulto2b(0x0002, feature->feature_code);
10419 	feature->flags = 0x04 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10420 	feature->add_length = 4;
10421 	feature->feature_data[0] = 0x02;
10422 	feature = (struct scsi_get_config_feature *)
10423 	    &feature->feature_data[feature->add_length];
10424 
10425 f3:	/* Removable Medium */
10426 	scsi_ulto2b(0x0003, feature->feature_code);
10427 	feature->flags = 0x04 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10428 	feature->add_length = 4;
10429 	feature->feature_data[0] = 0x39;
10430 	feature = (struct scsi_get_config_feature *)
10431 	    &feature->feature_data[feature->add_length];
10432 
10433 	if (rt == SGC_RT_CURRENT && (lun->flags & CTL_LUN_NO_MEDIA))
10434 		goto done;
10435 
10436 f10:	/* Random Read */
10437 	scsi_ulto2b(0x0010, feature->feature_code);
10438 	feature->flags = 0x00;
10439 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10440 		feature->flags |= SGC_F_CURRENT;
10441 	feature->add_length = 8;
10442 	scsi_ulto4b(lun->be_lun->blocksize, &feature->feature_data[0]);
10443 	scsi_ulto2b(1, &feature->feature_data[4]);
10444 	feature->feature_data[6] = 0x00;
10445 	feature = (struct scsi_get_config_feature *)
10446 	    &feature->feature_data[feature->add_length];
10447 
10448 f1d:	/* Multi-Read */
10449 	scsi_ulto2b(0x001D, feature->feature_code);
10450 	feature->flags = 0x00;
10451 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10452 		feature->flags |= SGC_F_CURRENT;
10453 	feature->add_length = 0;
10454 	feature = (struct scsi_get_config_feature *)
10455 	    &feature->feature_data[feature->add_length];
10456 
10457 f1e:	/* CD Read */
10458 	scsi_ulto2b(0x001E, feature->feature_code);
10459 	feature->flags = 0x00;
10460 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10461 		feature->flags |= SGC_F_CURRENT;
10462 	feature->add_length = 4;
10463 	feature->feature_data[0] = 0x00;
10464 	feature = (struct scsi_get_config_feature *)
10465 	    &feature->feature_data[feature->add_length];
10466 
10467 f1f:	/* DVD Read */
10468 	scsi_ulto2b(0x001F, feature->feature_code);
10469 	feature->flags = 0x08;
10470 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10471 		feature->flags |= SGC_F_CURRENT;
10472 	feature->add_length = 4;
10473 	feature->feature_data[0] = 0x01;
10474 	feature->feature_data[2] = 0x03;
10475 	feature = (struct scsi_get_config_feature *)
10476 	    &feature->feature_data[feature->add_length];
10477 
10478 f2a:	/* DVD+RW */
10479 	scsi_ulto2b(0x002A, feature->feature_code);
10480 	feature->flags = 0x04;
10481 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10482 		feature->flags |= SGC_F_CURRENT;
10483 	feature->add_length = 4;
10484 	feature->feature_data[0] = 0x00;
10485 	feature->feature_data[1] = 0x00;
10486 	feature = (struct scsi_get_config_feature *)
10487 	    &feature->feature_data[feature->add_length];
10488 
10489 f2b:	/* DVD+R */
10490 	scsi_ulto2b(0x002B, feature->feature_code);
10491 	feature->flags = 0x00;
10492 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10493 		feature->flags |= SGC_F_CURRENT;
10494 	feature->add_length = 4;
10495 	feature->feature_data[0] = 0x00;
10496 	feature = (struct scsi_get_config_feature *)
10497 	    &feature->feature_data[feature->add_length];
10498 
10499 f3a:	/* DVD+RW Dual Layer */
10500 	scsi_ulto2b(0x003A, feature->feature_code);
10501 	feature->flags = 0x00;
10502 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10503 		feature->flags |= SGC_F_CURRENT;
10504 	feature->add_length = 4;
10505 	feature->feature_data[0] = 0x00;
10506 	feature->feature_data[1] = 0x00;
10507 	feature = (struct scsi_get_config_feature *)
10508 	    &feature->feature_data[feature->add_length];
10509 
10510 f3b:	/* DVD+R Dual Layer */
10511 	scsi_ulto2b(0x003B, feature->feature_code);
10512 	feature->flags = 0x00;
10513 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10514 		feature->flags |= SGC_F_CURRENT;
10515 	feature->add_length = 4;
10516 	feature->feature_data[0] = 0x00;
10517 	feature = (struct scsi_get_config_feature *)
10518 	    &feature->feature_data[feature->add_length];
10519 
10520 done:
10521 	data_len = (uint8_t *)feature - (uint8_t *)hdr;
10522 	if (rt == SGC_RT_SPECIFIC && data_len > 4) {
10523 		feature = (struct scsi_get_config_feature *)(hdr + 1);
10524 		if (scsi_2btoul(feature->feature_code) == starting)
10525 			feature = (struct scsi_get_config_feature *)
10526 			    &feature->feature_data[feature->add_length];
10527 		data_len = (uint8_t *)feature - (uint8_t *)hdr;
10528 	}
10529 	scsi_ulto4b(data_len - 4, hdr->data_length);
10530 	ctsio->kern_data_len = min(data_len, alloc_len);
10531 	ctsio->kern_total_len = ctsio->kern_data_len;
10532 
10533 	ctl_set_success(ctsio);
10534 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10535 	ctsio->be_move_done = ctl_config_move_done;
10536 	ctl_datamove((union ctl_io *)ctsio);
10537 	return (CTL_RETVAL_COMPLETE);
10538 }
10539 
10540 int
10541 ctl_get_event_status(struct ctl_scsiio *ctsio)
10542 {
10543 	struct scsi_get_event_status_header *hdr;
10544 	struct scsi_get_event_status *cdb;
10545 	uint32_t alloc_len, data_len;
10546 
10547 	cdb = (struct scsi_get_event_status *)ctsio->cdb;
10548 	if ((cdb->byte2 & SGESN_POLLED) == 0) {
10549 		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1, /*command*/ 1,
10550 		    /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
10551 		ctl_done((union ctl_io *)ctsio);
10552 		return (CTL_RETVAL_COMPLETE);
10553 	}
10554 	alloc_len = scsi_2btoul(cdb->length);
10555 
10556 	data_len = sizeof(struct scsi_get_event_status_header);
10557 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10558 	ctsio->kern_sg_entries = 0;
10559 	ctsio->kern_rel_offset = 0;
10560 	ctsio->kern_data_len = min(data_len, alloc_len);
10561 	ctsio->kern_total_len = ctsio->kern_data_len;
10562 
10563 	hdr = (struct scsi_get_event_status_header *)ctsio->kern_data_ptr;
10564 	scsi_ulto2b(0, hdr->descr_length);
10565 	hdr->nea_class = SGESN_NEA;
10566 	hdr->supported_class = 0;
10567 
10568 	ctl_set_success(ctsio);
10569 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10570 	ctsio->be_move_done = ctl_config_move_done;
10571 	ctl_datamove((union ctl_io *)ctsio);
10572 	return (CTL_RETVAL_COMPLETE);
10573 }
10574 
10575 int
10576 ctl_mechanism_status(struct ctl_scsiio *ctsio)
10577 {
10578 	struct scsi_mechanism_status_header *hdr;
10579 	struct scsi_mechanism_status *cdb;
10580 	uint32_t alloc_len, data_len;
10581 
10582 	cdb = (struct scsi_mechanism_status *)ctsio->cdb;
10583 	alloc_len = scsi_2btoul(cdb->length);
10584 
10585 	data_len = sizeof(struct scsi_mechanism_status_header);
10586 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10587 	ctsio->kern_sg_entries = 0;
10588 	ctsio->kern_rel_offset = 0;
10589 	ctsio->kern_data_len = min(data_len, alloc_len);
10590 	ctsio->kern_total_len = ctsio->kern_data_len;
10591 
10592 	hdr = (struct scsi_mechanism_status_header *)ctsio->kern_data_ptr;
10593 	hdr->state1 = 0x00;
10594 	hdr->state2 = 0xe0;
10595 	scsi_ulto3b(0, hdr->lba);
10596 	hdr->slots_num = 0;
10597 	scsi_ulto2b(0, hdr->slots_length);
10598 
10599 	ctl_set_success(ctsio);
10600 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10601 	ctsio->be_move_done = ctl_config_move_done;
10602 	ctl_datamove((union ctl_io *)ctsio);
10603 	return (CTL_RETVAL_COMPLETE);
10604 }
10605 
10606 static void
10607 ctl_ultomsf(uint32_t lba, uint8_t *buf)
10608 {
10609 
10610 	lba += 150;
10611 	buf[0] = 0;
10612 	buf[1] = bin2bcd((lba / 75) / 60);
10613 	buf[2] = bin2bcd((lba / 75) % 60);
10614 	buf[3] = bin2bcd(lba % 75);
10615 }
10616 
10617 int
10618 ctl_read_toc(struct ctl_scsiio *ctsio)
10619 {
10620 	struct ctl_lun *lun = CTL_LUN(ctsio);
10621 	struct scsi_read_toc_hdr *hdr;
10622 	struct scsi_read_toc_type01_descr *descr;
10623 	struct scsi_read_toc *cdb;
10624 	uint32_t alloc_len, data_len;
10625 	int format, msf;
10626 
10627 	cdb = (struct scsi_read_toc *)ctsio->cdb;
10628 	msf = (cdb->byte2 & CD_MSF) != 0;
10629 	format = cdb->format;
10630 	alloc_len = scsi_2btoul(cdb->data_len);
10631 
10632 	data_len = sizeof(struct scsi_read_toc_hdr);
10633 	if (format == 0)
10634 		data_len += 2 * sizeof(struct scsi_read_toc_type01_descr);
10635 	else
10636 		data_len += sizeof(struct scsi_read_toc_type01_descr);
10637 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10638 	ctsio->kern_sg_entries = 0;
10639 	ctsio->kern_rel_offset = 0;
10640 	ctsio->kern_data_len = min(data_len, alloc_len);
10641 	ctsio->kern_total_len = ctsio->kern_data_len;
10642 
10643 	hdr = (struct scsi_read_toc_hdr *)ctsio->kern_data_ptr;
10644 	if (format == 0) {
10645 		scsi_ulto2b(0x12, hdr->data_length);
10646 		hdr->first = 1;
10647 		hdr->last = 1;
10648 		descr = (struct scsi_read_toc_type01_descr *)(hdr + 1);
10649 		descr->addr_ctl = 0x14;
10650 		descr->track_number = 1;
10651 		if (msf)
10652 			ctl_ultomsf(0, descr->track_start);
10653 		else
10654 			scsi_ulto4b(0, descr->track_start);
10655 		descr++;
10656 		descr->addr_ctl = 0x14;
10657 		descr->track_number = 0xaa;
10658 		if (msf)
10659 			ctl_ultomsf(lun->be_lun->maxlba+1, descr->track_start);
10660 		else
10661 			scsi_ulto4b(lun->be_lun->maxlba+1, descr->track_start);
10662 	} else {
10663 		scsi_ulto2b(0x0a, hdr->data_length);
10664 		hdr->first = 1;
10665 		hdr->last = 1;
10666 		descr = (struct scsi_read_toc_type01_descr *)(hdr + 1);
10667 		descr->addr_ctl = 0x14;
10668 		descr->track_number = 1;
10669 		if (msf)
10670 			ctl_ultomsf(0, descr->track_start);
10671 		else
10672 			scsi_ulto4b(0, descr->track_start);
10673 	}
10674 
10675 	ctl_set_success(ctsio);
10676 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10677 	ctsio->be_move_done = ctl_config_move_done;
10678 	ctl_datamove((union ctl_io *)ctsio);
10679 	return (CTL_RETVAL_COMPLETE);
10680 }
10681 
10682 /*
10683  * For known CDB types, parse the LBA and length.
10684  */
10685 static int
10686 ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10687 {
10688 	if (io->io_hdr.io_type != CTL_IO_SCSI)
10689 		return (1);
10690 
10691 	switch (io->scsiio.cdb[0]) {
10692 	case COMPARE_AND_WRITE: {
10693 		struct scsi_compare_and_write *cdb;
10694 
10695 		cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10696 
10697 		*lba = scsi_8btou64(cdb->addr);
10698 		*len = cdb->length;
10699 		break;
10700 	}
10701 	case READ_6:
10702 	case WRITE_6: {
10703 		struct scsi_rw_6 *cdb;
10704 
10705 		cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10706 
10707 		*lba = scsi_3btoul(cdb->addr);
10708 		/* only 5 bits are valid in the most significant address byte */
10709 		*lba &= 0x1fffff;
10710 		*len = cdb->length;
10711 		break;
10712 	}
10713 	case READ_10:
10714 	case WRITE_10: {
10715 		struct scsi_rw_10 *cdb;
10716 
10717 		cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10718 
10719 		*lba = scsi_4btoul(cdb->addr);
10720 		*len = scsi_2btoul(cdb->length);
10721 		break;
10722 	}
10723 	case WRITE_VERIFY_10: {
10724 		struct scsi_write_verify_10 *cdb;
10725 
10726 		cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10727 
10728 		*lba = scsi_4btoul(cdb->addr);
10729 		*len = scsi_2btoul(cdb->length);
10730 		break;
10731 	}
10732 	case READ_12:
10733 	case WRITE_12: {
10734 		struct scsi_rw_12 *cdb;
10735 
10736 		cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10737 
10738 		*lba = scsi_4btoul(cdb->addr);
10739 		*len = scsi_4btoul(cdb->length);
10740 		break;
10741 	}
10742 	case WRITE_VERIFY_12: {
10743 		struct scsi_write_verify_12 *cdb;
10744 
10745 		cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10746 
10747 		*lba = scsi_4btoul(cdb->addr);
10748 		*len = scsi_4btoul(cdb->length);
10749 		break;
10750 	}
10751 	case READ_16:
10752 	case WRITE_16: {
10753 		struct scsi_rw_16 *cdb;
10754 
10755 		cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10756 
10757 		*lba = scsi_8btou64(cdb->addr);
10758 		*len = scsi_4btoul(cdb->length);
10759 		break;
10760 	}
10761 	case WRITE_ATOMIC_16: {
10762 		struct scsi_write_atomic_16 *cdb;
10763 
10764 		cdb = (struct scsi_write_atomic_16 *)io->scsiio.cdb;
10765 
10766 		*lba = scsi_8btou64(cdb->addr);
10767 		*len = scsi_2btoul(cdb->length);
10768 		break;
10769 	}
10770 	case WRITE_VERIFY_16: {
10771 		struct scsi_write_verify_16 *cdb;
10772 
10773 		cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10774 
10775 		*lba = scsi_8btou64(cdb->addr);
10776 		*len = scsi_4btoul(cdb->length);
10777 		break;
10778 	}
10779 	case WRITE_SAME_10: {
10780 		struct scsi_write_same_10 *cdb;
10781 
10782 		cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10783 
10784 		*lba = scsi_4btoul(cdb->addr);
10785 		*len = scsi_2btoul(cdb->length);
10786 		break;
10787 	}
10788 	case WRITE_SAME_16: {
10789 		struct scsi_write_same_16 *cdb;
10790 
10791 		cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10792 
10793 		*lba = scsi_8btou64(cdb->addr);
10794 		*len = scsi_4btoul(cdb->length);
10795 		break;
10796 	}
10797 	case VERIFY_10: {
10798 		struct scsi_verify_10 *cdb;
10799 
10800 		cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10801 
10802 		*lba = scsi_4btoul(cdb->addr);
10803 		*len = scsi_2btoul(cdb->length);
10804 		break;
10805 	}
10806 	case VERIFY_12: {
10807 		struct scsi_verify_12 *cdb;
10808 
10809 		cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10810 
10811 		*lba = scsi_4btoul(cdb->addr);
10812 		*len = scsi_4btoul(cdb->length);
10813 		break;
10814 	}
10815 	case VERIFY_16: {
10816 		struct scsi_verify_16 *cdb;
10817 
10818 		cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10819 
10820 		*lba = scsi_8btou64(cdb->addr);
10821 		*len = scsi_4btoul(cdb->length);
10822 		break;
10823 	}
10824 	case UNMAP: {
10825 		*lba = 0;
10826 		*len = UINT64_MAX;
10827 		break;
10828 	}
10829 	case SERVICE_ACTION_IN: {	/* GET LBA STATUS */
10830 		struct scsi_get_lba_status *cdb;
10831 
10832 		cdb = (struct scsi_get_lba_status *)io->scsiio.cdb;
10833 		*lba = scsi_8btou64(cdb->addr);
10834 		*len = UINT32_MAX;
10835 		break;
10836 	}
10837 	default:
10838 		return (1);
10839 		break; /* NOTREACHED */
10840 	}
10841 
10842 	return (0);
10843 }
10844 
10845 static ctl_action
10846 ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2,
10847     bool seq)
10848 {
10849 	uint64_t endlba1, endlba2;
10850 
10851 	endlba1 = lba1 + len1 - (seq ? 0 : 1);
10852 	endlba2 = lba2 + len2 - 1;
10853 
10854 	if ((endlba1 < lba2) || (endlba2 < lba1))
10855 		return (CTL_ACTION_PASS);
10856 	else
10857 		return (CTL_ACTION_BLOCK);
10858 }
10859 
10860 static int
10861 ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
10862 {
10863 	struct ctl_ptr_len_flags *ptrlen;
10864 	struct scsi_unmap_desc *buf, *end, *range;
10865 	uint64_t lba;
10866 	uint32_t len;
10867 
10868 	/* If not UNMAP -- go other way. */
10869 	if (io->io_hdr.io_type != CTL_IO_SCSI ||
10870 	    io->scsiio.cdb[0] != UNMAP)
10871 		return (CTL_ACTION_ERROR);
10872 
10873 	/* If UNMAP without data -- block and wait for data. */
10874 	ptrlen = (struct ctl_ptr_len_flags *)
10875 	    &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10876 	if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
10877 	    ptrlen->ptr == NULL)
10878 		return (CTL_ACTION_BLOCK);
10879 
10880 	/* UNMAP with data -- check for collision. */
10881 	buf = (struct scsi_unmap_desc *)ptrlen->ptr;
10882 	end = buf + ptrlen->len / sizeof(*buf);
10883 	for (range = buf; range < end; range++) {
10884 		lba = scsi_8btou64(range->lba);
10885 		len = scsi_4btoul(range->length);
10886 		if ((lba < lba2 + len2) && (lba + len > lba2))
10887 			return (CTL_ACTION_BLOCK);
10888 	}
10889 	return (CTL_ACTION_PASS);
10890 }
10891 
10892 static ctl_action
10893 ctl_extent_check(union ctl_io *io1, union ctl_io *io2, bool seq)
10894 {
10895 	uint64_t lba1, lba2;
10896 	uint64_t len1, len2;
10897 	int retval;
10898 
10899 	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10900 		return (CTL_ACTION_ERROR);
10901 
10902 	retval = ctl_extent_check_unmap(io1, lba2, len2);
10903 	if (retval != CTL_ACTION_ERROR)
10904 		return (retval);
10905 
10906 	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10907 		return (CTL_ACTION_ERROR);
10908 
10909 	if (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE)
10910 		seq = FALSE;
10911 	return (ctl_extent_check_lba(lba1, len1, lba2, len2, seq));
10912 }
10913 
10914 static ctl_action
10915 ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2)
10916 {
10917 	uint64_t lba1, lba2;
10918 	uint64_t len1, len2;
10919 
10920 	if (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE)
10921 		return (CTL_ACTION_PASS);
10922 	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10923 		return (CTL_ACTION_ERROR);
10924 	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10925 		return (CTL_ACTION_ERROR);
10926 
10927 	if (lba1 + len1 == lba2)
10928 		return (CTL_ACTION_BLOCK);
10929 	return (CTL_ACTION_PASS);
10930 }
10931 
10932 static ctl_action
10933 ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
10934     union ctl_io *ooa_io)
10935 {
10936 	const struct ctl_cmd_entry *pending_entry, *ooa_entry;
10937 	const ctl_serialize_action *serialize_row;
10938 
10939 	/*
10940 	 * Aborted commands are not going to be executed and may even
10941 	 * not report completion, so we don't care about their order.
10942 	 * Let them complete ASAP to clean the OOA queue.
10943 	 */
10944 	if (pending_io->io_hdr.flags & CTL_FLAG_ABORT)
10945 		return (CTL_ACTION_SKIP);
10946 
10947 	/*
10948 	 * The initiator attempted multiple untagged commands at the same
10949 	 * time.  Can't do that.
10950 	 */
10951 	if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10952 	 && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10953 	 && ((pending_io->io_hdr.nexus.targ_port ==
10954 	      ooa_io->io_hdr.nexus.targ_port)
10955 	  && (pending_io->io_hdr.nexus.initid ==
10956 	      ooa_io->io_hdr.nexus.initid))
10957 	 && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
10958 	      CTL_FLAG_STATUS_SENT)) == 0))
10959 		return (CTL_ACTION_OVERLAP);
10960 
10961 	/*
10962 	 * The initiator attempted to send multiple tagged commands with
10963 	 * the same ID.  (It's fine if different initiators have the same
10964 	 * tag ID.)
10965 	 *
10966 	 * Even if all of those conditions are true, we don't kill the I/O
10967 	 * if the command ahead of us has been aborted.  We won't end up
10968 	 * sending it to the FETD, and it's perfectly legal to resend a
10969 	 * command with the same tag number as long as the previous
10970 	 * instance of this tag number has been aborted somehow.
10971 	 */
10972 	if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10973 	 && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10974 	 && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
10975 	 && ((pending_io->io_hdr.nexus.targ_port ==
10976 	      ooa_io->io_hdr.nexus.targ_port)
10977 	  && (pending_io->io_hdr.nexus.initid ==
10978 	      ooa_io->io_hdr.nexus.initid))
10979 	 && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
10980 	      CTL_FLAG_STATUS_SENT)) == 0))
10981 		return (CTL_ACTION_OVERLAP_TAG);
10982 
10983 	/*
10984 	 * If we get a head of queue tag, SAM-3 says that we should
10985 	 * immediately execute it.
10986 	 *
10987 	 * What happens if this command would normally block for some other
10988 	 * reason?  e.g. a request sense with a head of queue tag
10989 	 * immediately after a write.  Normally that would block, but this
10990 	 * will result in its getting executed immediately...
10991 	 *
10992 	 * We currently return "pass" instead of "skip", so we'll end up
10993 	 * going through the rest of the queue to check for overlapped tags.
10994 	 *
10995 	 * XXX KDM check for other types of blockage first??
10996 	 */
10997 	if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10998 		return (CTL_ACTION_PASS);
10999 
11000 	/*
11001 	 * Ordered tags have to block until all items ahead of them
11002 	 * have completed.  If we get called with an ordered tag, we always
11003 	 * block, if something else is ahead of us in the queue.
11004 	 */
11005 	if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
11006 		return (CTL_ACTION_BLOCK);
11007 
11008 	/*
11009 	 * Simple tags get blocked until all head of queue and ordered tags
11010 	 * ahead of them have completed.  I'm lumping untagged commands in
11011 	 * with simple tags here.  XXX KDM is that the right thing to do?
11012 	 */
11013 	if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
11014 	  || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
11015 	 && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
11016 	  || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
11017 		return (CTL_ACTION_BLOCK);
11018 
11019 	pending_entry = ctl_get_cmd_entry(&pending_io->scsiio, NULL);
11020 	KASSERT(pending_entry->seridx < CTL_SERIDX_COUNT,
11021 	    ("%s: Invalid seridx %d for pending CDB %02x %02x @ %p",
11022 	     __func__, pending_entry->seridx, pending_io->scsiio.cdb[0],
11023 	     pending_io->scsiio.cdb[1], pending_io));
11024 	ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio, NULL);
11025 	if (ooa_entry->seridx == CTL_SERIDX_INVLD)
11026 		return (CTL_ACTION_PASS); /* Unsupported command in OOA queue */
11027 	KASSERT(ooa_entry->seridx < CTL_SERIDX_COUNT,
11028 	    ("%s: Invalid seridx %d for ooa CDB %02x %02x @ %p",
11029 	     __func__, ooa_entry->seridx, ooa_io->scsiio.cdb[0],
11030 	     ooa_io->scsiio.cdb[1], ooa_io));
11031 
11032 	serialize_row = ctl_serialize_table[ooa_entry->seridx];
11033 
11034 	switch (serialize_row[pending_entry->seridx]) {
11035 	case CTL_SER_BLOCK:
11036 		return (CTL_ACTION_BLOCK);
11037 	case CTL_SER_EXTENT:
11038 		return (ctl_extent_check(ooa_io, pending_io,
11039 		    (lun->be_lun && lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
11040 	case CTL_SER_EXTENTOPT:
11041 		if ((lun->MODE_CTRL.queue_flags & SCP_QUEUE_ALG_MASK) !=
11042 		    SCP_QUEUE_ALG_UNRESTRICTED)
11043 			return (ctl_extent_check(ooa_io, pending_io,
11044 			    (lun->be_lun &&
11045 			     lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
11046 		return (CTL_ACTION_PASS);
11047 	case CTL_SER_EXTENTSEQ:
11048 		if (lun->be_lun && lun->be_lun->serseq != CTL_LUN_SERSEQ_OFF)
11049 			return (ctl_extent_check_seq(ooa_io, pending_io));
11050 		return (CTL_ACTION_PASS);
11051 	case CTL_SER_PASS:
11052 		return (CTL_ACTION_PASS);
11053 	case CTL_SER_BLOCKOPT:
11054 		if ((lun->MODE_CTRL.queue_flags & SCP_QUEUE_ALG_MASK) !=
11055 		    SCP_QUEUE_ALG_UNRESTRICTED)
11056 			return (CTL_ACTION_BLOCK);
11057 		return (CTL_ACTION_PASS);
11058 	case CTL_SER_SKIP:
11059 		return (CTL_ACTION_SKIP);
11060 	default:
11061 		panic("%s: Invalid serialization value %d for %d => %d",
11062 		    __func__, serialize_row[pending_entry->seridx],
11063 		    pending_entry->seridx, ooa_entry->seridx);
11064 	}
11065 
11066 	return (CTL_ACTION_ERROR);
11067 }
11068 
11069 /*
11070  * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
11071  * Assumptions:
11072  * - pending_io is generally either incoming, or on the blocked queue
11073  * - starting I/O is the I/O we want to start the check with.
11074  */
11075 static ctl_action
11076 ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
11077 	      union ctl_io **starting_io)
11078 {
11079 	union ctl_io *ooa_io;
11080 	ctl_action action;
11081 
11082 	mtx_assert(&lun->lun_lock, MA_OWNED);
11083 
11084 	/*
11085 	 * Run back along the OOA queue, starting with the current
11086 	 * blocked I/O and going through every I/O before it on the
11087 	 * queue.  If starting_io is NULL, we'll just end up returning
11088 	 * CTL_ACTION_PASS.
11089 	 */
11090 	for (ooa_io = *starting_io; ooa_io != NULL;
11091 	     ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
11092 	     ooa_links)){
11093 		action = ctl_check_for_blockage(lun, pending_io, ooa_io);
11094 		if (action != CTL_ACTION_PASS) {
11095 			*starting_io = ooa_io;
11096 			return (action);
11097 		}
11098 	}
11099 
11100 	*starting_io = NULL;
11101 	return (CTL_ACTION_PASS);
11102 }
11103 
11104 /*
11105  * Try to unblock the specified I/O.
11106  *
11107  * skip parameter allows explicitly skip present blocker of the I/O,
11108  * starting from the previous one on OOA queue.  It can be used when
11109  * we know for sure that the blocker I/O does no longer count.
11110  */
11111 static void
11112 ctl_try_unblock_io(struct ctl_lun *lun, union ctl_io *io, bool skip)
11113 {
11114 	struct ctl_softc *softc = lun->ctl_softc;
11115 	union ctl_io *bio, *obio;
11116 	const struct ctl_cmd_entry *entry;
11117 	union ctl_ha_msg msg_info;
11118 	ctl_action action;
11119 
11120 	mtx_assert(&lun->lun_lock, MA_OWNED);
11121 
11122 	if (io->io_hdr.blocker == NULL)
11123 		return;
11124 
11125 	obio = bio = io->io_hdr.blocker;
11126 	if (skip)
11127 		bio = (union ctl_io *)TAILQ_PREV(&bio->io_hdr, ctl_ooaq,
11128 		    ooa_links);
11129 	action = ctl_check_ooa(lun, io, &bio);
11130 	if (action == CTL_ACTION_BLOCK) {
11131 		/* Still blocked, but may be by different I/O now. */
11132 		if (bio != obio) {
11133 			TAILQ_REMOVE(&obio->io_hdr.blocked_queue,
11134 			    &io->io_hdr, blocked_links);
11135 			TAILQ_INSERT_TAIL(&bio->io_hdr.blocked_queue,
11136 			    &io->io_hdr, blocked_links);
11137 			io->io_hdr.blocker = bio;
11138 		}
11139 		return;
11140 	}
11141 
11142 	/* No longer blocked, one way or another. */
11143 	TAILQ_REMOVE(&obio->io_hdr.blocked_queue, &io->io_hdr, blocked_links);
11144 	io->io_hdr.blocker = NULL;
11145 
11146 	switch (action) {
11147 	case CTL_ACTION_OVERLAP:
11148 		ctl_set_overlapped_cmd(&io->scsiio);
11149 		goto error;
11150 	case CTL_ACTION_OVERLAP_TAG:
11151 		ctl_set_overlapped_tag(&io->scsiio,
11152 		    io->scsiio.tag_num & 0xff);
11153 		goto error;
11154 	case CTL_ACTION_PASS:
11155 	case CTL_ACTION_SKIP:
11156 
11157 		/* Serializing commands from the other SC retire there. */
11158 		if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) &&
11159 		    (softc->ha_mode != CTL_HA_MODE_XFER)) {
11160 			io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11161 			msg_info.hdr.original_sc = io->io_hdr.remote_io;
11162 			msg_info.hdr.serializing_sc = io;
11163 			msg_info.hdr.msg_type = CTL_MSG_R2R;
11164 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11165 			    sizeof(msg_info.hdr), M_NOWAIT);
11166 			break;
11167 		}
11168 
11169 		/*
11170 		 * Check this I/O for LUN state changes that may have happened
11171 		 * while this command was blocked. The LUN state may have been
11172 		 * changed by a command ahead of us in the queue.
11173 		 */
11174 		entry = ctl_get_cmd_entry(&io->scsiio, NULL);
11175 		if (ctl_scsiio_lun_check(lun, entry, &io->scsiio) != 0) {
11176 			ctl_done(io);
11177 			break;
11178 		}
11179 
11180 		io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11181 		ctl_enqueue_rtr(io);
11182 		break;
11183 	case CTL_ACTION_ERROR:
11184 	default:
11185 		ctl_set_internal_failure(&io->scsiio,
11186 					 /*sks_valid*/ 0,
11187 					 /*retry_count*/ 0);
11188 
11189 error:
11190 		/* Serializing commands from the other SC are done here. */
11191 		if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) &&
11192 		    (softc->ha_mode != CTL_HA_MODE_XFER)) {
11193 			ctl_try_unblock_others(lun, io, TRUE);
11194 			TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
11195 
11196 			ctl_copy_sense_data_back(io, &msg_info);
11197 			msg_info.hdr.original_sc = io->io_hdr.remote_io;
11198 			msg_info.hdr.serializing_sc = NULL;
11199 			msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
11200 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11201 			    sizeof(msg_info.scsi), M_WAITOK);
11202 			ctl_free_io(io);
11203 			break;
11204 		}
11205 
11206 		ctl_done(io);
11207 		break;
11208 	}
11209 }
11210 
11211 /*
11212  * Try to unblock I/Os blocked by the specified I/O.
11213  *
11214  * skip parameter allows explicitly skip the specified I/O as blocker,
11215  * starting from the previous one on the OOA queue.  It can be used when
11216  * we know for sure that the specified I/O does no longer count (done).
11217  * It has to be still on OOA queue though so that we know where to start.
11218  */
11219 static void
11220 ctl_try_unblock_others(struct ctl_lun *lun, union ctl_io *bio, bool skip)
11221 {
11222 	union ctl_io *io, *next_io;
11223 
11224 	mtx_assert(&lun->lun_lock, MA_OWNED);
11225 
11226 	for (io = (union ctl_io *)TAILQ_FIRST(&bio->io_hdr.blocked_queue);
11227 	     io != NULL; io = next_io) {
11228 		next_io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr, blocked_links);
11229 
11230 		KASSERT(io->io_hdr.blocker != NULL,
11231 		    ("I/O %p on blocked list without blocker", io));
11232 		ctl_try_unblock_io(lun, io, skip);
11233 	}
11234 	KASSERT(!skip || TAILQ_EMPTY(&bio->io_hdr.blocked_queue),
11235 	    ("blocked_queue is not empty after skipping %p", bio));
11236 }
11237 
11238 /*
11239  * This routine (with one exception) checks LUN flags that can be set by
11240  * commands ahead of us in the OOA queue.  These flags have to be checked
11241  * when a command initially comes in, and when we pull a command off the
11242  * blocked queue and are preparing to execute it.  The reason we have to
11243  * check these flags for commands on the blocked queue is that the LUN
11244  * state may have been changed by a command ahead of us while we're on the
11245  * blocked queue.
11246  *
11247  * Ordering is somewhat important with these checks, so please pay
11248  * careful attention to the placement of any new checks.
11249  */
11250 static int
11251 ctl_scsiio_lun_check(struct ctl_lun *lun,
11252     const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11253 {
11254 	struct ctl_softc *softc = lun->ctl_softc;
11255 	int retval;
11256 	uint32_t residx;
11257 
11258 	retval = 0;
11259 
11260 	mtx_assert(&lun->lun_lock, MA_OWNED);
11261 
11262 	/*
11263 	 * If this shelf is a secondary shelf controller, we may have to
11264 	 * reject some commands disallowed by HA mode and link state.
11265 	 */
11266 	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11267 		if (softc->ha_link == CTL_HA_LINK_OFFLINE &&
11268 		    (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11269 			ctl_set_lun_unavail(ctsio);
11270 			retval = 1;
11271 			goto bailout;
11272 		}
11273 		if ((lun->flags & CTL_LUN_PEER_SC_PRIMARY) == 0 &&
11274 		    (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11275 			ctl_set_lun_transit(ctsio);
11276 			retval = 1;
11277 			goto bailout;
11278 		}
11279 		if (softc->ha_mode == CTL_HA_MODE_ACT_STBY &&
11280 		    (entry->flags & CTL_CMD_FLAG_OK_ON_STANDBY) == 0) {
11281 			ctl_set_lun_standby(ctsio);
11282 			retval = 1;
11283 			goto bailout;
11284 		}
11285 
11286 		/* The rest of checks are only done on executing side */
11287 		if (softc->ha_mode == CTL_HA_MODE_XFER)
11288 			goto bailout;
11289 	}
11290 
11291 	if (entry->pattern & CTL_LUN_PAT_WRITE) {
11292 		if (lun->be_lun &&
11293 		    lun->be_lun->flags & CTL_LUN_FLAG_READONLY) {
11294 			ctl_set_hw_write_protected(ctsio);
11295 			retval = 1;
11296 			goto bailout;
11297 		}
11298 		if ((lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0) {
11299 			ctl_set_sense(ctsio, /*current_error*/ 1,
11300 			    /*sense_key*/ SSD_KEY_DATA_PROTECT,
11301 			    /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
11302 			retval = 1;
11303 			goto bailout;
11304 		}
11305 	}
11306 
11307 	/*
11308 	 * Check for a reservation conflict.  If this command isn't allowed
11309 	 * even on reserved LUNs, and if this initiator isn't the one who
11310 	 * reserved us, reject the command with a reservation conflict.
11311 	 */
11312 	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11313 	if ((lun->flags & CTL_LUN_RESERVED)
11314 	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11315 		if (lun->res_idx != residx) {
11316 			ctl_set_reservation_conflict(ctsio);
11317 			retval = 1;
11318 			goto bailout;
11319 		}
11320 	}
11321 
11322 	if ((lun->flags & CTL_LUN_PR_RESERVED) == 0 ||
11323 	    (entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV)) {
11324 		/* No reservation or command is allowed. */;
11325 	} else if ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_WRESV) &&
11326 	    (lun->pr_res_type == SPR_TYPE_WR_EX ||
11327 	     lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
11328 	     lun->pr_res_type == SPR_TYPE_WR_EX_AR)) {
11329 		/* The command is allowed for Write Exclusive resv. */;
11330 	} else {
11331 		/*
11332 		 * if we aren't registered or it's a res holder type
11333 		 * reservation and this isn't the res holder then set a
11334 		 * conflict.
11335 		 */
11336 		if (ctl_get_prkey(lun, residx) == 0 ||
11337 		    (residx != lun->pr_res_idx && lun->pr_res_type < 4)) {
11338 			ctl_set_reservation_conflict(ctsio);
11339 			retval = 1;
11340 			goto bailout;
11341 		}
11342 	}
11343 
11344 	if ((entry->flags & CTL_CMD_FLAG_OK_ON_NO_MEDIA) == 0) {
11345 		if (lun->flags & CTL_LUN_EJECTED)
11346 			ctl_set_lun_ejected(ctsio);
11347 		else if (lun->flags & CTL_LUN_NO_MEDIA) {
11348 			if (lun->flags & CTL_LUN_REMOVABLE)
11349 				ctl_set_lun_no_media(ctsio);
11350 			else
11351 				ctl_set_lun_int_reqd(ctsio);
11352 		} else if (lun->flags & CTL_LUN_STOPPED)
11353 			ctl_set_lun_stopped(ctsio);
11354 		else
11355 			goto bailout;
11356 		retval = 1;
11357 		goto bailout;
11358 	}
11359 
11360 bailout:
11361 	return (retval);
11362 }
11363 
11364 static void
11365 ctl_failover_io(union ctl_io *io, int have_lock)
11366 {
11367 	ctl_set_busy(&io->scsiio);
11368 	ctl_done(io);
11369 }
11370 
11371 static void
11372 ctl_failover_lun(union ctl_io *rio)
11373 {
11374 	struct ctl_softc *softc = CTL_SOFTC(rio);
11375 	struct ctl_lun *lun;
11376 	struct ctl_io_hdr *io, *next_io;
11377 	uint32_t targ_lun;
11378 
11379 	targ_lun = rio->io_hdr.nexus.targ_mapped_lun;
11380 	CTL_DEBUG_PRINT(("FAILOVER for lun %u\n", targ_lun));
11381 
11382 	/* Find and lock the LUN. */
11383 	mtx_lock(&softc->ctl_lock);
11384 	if (targ_lun > ctl_max_luns ||
11385 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11386 		mtx_unlock(&softc->ctl_lock);
11387 		return;
11388 	}
11389 	mtx_lock(&lun->lun_lock);
11390 	mtx_unlock(&softc->ctl_lock);
11391 	if (lun->flags & CTL_LUN_DISABLED) {
11392 		mtx_unlock(&lun->lun_lock);
11393 		return;
11394 	}
11395 
11396 	if (softc->ha_mode == CTL_HA_MODE_XFER) {
11397 		TAILQ_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11398 			/* We are master */
11399 			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11400 				if (io->flags & CTL_FLAG_IO_ACTIVE) {
11401 					io->flags |= CTL_FLAG_ABORT;
11402 					io->flags |= CTL_FLAG_FAILOVER;
11403 					ctl_try_unblock_io(lun,
11404 					    (union ctl_io *)io, FALSE);
11405 				} else { /* This can be only due to DATAMOVE */
11406 					io->msg_type = CTL_MSG_DATAMOVE_DONE;
11407 					io->flags &= ~CTL_FLAG_DMA_INPROG;
11408 					io->flags |= CTL_FLAG_IO_ACTIVE;
11409 					io->port_status = 31340;
11410 					ctl_enqueue_isc((union ctl_io *)io);
11411 				}
11412 			} else
11413 			/* We are slave */
11414 			if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11415 				io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11416 				if (io->flags & CTL_FLAG_IO_ACTIVE) {
11417 					io->flags |= CTL_FLAG_FAILOVER;
11418 				} else {
11419 					ctl_set_busy(&((union ctl_io *)io)->
11420 					    scsiio);
11421 					ctl_done((union ctl_io *)io);
11422 				}
11423 			}
11424 		}
11425 	} else { /* SERIALIZE modes */
11426 		TAILQ_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11427 			/* We are master */
11428 			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11429 				if (io->blocker != NULL) {
11430 					TAILQ_REMOVE(&io->blocker->io_hdr.blocked_queue,
11431 					    io, blocked_links);
11432 					io->blocker = NULL;
11433 				}
11434 				ctl_try_unblock_others(lun, (union ctl_io *)io,
11435 				    TRUE);
11436 				TAILQ_REMOVE(&lun->ooa_queue, io, ooa_links);
11437 				ctl_free_io((union ctl_io *)io);
11438 			} else
11439 			/* We are slave */
11440 			if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11441 				io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11442 				if (!(io->flags & CTL_FLAG_IO_ACTIVE)) {
11443 					ctl_set_busy(&((union ctl_io *)io)->
11444 					    scsiio);
11445 					ctl_done((union ctl_io *)io);
11446 				}
11447 			}
11448 		}
11449 	}
11450 	mtx_unlock(&lun->lun_lock);
11451 }
11452 
11453 static int
11454 ctl_scsiio_precheck(struct ctl_softc *softc, struct ctl_scsiio *ctsio)
11455 {
11456 	struct ctl_lun *lun;
11457 	const struct ctl_cmd_entry *entry;
11458 	union ctl_io *bio;
11459 	uint32_t initidx, targ_lun;
11460 	int retval = 0;
11461 
11462 	lun = NULL;
11463 	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11464 	if (targ_lun < ctl_max_luns)
11465 		lun = softc->ctl_luns[targ_lun];
11466 	if (lun) {
11467 		/*
11468 		 * If the LUN is invalid, pretend that it doesn't exist.
11469 		 * It will go away as soon as all pending I/O has been
11470 		 * completed.
11471 		 */
11472 		mtx_lock(&lun->lun_lock);
11473 		if (lun->flags & CTL_LUN_DISABLED) {
11474 			mtx_unlock(&lun->lun_lock);
11475 			lun = NULL;
11476 		}
11477 	}
11478 	CTL_LUN(ctsio) = lun;
11479 	if (lun) {
11480 		CTL_BACKEND_LUN(ctsio) = lun->be_lun;
11481 
11482 		/*
11483 		 * Every I/O goes into the OOA queue for a particular LUN,
11484 		 * and stays there until completion.
11485 		 */
11486 #ifdef CTL_TIME_IO
11487 		if (TAILQ_EMPTY(&lun->ooa_queue))
11488 			lun->idle_time += getsbinuptime() - lun->last_busy;
11489 #endif
11490 		TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
11491 	}
11492 
11493 	/* Get command entry and return error if it is unsuppotyed. */
11494 	entry = ctl_validate_command(ctsio);
11495 	if (entry == NULL) {
11496 		if (lun)
11497 			mtx_unlock(&lun->lun_lock);
11498 		return (retval);
11499 	}
11500 
11501 	ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11502 	ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11503 
11504 	/*
11505 	 * Check to see whether we can send this command to LUNs that don't
11506 	 * exist.  This should pretty much only be the case for inquiry
11507 	 * and request sense.  Further checks, below, really require having
11508 	 * a LUN, so we can't really check the command anymore.  Just put
11509 	 * it on the rtr queue.
11510 	 */
11511 	if (lun == NULL) {
11512 		if (entry->flags & CTL_CMD_FLAG_OK_ON_NO_LUN) {
11513 			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11514 			ctl_enqueue_rtr((union ctl_io *)ctsio);
11515 			return (retval);
11516 		}
11517 
11518 		ctl_set_unsupported_lun(ctsio);
11519 		ctl_done((union ctl_io *)ctsio);
11520 		CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11521 		return (retval);
11522 	} else {
11523 		/*
11524 		 * Make sure we support this particular command on this LUN.
11525 		 * e.g., we don't support writes to the control LUN.
11526 		 */
11527 		if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11528 			mtx_unlock(&lun->lun_lock);
11529 			ctl_set_invalid_opcode(ctsio);
11530 			ctl_done((union ctl_io *)ctsio);
11531 			return (retval);
11532 		}
11533 	}
11534 
11535 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11536 
11537 	/*
11538 	 * If we've got a request sense, it'll clear the contingent
11539 	 * allegiance condition.  Otherwise, if we have a CA condition for
11540 	 * this initiator, clear it, because it sent down a command other
11541 	 * than request sense.
11542 	 */
11543 	if (ctsio->cdb[0] != REQUEST_SENSE) {
11544 		struct scsi_sense_data *ps;
11545 
11546 		ps = lun->pending_sense[initidx / CTL_MAX_INIT_PER_PORT];
11547 		if (ps != NULL)
11548 			ps[initidx % CTL_MAX_INIT_PER_PORT].error_code = 0;
11549 	}
11550 
11551 	/*
11552 	 * If the command has this flag set, it handles its own unit
11553 	 * attention reporting, we shouldn't do anything.  Otherwise we
11554 	 * check for any pending unit attentions, and send them back to the
11555 	 * initiator.  We only do this when a command initially comes in,
11556 	 * not when we pull it off the blocked queue.
11557 	 *
11558 	 * According to SAM-3, section 5.3.2, the order that things get
11559 	 * presented back to the host is basically unit attentions caused
11560 	 * by some sort of reset event, busy status, reservation conflicts
11561 	 * or task set full, and finally any other status.
11562 	 *
11563 	 * One issue here is that some of the unit attentions we report
11564 	 * don't fall into the "reset" category (e.g. "reported luns data
11565 	 * has changed").  So reporting it here, before the reservation
11566 	 * check, may be technically wrong.  I guess the only thing to do
11567 	 * would be to check for and report the reset events here, and then
11568 	 * check for the other unit attention types after we check for a
11569 	 * reservation conflict.
11570 	 *
11571 	 * XXX KDM need to fix this
11572 	 */
11573 	if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11574 		ctl_ua_type ua_type;
11575 		u_int sense_len = 0;
11576 
11577 		ua_type = ctl_build_ua(lun, initidx, &ctsio->sense_data,
11578 		    &sense_len, SSD_TYPE_NONE);
11579 		if (ua_type != CTL_UA_NONE) {
11580 			mtx_unlock(&lun->lun_lock);
11581 			ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11582 			ctsio->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
11583 			ctsio->sense_len = sense_len;
11584 			ctl_done((union ctl_io *)ctsio);
11585 			return (retval);
11586 		}
11587 	}
11588 
11589 
11590 	if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
11591 		mtx_unlock(&lun->lun_lock);
11592 		ctl_done((union ctl_io *)ctsio);
11593 		return (retval);
11594 	}
11595 
11596 	/*
11597 	 * XXX CHD this is where we want to send IO to other side if
11598 	 * this LUN is secondary on this SC. We will need to make a copy
11599 	 * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11600 	 * the copy we send as FROM_OTHER.
11601 	 * We also need to stuff the address of the original IO so we can
11602 	 * find it easily. Something similar will need be done on the other
11603 	 * side so when we are done we can find the copy.
11604 	 */
11605 	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
11606 	    (lun->flags & CTL_LUN_PEER_SC_PRIMARY) != 0 &&
11607 	    (entry->flags & CTL_CMD_FLAG_RUN_HERE) == 0) {
11608 		union ctl_ha_msg msg_info;
11609 		int isc_retval;
11610 
11611 		ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11612 		ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11613 		mtx_unlock(&lun->lun_lock);
11614 
11615 		msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11616 		msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11617 		msg_info.hdr.serializing_sc = NULL;
11618 		msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11619 		msg_info.scsi.tag_num = ctsio->tag_num;
11620 		msg_info.scsi.tag_type = ctsio->tag_type;
11621 		msg_info.scsi.cdb_len = ctsio->cdb_len;
11622 		memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11623 
11624 		if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11625 		    sizeof(msg_info.scsi) - sizeof(msg_info.scsi.sense_data),
11626 		    M_WAITOK)) > CTL_HA_STATUS_SUCCESS) {
11627 			ctl_set_busy(ctsio);
11628 			ctl_done((union ctl_io *)ctsio);
11629 			return (retval);
11630 		}
11631 		return (retval);
11632 	}
11633 
11634 	bio = (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq, ooa_links);
11635 	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio, &bio)) {
11636 	case CTL_ACTION_BLOCK:
11637 		ctsio->io_hdr.blocker = bio;
11638 		TAILQ_INSERT_TAIL(&bio->io_hdr.blocked_queue, &ctsio->io_hdr,
11639 				  blocked_links);
11640 		mtx_unlock(&lun->lun_lock);
11641 		return (retval);
11642 	case CTL_ACTION_PASS:
11643 	case CTL_ACTION_SKIP:
11644 		ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11645 		mtx_unlock(&lun->lun_lock);
11646 		ctl_enqueue_rtr((union ctl_io *)ctsio);
11647 		break;
11648 	case CTL_ACTION_OVERLAP:
11649 		mtx_unlock(&lun->lun_lock);
11650 		ctl_set_overlapped_cmd(ctsio);
11651 		ctl_done((union ctl_io *)ctsio);
11652 		break;
11653 	case CTL_ACTION_OVERLAP_TAG:
11654 		mtx_unlock(&lun->lun_lock);
11655 		ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11656 		ctl_done((union ctl_io *)ctsio);
11657 		break;
11658 	case CTL_ACTION_ERROR:
11659 	default:
11660 		mtx_unlock(&lun->lun_lock);
11661 		ctl_set_internal_failure(ctsio,
11662 					 /*sks_valid*/ 0,
11663 					 /*retry_count*/ 0);
11664 		ctl_done((union ctl_io *)ctsio);
11665 		break;
11666 	}
11667 	return (retval);
11668 }
11669 
11670 const struct ctl_cmd_entry *
11671 ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11672 {
11673 	const struct ctl_cmd_entry *entry;
11674 	int service_action;
11675 
11676 	entry = &ctl_cmd_table[ctsio->cdb[0]];
11677 	if (sa)
11678 		*sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11679 	if (entry->flags & CTL_CMD_FLAG_SA5) {
11680 		service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11681 		entry = &((const struct ctl_cmd_entry *)
11682 		    entry->execute)[service_action];
11683 	}
11684 	return (entry);
11685 }
11686 
11687 const struct ctl_cmd_entry *
11688 ctl_validate_command(struct ctl_scsiio *ctsio)
11689 {
11690 	const struct ctl_cmd_entry *entry;
11691 	int i, sa;
11692 	uint8_t diff;
11693 
11694 	entry = ctl_get_cmd_entry(ctsio, &sa);
11695 	if (entry->execute == NULL) {
11696 		if (sa)
11697 			ctl_set_invalid_field(ctsio,
11698 					      /*sks_valid*/ 1,
11699 					      /*command*/ 1,
11700 					      /*field*/ 1,
11701 					      /*bit_valid*/ 1,
11702 					      /*bit*/ 4);
11703 		else
11704 			ctl_set_invalid_opcode(ctsio);
11705 		ctl_done((union ctl_io *)ctsio);
11706 		return (NULL);
11707 	}
11708 	KASSERT(entry->length > 0,
11709 	    ("Not defined length for command 0x%02x/0x%02x",
11710 	     ctsio->cdb[0], ctsio->cdb[1]));
11711 	for (i = 1; i < entry->length; i++) {
11712 		diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11713 		if (diff == 0)
11714 			continue;
11715 		ctl_set_invalid_field(ctsio,
11716 				      /*sks_valid*/ 1,
11717 				      /*command*/ 1,
11718 				      /*field*/ i,
11719 				      /*bit_valid*/ 1,
11720 				      /*bit*/ fls(diff) - 1);
11721 		ctl_done((union ctl_io *)ctsio);
11722 		return (NULL);
11723 	}
11724 	return (entry);
11725 }
11726 
11727 static int
11728 ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11729 {
11730 
11731 	switch (lun_type) {
11732 	case T_DIRECT:
11733 		if ((entry->flags & CTL_CMD_FLAG_OK_ON_DIRECT) == 0)
11734 			return (0);
11735 		break;
11736 	case T_PROCESSOR:
11737 		if ((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0)
11738 			return (0);
11739 		break;
11740 	case T_CDROM:
11741 		if ((entry->flags & CTL_CMD_FLAG_OK_ON_CDROM) == 0)
11742 			return (0);
11743 		break;
11744 	default:
11745 		return (0);
11746 	}
11747 	return (1);
11748 }
11749 
11750 static int
11751 ctl_scsiio(struct ctl_scsiio *ctsio)
11752 {
11753 	int retval;
11754 	const struct ctl_cmd_entry *entry;
11755 
11756 	retval = CTL_RETVAL_COMPLETE;
11757 
11758 	CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11759 
11760 	entry = ctl_get_cmd_entry(ctsio, NULL);
11761 
11762 	/*
11763 	 * If this I/O has been aborted, just send it straight to
11764 	 * ctl_done() without executing it.
11765 	 */
11766 	if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11767 		ctl_done((union ctl_io *)ctsio);
11768 		goto bailout;
11769 	}
11770 
11771 	/*
11772 	 * All the checks should have been handled by ctl_scsiio_precheck().
11773 	 * We should be clear now to just execute the I/O.
11774 	 */
11775 	retval = entry->execute(ctsio);
11776 
11777 bailout:
11778 	return (retval);
11779 }
11780 
11781 static int
11782 ctl_target_reset(union ctl_io *io)
11783 {
11784 	struct ctl_softc *softc = CTL_SOFTC(io);
11785 	struct ctl_port *port = CTL_PORT(io);
11786 	struct ctl_lun *lun;
11787 	uint32_t initidx;
11788 	ctl_ua_type ua_type;
11789 
11790 	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11791 		union ctl_ha_msg msg_info;
11792 
11793 		msg_info.hdr.nexus = io->io_hdr.nexus;
11794 		msg_info.task.task_action = io->taskio.task_action;
11795 		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11796 		msg_info.hdr.original_sc = NULL;
11797 		msg_info.hdr.serializing_sc = NULL;
11798 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11799 		    sizeof(msg_info.task), M_WAITOK);
11800 	}
11801 
11802 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
11803 	if (io->taskio.task_action == CTL_TASK_TARGET_RESET)
11804 		ua_type = CTL_UA_TARG_RESET;
11805 	else
11806 		ua_type = CTL_UA_BUS_RESET;
11807 	mtx_lock(&softc->ctl_lock);
11808 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
11809 		if (port != NULL &&
11810 		    ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
11811 			continue;
11812 		ctl_do_lun_reset(lun, initidx, ua_type);
11813 	}
11814 	mtx_unlock(&softc->ctl_lock);
11815 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11816 	return (0);
11817 }
11818 
11819 /*
11820  * The LUN should always be set.  The I/O is optional, and is used to
11821  * distinguish between I/Os sent by this initiator, and by other
11822  * initiators.  We set unit attention for initiators other than this one.
11823  * SAM-3 is vague on this point.  It does say that a unit attention should
11824  * be established for other initiators when a LUN is reset (see section
11825  * 5.7.3), but it doesn't specifically say that the unit attention should
11826  * be established for this particular initiator when a LUN is reset.  Here
11827  * is the relevant text, from SAM-3 rev 8:
11828  *
11829  * 5.7.2 When a SCSI initiator port aborts its own tasks
11830  *
11831  * When a SCSI initiator port causes its own task(s) to be aborted, no
11832  * notification that the task(s) have been aborted shall be returned to
11833  * the SCSI initiator port other than the completion response for the
11834  * command or task management function action that caused the task(s) to
11835  * be aborted and notification(s) associated with related effects of the
11836  * action (e.g., a reset unit attention condition).
11837  *
11838  * XXX KDM for now, we're setting unit attention for all initiators.
11839  */
11840 static void
11841 ctl_do_lun_reset(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua_type)
11842 {
11843 	union ctl_io *xio;
11844 	int i;
11845 
11846 	mtx_lock(&lun->lun_lock);
11847 	/* Abort tasks. */
11848 	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11849 	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11850 		xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
11851 		ctl_try_unblock_io(lun, xio, FALSE);
11852 	}
11853 	/* Clear CA. */
11854 	for (i = 0; i < ctl_max_ports; i++) {
11855 		free(lun->pending_sense[i], M_CTL);
11856 		lun->pending_sense[i] = NULL;
11857 	}
11858 	/* Clear reservation. */
11859 	lun->flags &= ~CTL_LUN_RESERVED;
11860 	/* Clear prevent media removal. */
11861 	if (lun->prevent) {
11862 		for (i = 0; i < CTL_MAX_INITIATORS; i++)
11863 			ctl_clear_mask(lun->prevent, i);
11864 		lun->prevent_count = 0;
11865 	}
11866 	/* Clear TPC status */
11867 	ctl_tpc_lun_clear(lun, -1);
11868 	/* Establish UA. */
11869 #if 0
11870 	ctl_est_ua_all(lun, initidx, ua_type);
11871 #else
11872 	ctl_est_ua_all(lun, -1, ua_type);
11873 #endif
11874 	mtx_unlock(&lun->lun_lock);
11875 }
11876 
11877 static int
11878 ctl_lun_reset(union ctl_io *io)
11879 {
11880 	struct ctl_softc *softc = CTL_SOFTC(io);
11881 	struct ctl_lun *lun;
11882 	uint32_t targ_lun, initidx;
11883 
11884 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11885 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
11886 	mtx_lock(&softc->ctl_lock);
11887 	if (targ_lun >= ctl_max_luns ||
11888 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11889 		mtx_unlock(&softc->ctl_lock);
11890 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11891 		return (1);
11892 	}
11893 	ctl_do_lun_reset(lun, initidx, CTL_UA_LUN_RESET);
11894 	mtx_unlock(&softc->ctl_lock);
11895 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11896 
11897 	if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0) {
11898 		union ctl_ha_msg msg_info;
11899 
11900 		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11901 		msg_info.hdr.nexus = io->io_hdr.nexus;
11902 		msg_info.task.task_action = CTL_TASK_LUN_RESET;
11903 		msg_info.hdr.original_sc = NULL;
11904 		msg_info.hdr.serializing_sc = NULL;
11905 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11906 		    sizeof(msg_info.task), M_WAITOK);
11907 	}
11908 	return (0);
11909 }
11910 
11911 static void
11912 ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
11913     int other_sc)
11914 {
11915 	union ctl_io *xio;
11916 
11917 	mtx_assert(&lun->lun_lock, MA_OWNED);
11918 
11919 	/*
11920 	 * Run through the OOA queue and attempt to find the given I/O.
11921 	 * The target port, initiator ID, tag type and tag number have to
11922 	 * match the values that we got from the initiator.  If we have an
11923 	 * untagged command to abort, simply abort the first untagged command
11924 	 * we come to.  We only allow one untagged command at a time of course.
11925 	 */
11926 	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11927 	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11928 
11929 		if ((targ_port == UINT32_MAX ||
11930 		     targ_port == xio->io_hdr.nexus.targ_port) &&
11931 		    (init_id == UINT32_MAX ||
11932 		     init_id == xio->io_hdr.nexus.initid)) {
11933 			if (targ_port != xio->io_hdr.nexus.targ_port ||
11934 			    init_id != xio->io_hdr.nexus.initid)
11935 				xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
11936 			xio->io_hdr.flags |= CTL_FLAG_ABORT;
11937 			if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11938 				union ctl_ha_msg msg_info;
11939 
11940 				msg_info.hdr.nexus = xio->io_hdr.nexus;
11941 				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
11942 				msg_info.task.tag_num = xio->scsiio.tag_num;
11943 				msg_info.task.tag_type = xio->scsiio.tag_type;
11944 				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11945 				msg_info.hdr.original_sc = NULL;
11946 				msg_info.hdr.serializing_sc = NULL;
11947 				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11948 				    sizeof(msg_info.task), M_NOWAIT);
11949 			}
11950 			ctl_try_unblock_io(lun, xio, FALSE);
11951 		}
11952 	}
11953 }
11954 
11955 static int
11956 ctl_abort_task_set(union ctl_io *io)
11957 {
11958 	struct ctl_softc *softc = CTL_SOFTC(io);
11959 	struct ctl_lun *lun;
11960 	uint32_t targ_lun;
11961 
11962 	/*
11963 	 * Look up the LUN.
11964 	 */
11965 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11966 	mtx_lock(&softc->ctl_lock);
11967 	if (targ_lun >= ctl_max_luns ||
11968 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11969 		mtx_unlock(&softc->ctl_lock);
11970 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11971 		return (1);
11972 	}
11973 
11974 	mtx_lock(&lun->lun_lock);
11975 	mtx_unlock(&softc->ctl_lock);
11976 	if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
11977 		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
11978 		    io->io_hdr.nexus.initid,
11979 		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11980 	} else { /* CTL_TASK_CLEAR_TASK_SET */
11981 		ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
11982 		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11983 	}
11984 	mtx_unlock(&lun->lun_lock);
11985 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11986 	return (0);
11987 }
11988 
11989 static void
11990 ctl_i_t_nexus_loss(struct ctl_softc *softc, uint32_t initidx,
11991     ctl_ua_type ua_type)
11992 {
11993 	struct ctl_lun *lun;
11994 	struct scsi_sense_data *ps;
11995 	uint32_t p, i;
11996 
11997 	p = initidx / CTL_MAX_INIT_PER_PORT;
11998 	i = initidx % CTL_MAX_INIT_PER_PORT;
11999 	mtx_lock(&softc->ctl_lock);
12000 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
12001 		mtx_lock(&lun->lun_lock);
12002 		/* Abort tasks. */
12003 		ctl_abort_tasks_lun(lun, p, i, 1);
12004 		/* Clear CA. */
12005 		ps = lun->pending_sense[p];
12006 		if (ps != NULL)
12007 			ps[i].error_code = 0;
12008 		/* Clear reservation. */
12009 		if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == initidx))
12010 			lun->flags &= ~CTL_LUN_RESERVED;
12011 		/* Clear prevent media removal. */
12012 		if (lun->prevent && ctl_is_set(lun->prevent, initidx)) {
12013 			ctl_clear_mask(lun->prevent, initidx);
12014 			lun->prevent_count--;
12015 		}
12016 		/* Clear TPC status */
12017 		ctl_tpc_lun_clear(lun, initidx);
12018 		/* Establish UA. */
12019 		ctl_est_ua(lun, initidx, ua_type);
12020 		mtx_unlock(&lun->lun_lock);
12021 	}
12022 	mtx_unlock(&softc->ctl_lock);
12023 }
12024 
12025 static int
12026 ctl_i_t_nexus_reset(union ctl_io *io)
12027 {
12028 	struct ctl_softc *softc = CTL_SOFTC(io);
12029 	uint32_t initidx;
12030 
12031 	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12032 		union ctl_ha_msg msg_info;
12033 
12034 		msg_info.hdr.nexus = io->io_hdr.nexus;
12035 		msg_info.task.task_action = CTL_TASK_I_T_NEXUS_RESET;
12036 		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12037 		msg_info.hdr.original_sc = NULL;
12038 		msg_info.hdr.serializing_sc = NULL;
12039 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12040 		    sizeof(msg_info.task), M_WAITOK);
12041 	}
12042 
12043 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
12044 	ctl_i_t_nexus_loss(softc, initidx, CTL_UA_I_T_NEXUS_LOSS);
12045 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12046 	return (0);
12047 }
12048 
12049 static int
12050 ctl_abort_task(union ctl_io *io)
12051 {
12052 	struct ctl_softc *softc = CTL_SOFTC(io);
12053 	union ctl_io *xio;
12054 	struct ctl_lun *lun;
12055 	uint32_t targ_lun;
12056 
12057 	/*
12058 	 * Look up the LUN.
12059 	 */
12060 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12061 	mtx_lock(&softc->ctl_lock);
12062 	if (targ_lun >= ctl_max_luns ||
12063 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12064 		mtx_unlock(&softc->ctl_lock);
12065 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12066 		return (1);
12067 	}
12068 
12069 	mtx_lock(&lun->lun_lock);
12070 	mtx_unlock(&softc->ctl_lock);
12071 	/*
12072 	 * Run through the OOA queue and attempt to find the given I/O.
12073 	 * The target port, initiator ID, tag type and tag number have to
12074 	 * match the values that we got from the initiator.  If we have an
12075 	 * untagged command to abort, simply abort the first untagged command
12076 	 * we come to.  We only allow one untagged command at a time of course.
12077 	 */
12078 	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12079 	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12080 
12081 		if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
12082 		 || (xio->io_hdr.nexus.initid != io->io_hdr.nexus.initid)
12083 		 || (xio->io_hdr.flags & CTL_FLAG_ABORT))
12084 			continue;
12085 
12086 		/*
12087 		 * If the abort says that the task is untagged, the
12088 		 * task in the queue must be untagged.  Otherwise,
12089 		 * we just check to see whether the tag numbers
12090 		 * match.  This is because the QLogic firmware
12091 		 * doesn't pass back the tag type in an abort
12092 		 * request.
12093 		 */
12094 #if 0
12095 		if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
12096 		  && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
12097 		 || (xio->scsiio.tag_num == io->taskio.tag_num)) {
12098 #else
12099 		/*
12100 		 * XXX KDM we've got problems with FC, because it
12101 		 * doesn't send down a tag type with aborts.  So we
12102 		 * can only really go by the tag number...
12103 		 * This may cause problems with parallel SCSI.
12104 		 * Need to figure that out!!
12105 		 */
12106 		if (xio->scsiio.tag_num == io->taskio.tag_num) {
12107 #endif
12108 			xio->io_hdr.flags |= CTL_FLAG_ABORT;
12109 			if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0 &&
12110 			    !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12111 				union ctl_ha_msg msg_info;
12112 
12113 				msg_info.hdr.nexus = io->io_hdr.nexus;
12114 				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
12115 				msg_info.task.tag_num = io->taskio.tag_num;
12116 				msg_info.task.tag_type = io->taskio.tag_type;
12117 				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12118 				msg_info.hdr.original_sc = NULL;
12119 				msg_info.hdr.serializing_sc = NULL;
12120 				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12121 				    sizeof(msg_info.task), M_NOWAIT);
12122 			}
12123 			ctl_try_unblock_io(lun, xio, FALSE);
12124 		}
12125 	}
12126 	mtx_unlock(&lun->lun_lock);
12127 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12128 	return (0);
12129 }
12130 
12131 static int
12132 ctl_query_task(union ctl_io *io, int task_set)
12133 {
12134 	struct ctl_softc *softc = CTL_SOFTC(io);
12135 	union ctl_io *xio;
12136 	struct ctl_lun *lun;
12137 	int found = 0;
12138 	uint32_t targ_lun;
12139 
12140 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12141 	mtx_lock(&softc->ctl_lock);
12142 	if (targ_lun >= ctl_max_luns ||
12143 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12144 		mtx_unlock(&softc->ctl_lock);
12145 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12146 		return (1);
12147 	}
12148 	mtx_lock(&lun->lun_lock);
12149 	mtx_unlock(&softc->ctl_lock);
12150 	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12151 	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12152 
12153 		if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
12154 		 || (xio->io_hdr.nexus.initid != io->io_hdr.nexus.initid)
12155 		 || (xio->io_hdr.flags & CTL_FLAG_ABORT))
12156 			continue;
12157 
12158 		if (task_set || xio->scsiio.tag_num == io->taskio.tag_num) {
12159 			found = 1;
12160 			break;
12161 		}
12162 	}
12163 	mtx_unlock(&lun->lun_lock);
12164 	if (found)
12165 		io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12166 	else
12167 		io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12168 	return (0);
12169 }
12170 
12171 static int
12172 ctl_query_async_event(union ctl_io *io)
12173 {
12174 	struct ctl_softc *softc = CTL_SOFTC(io);
12175 	struct ctl_lun *lun;
12176 	ctl_ua_type ua;
12177 	uint32_t targ_lun, initidx;
12178 
12179 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12180 	mtx_lock(&softc->ctl_lock);
12181 	if (targ_lun >= ctl_max_luns ||
12182 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12183 		mtx_unlock(&softc->ctl_lock);
12184 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12185 		return (1);
12186 	}
12187 	mtx_lock(&lun->lun_lock);
12188 	mtx_unlock(&softc->ctl_lock);
12189 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
12190 	ua = ctl_build_qae(lun, initidx, io->taskio.task_resp);
12191 	mtx_unlock(&lun->lun_lock);
12192 	if (ua != CTL_UA_NONE)
12193 		io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12194 	else
12195 		io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12196 	return (0);
12197 }
12198 
12199 static void
12200 ctl_run_task(union ctl_io *io)
12201 {
12202 	int retval = 1;
12203 
12204 	CTL_DEBUG_PRINT(("ctl_run_task\n"));
12205 	KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12206 	    ("ctl_run_task: Unextected io_type %d\n", io->io_hdr.io_type));
12207 	io->taskio.task_status = CTL_TASK_FUNCTION_NOT_SUPPORTED;
12208 	bzero(io->taskio.task_resp, sizeof(io->taskio.task_resp));
12209 	switch (io->taskio.task_action) {
12210 	case CTL_TASK_ABORT_TASK:
12211 		retval = ctl_abort_task(io);
12212 		break;
12213 	case CTL_TASK_ABORT_TASK_SET:
12214 	case CTL_TASK_CLEAR_TASK_SET:
12215 		retval = ctl_abort_task_set(io);
12216 		break;
12217 	case CTL_TASK_CLEAR_ACA:
12218 		break;
12219 	case CTL_TASK_I_T_NEXUS_RESET:
12220 		retval = ctl_i_t_nexus_reset(io);
12221 		break;
12222 	case CTL_TASK_LUN_RESET:
12223 		retval = ctl_lun_reset(io);
12224 		break;
12225 	case CTL_TASK_TARGET_RESET:
12226 	case CTL_TASK_BUS_RESET:
12227 		retval = ctl_target_reset(io);
12228 		break;
12229 	case CTL_TASK_PORT_LOGIN:
12230 		break;
12231 	case CTL_TASK_PORT_LOGOUT:
12232 		break;
12233 	case CTL_TASK_QUERY_TASK:
12234 		retval = ctl_query_task(io, 0);
12235 		break;
12236 	case CTL_TASK_QUERY_TASK_SET:
12237 		retval = ctl_query_task(io, 1);
12238 		break;
12239 	case CTL_TASK_QUERY_ASYNC_EVENT:
12240 		retval = ctl_query_async_event(io);
12241 		break;
12242 	default:
12243 		printf("%s: got unknown task management event %d\n",
12244 		       __func__, io->taskio.task_action);
12245 		break;
12246 	}
12247 	if (retval == 0)
12248 		io->io_hdr.status = CTL_SUCCESS;
12249 	else
12250 		io->io_hdr.status = CTL_ERROR;
12251 	ctl_done(io);
12252 }
12253 
12254 /*
12255  * For HA operation.  Handle commands that come in from the other
12256  * controller.
12257  */
12258 static void
12259 ctl_handle_isc(union ctl_io *io)
12260 {
12261 	struct ctl_softc *softc = CTL_SOFTC(io);
12262 	struct ctl_lun *lun;
12263 	const struct ctl_cmd_entry *entry;
12264 	uint32_t targ_lun;
12265 
12266 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12267 	switch (io->io_hdr.msg_type) {
12268 	case CTL_MSG_SERIALIZE:
12269 		ctl_serialize_other_sc_cmd(&io->scsiio);
12270 		break;
12271 	case CTL_MSG_R2R:		/* Only used in SER_ONLY mode. */
12272 		entry = ctl_get_cmd_entry(&io->scsiio, NULL);
12273 		if (targ_lun >= ctl_max_luns ||
12274 		    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12275 			ctl_done(io);
12276 			break;
12277 		}
12278 		mtx_lock(&lun->lun_lock);
12279 		if (ctl_scsiio_lun_check(lun, entry, &io->scsiio) != 0) {
12280 			mtx_unlock(&lun->lun_lock);
12281 			ctl_done(io);
12282 			break;
12283 		}
12284 		io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12285 		mtx_unlock(&lun->lun_lock);
12286 		ctl_enqueue_rtr(io);
12287 		break;
12288 	case CTL_MSG_FINISH_IO:
12289 		if (softc->ha_mode == CTL_HA_MODE_XFER) {
12290 			ctl_done(io);
12291 			break;
12292 		}
12293 		if (targ_lun >= ctl_max_luns ||
12294 		    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12295 			ctl_free_io(io);
12296 			break;
12297 		}
12298 		mtx_lock(&lun->lun_lock);
12299 		ctl_try_unblock_others(lun, io, TRUE);
12300 		TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
12301 		mtx_unlock(&lun->lun_lock);
12302 		ctl_free_io(io);
12303 		break;
12304 	case CTL_MSG_PERS_ACTION:
12305 		ctl_hndl_per_res_out_on_other_sc(io);
12306 		ctl_free_io(io);
12307 		break;
12308 	case CTL_MSG_BAD_JUJU:
12309 		ctl_done(io);
12310 		break;
12311 	case CTL_MSG_DATAMOVE:		/* Only used in XFER mode */
12312 		ctl_datamove_remote(io);
12313 		break;
12314 	case CTL_MSG_DATAMOVE_DONE:	/* Only used in XFER mode */
12315 		io->scsiio.be_move_done(io);
12316 		break;
12317 	case CTL_MSG_FAILOVER:
12318 		ctl_failover_lun(io);
12319 		ctl_free_io(io);
12320 		break;
12321 	default:
12322 		printf("%s: Invalid message type %d\n",
12323 		       __func__, io->io_hdr.msg_type);
12324 		ctl_free_io(io);
12325 		break;
12326 	}
12327 
12328 }
12329 
12330 
12331 /*
12332  * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12333  * there is no match.
12334  */
12335 static ctl_lun_error_pattern
12336 ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12337 {
12338 	const struct ctl_cmd_entry *entry;
12339 	ctl_lun_error_pattern filtered_pattern, pattern;
12340 
12341 	pattern = desc->error_pattern;
12342 
12343 	/*
12344 	 * XXX KDM we need more data passed into this function to match a
12345 	 * custom pattern, and we actually need to implement custom pattern
12346 	 * matching.
12347 	 */
12348 	if (pattern & CTL_LUN_PAT_CMD)
12349 		return (CTL_LUN_PAT_CMD);
12350 
12351 	if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12352 		return (CTL_LUN_PAT_ANY);
12353 
12354 	entry = ctl_get_cmd_entry(ctsio, NULL);
12355 
12356 	filtered_pattern = entry->pattern & pattern;
12357 
12358 	/*
12359 	 * If the user requested specific flags in the pattern (e.g.
12360 	 * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12361 	 * flags.
12362 	 *
12363 	 * If the user did not specify any flags, it doesn't matter whether
12364 	 * or not the command supports the flags.
12365 	 */
12366 	if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12367 	     (pattern & ~CTL_LUN_PAT_MASK))
12368 		return (CTL_LUN_PAT_NONE);
12369 
12370 	/*
12371 	 * If the user asked for a range check, see if the requested LBA
12372 	 * range overlaps with this command's LBA range.
12373 	 */
12374 	if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12375 		uint64_t lba1;
12376 		uint64_t len1;
12377 		ctl_action action;
12378 		int retval;
12379 
12380 		retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12381 		if (retval != 0)
12382 			return (CTL_LUN_PAT_NONE);
12383 
12384 		action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12385 					      desc->lba_range.len, FALSE);
12386 		/*
12387 		 * A "pass" means that the LBA ranges don't overlap, so
12388 		 * this doesn't match the user's range criteria.
12389 		 */
12390 		if (action == CTL_ACTION_PASS)
12391 			return (CTL_LUN_PAT_NONE);
12392 	}
12393 
12394 	return (filtered_pattern);
12395 }
12396 
12397 static void
12398 ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12399 {
12400 	struct ctl_error_desc *desc, *desc2;
12401 
12402 	mtx_assert(&lun->lun_lock, MA_OWNED);
12403 
12404 	STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12405 		ctl_lun_error_pattern pattern;
12406 		/*
12407 		 * Check to see whether this particular command matches
12408 		 * the pattern in the descriptor.
12409 		 */
12410 		pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12411 		if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12412 			continue;
12413 
12414 		switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12415 		case CTL_LUN_INJ_ABORTED:
12416 			ctl_set_aborted(&io->scsiio);
12417 			break;
12418 		case CTL_LUN_INJ_MEDIUM_ERR:
12419 			ctl_set_medium_error(&io->scsiio,
12420 			    (io->io_hdr.flags & CTL_FLAG_DATA_MASK) !=
12421 			     CTL_FLAG_DATA_OUT);
12422 			break;
12423 		case CTL_LUN_INJ_UA:
12424 			/* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12425 			 * OCCURRED */
12426 			ctl_set_ua(&io->scsiio, 0x29, 0x00);
12427 			break;
12428 		case CTL_LUN_INJ_CUSTOM:
12429 			/*
12430 			 * We're assuming the user knows what he is doing.
12431 			 * Just copy the sense information without doing
12432 			 * checks.
12433 			 */
12434 			bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12435 			      MIN(sizeof(desc->custom_sense),
12436 				  sizeof(io->scsiio.sense_data)));
12437 			io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12438 			io->scsiio.sense_len = SSD_FULL_SIZE;
12439 			io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12440 			break;
12441 		case CTL_LUN_INJ_NONE:
12442 		default:
12443 			/*
12444 			 * If this is an error injection type we don't know
12445 			 * about, clear the continuous flag (if it is set)
12446 			 * so it will get deleted below.
12447 			 */
12448 			desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12449 			break;
12450 		}
12451 		/*
12452 		 * By default, each error injection action is a one-shot
12453 		 */
12454 		if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12455 			continue;
12456 
12457 		STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12458 
12459 		free(desc, M_CTL);
12460 	}
12461 }
12462 
12463 #ifdef CTL_IO_DELAY
12464 static void
12465 ctl_datamove_timer_wakeup(void *arg)
12466 {
12467 	union ctl_io *io;
12468 
12469 	io = (union ctl_io *)arg;
12470 
12471 	ctl_datamove(io);
12472 }
12473 #endif /* CTL_IO_DELAY */
12474 
12475 void
12476 ctl_datamove(union ctl_io *io)
12477 {
12478 	void (*fe_datamove)(union ctl_io *io);
12479 
12480 	mtx_assert(&((struct ctl_softc *)CTL_SOFTC(io))->ctl_lock, MA_NOTOWNED);
12481 
12482 	CTL_DEBUG_PRINT(("ctl_datamove\n"));
12483 
12484 	/* No data transferred yet.  Frontend must update this when done. */
12485 	io->scsiio.kern_data_resid = io->scsiio.kern_data_len;
12486 
12487 #ifdef CTL_TIME_IO
12488 	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12489 		char str[256];
12490 		char path_str[64];
12491 		struct sbuf sb;
12492 
12493 		ctl_scsi_path_string(io, path_str, sizeof(path_str));
12494 		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12495 
12496 		sbuf_cat(&sb, path_str);
12497 		switch (io->io_hdr.io_type) {
12498 		case CTL_IO_SCSI:
12499 			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12500 			sbuf_printf(&sb, "\n");
12501 			sbuf_cat(&sb, path_str);
12502 			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12503 				    io->scsiio.tag_num, io->scsiio.tag_type);
12504 			break;
12505 		case CTL_IO_TASK:
12506 			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12507 				    "Tag Type: %d\n", io->taskio.task_action,
12508 				    io->taskio.tag_num, io->taskio.tag_type);
12509 			break;
12510 		default:
12511 			panic("%s: Invalid CTL I/O type %d\n",
12512 			    __func__, io->io_hdr.io_type);
12513 		}
12514 		sbuf_cat(&sb, path_str);
12515 		sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12516 			    (intmax_t)time_uptime - io->io_hdr.start_time);
12517 		sbuf_finish(&sb);
12518 		printf("%s", sbuf_data(&sb));
12519 	}
12520 #endif /* CTL_TIME_IO */
12521 
12522 #ifdef CTL_IO_DELAY
12523 	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12524 		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12525 	} else {
12526 		struct ctl_lun *lun;
12527 
12528 		lun = CTL_LUN(io);
12529 		if ((lun != NULL)
12530 		 && (lun->delay_info.datamove_delay > 0)) {
12531 
12532 			callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
12533 			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12534 			callout_reset(&io->io_hdr.delay_callout,
12535 				      lun->delay_info.datamove_delay * hz,
12536 				      ctl_datamove_timer_wakeup, io);
12537 			if (lun->delay_info.datamove_type ==
12538 			    CTL_DELAY_TYPE_ONESHOT)
12539 				lun->delay_info.datamove_delay = 0;
12540 			return;
12541 		}
12542 	}
12543 #endif
12544 
12545 	/*
12546 	 * This command has been aborted.  Set the port status, so we fail
12547 	 * the data move.
12548 	 */
12549 	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12550 		printf("ctl_datamove: tag 0x%04x on (%u:%u:%u) aborted\n",
12551 		       io->scsiio.tag_num, io->io_hdr.nexus.initid,
12552 		       io->io_hdr.nexus.targ_port,
12553 		       io->io_hdr.nexus.targ_lun);
12554 		io->io_hdr.port_status = 31337;
12555 		/*
12556 		 * Note that the backend, in this case, will get the
12557 		 * callback in its context.  In other cases it may get
12558 		 * called in the frontend's interrupt thread context.
12559 		 */
12560 		io->scsiio.be_move_done(io);
12561 		return;
12562 	}
12563 
12564 	/* Don't confuse frontend with zero length data move. */
12565 	if (io->scsiio.kern_data_len == 0) {
12566 		io->scsiio.be_move_done(io);
12567 		return;
12568 	}
12569 
12570 	fe_datamove = CTL_PORT(io)->fe_datamove;
12571 	fe_datamove(io);
12572 }
12573 
12574 static void
12575 ctl_send_datamove_done(union ctl_io *io, int have_lock)
12576 {
12577 	union ctl_ha_msg msg;
12578 #ifdef CTL_TIME_IO
12579 	struct bintime cur_bt;
12580 #endif
12581 
12582 	memset(&msg, 0, sizeof(msg));
12583 	msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12584 	msg.hdr.original_sc = io;
12585 	msg.hdr.serializing_sc = io->io_hdr.remote_io;
12586 	msg.hdr.nexus = io->io_hdr.nexus;
12587 	msg.hdr.status = io->io_hdr.status;
12588 	msg.scsi.kern_data_resid = io->scsiio.kern_data_resid;
12589 	msg.scsi.tag_num = io->scsiio.tag_num;
12590 	msg.scsi.tag_type = io->scsiio.tag_type;
12591 	msg.scsi.scsi_status = io->scsiio.scsi_status;
12592 	memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12593 	       io->scsiio.sense_len);
12594 	msg.scsi.sense_len = io->scsiio.sense_len;
12595 	msg.scsi.port_status = io->io_hdr.port_status;
12596 	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12597 	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12598 		ctl_failover_io(io, /*have_lock*/ have_lock);
12599 		return;
12600 	}
12601 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12602 	    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
12603 	    msg.scsi.sense_len, M_WAITOK);
12604 
12605 #ifdef CTL_TIME_IO
12606 	getbinuptime(&cur_bt);
12607 	bintime_sub(&cur_bt, &io->io_hdr.dma_start_bt);
12608 	bintime_add(&io->io_hdr.dma_bt, &cur_bt);
12609 #endif
12610 	io->io_hdr.num_dmas++;
12611 }
12612 
12613 /*
12614  * The DMA to the remote side is done, now we need to tell the other side
12615  * we're done so it can continue with its data movement.
12616  */
12617 static void
12618 ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12619 {
12620 	union ctl_io *io;
12621 	uint32_t i;
12622 
12623 	io = rq->context;
12624 
12625 	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12626 		printf("%s: ISC DMA write failed with error %d", __func__,
12627 		       rq->ret);
12628 		ctl_set_internal_failure(&io->scsiio,
12629 					 /*sks_valid*/ 1,
12630 					 /*retry_count*/ rq->ret);
12631 	}
12632 
12633 	ctl_dt_req_free(rq);
12634 
12635 	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12636 		free(CTL_LSGLT(io)[i].addr, M_CTL);
12637 	free(CTL_RSGL(io), M_CTL);
12638 	CTL_RSGL(io) = NULL;
12639 	CTL_LSGL(io) = NULL;
12640 
12641 	/*
12642 	 * The data is in local and remote memory, so now we need to send
12643 	 * status (good or back) back to the other side.
12644 	 */
12645 	ctl_send_datamove_done(io, /*have_lock*/ 0);
12646 }
12647 
12648 /*
12649  * We've moved the data from the host/controller into local memory.  Now we
12650  * need to push it over to the remote controller's memory.
12651  */
12652 static int
12653 ctl_datamove_remote_dm_write_cb(union ctl_io *io)
12654 {
12655 	int retval;
12656 
12657 	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
12658 					  ctl_datamove_remote_write_cb);
12659 	return (retval);
12660 }
12661 
12662 static void
12663 ctl_datamove_remote_write(union ctl_io *io)
12664 {
12665 	int retval;
12666 	void (*fe_datamove)(union ctl_io *io);
12667 
12668 	/*
12669 	 * - Get the data from the host/HBA into local memory.
12670 	 * - DMA memory from the local controller to the remote controller.
12671 	 * - Send status back to the remote controller.
12672 	 */
12673 
12674 	retval = ctl_datamove_remote_sgl_setup(io);
12675 	if (retval != 0)
12676 		return;
12677 
12678 	/* Switch the pointer over so the FETD knows what to do */
12679 	io->scsiio.kern_data_ptr = (uint8_t *)CTL_LSGL(io);
12680 
12681 	/*
12682 	 * Use a custom move done callback, since we need to send completion
12683 	 * back to the other controller, not to the backend on this side.
12684 	 */
12685 	io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
12686 
12687 	fe_datamove = CTL_PORT(io)->fe_datamove;
12688 	fe_datamove(io);
12689 }
12690 
12691 static int
12692 ctl_datamove_remote_dm_read_cb(union ctl_io *io)
12693 {
12694 	uint32_t i;
12695 
12696 	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12697 		free(CTL_LSGLT(io)[i].addr, M_CTL);
12698 	free(CTL_RSGL(io), M_CTL);
12699 	CTL_RSGL(io) = NULL;
12700 	CTL_LSGL(io) = NULL;
12701 
12702 	/*
12703 	 * The read is done, now we need to send status (good or bad) back
12704 	 * to the other side.
12705 	 */
12706 	ctl_send_datamove_done(io, /*have_lock*/ 0);
12707 
12708 	return (0);
12709 }
12710 
12711 static void
12712 ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
12713 {
12714 	union ctl_io *io;
12715 	void (*fe_datamove)(union ctl_io *io);
12716 
12717 	io = rq->context;
12718 
12719 	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12720 		printf("%s: ISC DMA read failed with error %d\n", __func__,
12721 		       rq->ret);
12722 		ctl_set_internal_failure(&io->scsiio,
12723 					 /*sks_valid*/ 1,
12724 					 /*retry_count*/ rq->ret);
12725 	}
12726 
12727 	ctl_dt_req_free(rq);
12728 
12729 	/* Switch the pointer over so the FETD knows what to do */
12730 	io->scsiio.kern_data_ptr = (uint8_t *)CTL_LSGL(io);
12731 
12732 	/*
12733 	 * Use a custom move done callback, since we need to send completion
12734 	 * back to the other controller, not to the backend on this side.
12735 	 */
12736 	io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
12737 
12738 	/* XXX KDM add checks like the ones in ctl_datamove? */
12739 
12740 	fe_datamove = CTL_PORT(io)->fe_datamove;
12741 	fe_datamove(io);
12742 }
12743 
12744 static int
12745 ctl_datamove_remote_sgl_setup(union ctl_io *io)
12746 {
12747 	struct ctl_sg_entry *local_sglist;
12748 	uint32_t len_to_go;
12749 	int retval;
12750 	int i;
12751 
12752 	retval = 0;
12753 	local_sglist = CTL_LSGL(io);
12754 	len_to_go = io->scsiio.kern_data_len;
12755 
12756 	/*
12757 	 * The difficult thing here is that the size of the various
12758 	 * S/G segments may be different than the size from the
12759 	 * remote controller.  That'll make it harder when DMAing
12760 	 * the data back to the other side.
12761 	 */
12762 	for (i = 0; len_to_go > 0; i++) {
12763 		local_sglist[i].len = MIN(len_to_go, CTL_HA_DATAMOVE_SEGMENT);
12764 		local_sglist[i].addr =
12765 		    malloc(local_sglist[i].len, M_CTL, M_WAITOK);
12766 
12767 		len_to_go -= local_sglist[i].len;
12768 	}
12769 	/*
12770 	 * Reset the number of S/G entries accordingly.  The original
12771 	 * number of S/G entries is available in rem_sg_entries.
12772 	 */
12773 	io->scsiio.kern_sg_entries = i;
12774 
12775 	return (retval);
12776 }
12777 
12778 static int
12779 ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
12780 			 ctl_ha_dt_cb callback)
12781 {
12782 	struct ctl_ha_dt_req *rq;
12783 	struct ctl_sg_entry *remote_sglist, *local_sglist;
12784 	uint32_t local_used, remote_used, total_used;
12785 	int i, j, isc_ret;
12786 
12787 	rq = ctl_dt_req_alloc();
12788 
12789 	/*
12790 	 * If we failed to allocate the request, and if the DMA didn't fail
12791 	 * anyway, set busy status.  This is just a resource allocation
12792 	 * failure.
12793 	 */
12794 	if ((rq == NULL)
12795 	 && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12796 	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS))
12797 		ctl_set_busy(&io->scsiio);
12798 
12799 	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12800 	    (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) {
12801 
12802 		if (rq != NULL)
12803 			ctl_dt_req_free(rq);
12804 
12805 		/*
12806 		 * The data move failed.  We need to return status back
12807 		 * to the other controller.  No point in trying to DMA
12808 		 * data to the remote controller.
12809 		 */
12810 
12811 		ctl_send_datamove_done(io, /*have_lock*/ 0);
12812 
12813 		return (1);
12814 	}
12815 
12816 	local_sglist = CTL_LSGL(io);
12817 	remote_sglist = CTL_RSGL(io);
12818 	local_used = 0;
12819 	remote_used = 0;
12820 	total_used = 0;
12821 
12822 	/*
12823 	 * Pull/push the data over the wire from/to the other controller.
12824 	 * This takes into account the possibility that the local and
12825 	 * remote sglists may not be identical in terms of the size of
12826 	 * the elements and the number of elements.
12827 	 *
12828 	 * One fundamental assumption here is that the length allocated for
12829 	 * both the local and remote sglists is identical.  Otherwise, we've
12830 	 * essentially got a coding error of some sort.
12831 	 */
12832 	isc_ret = CTL_HA_STATUS_SUCCESS;
12833 	for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
12834 		uint32_t cur_len;
12835 		uint8_t *tmp_ptr;
12836 
12837 		rq->command = command;
12838 		rq->context = io;
12839 
12840 		/*
12841 		 * Both pointers should be aligned.  But it is possible
12842 		 * that the allocation length is not.  They should both
12843 		 * also have enough slack left over at the end, though,
12844 		 * to round up to the next 8 byte boundary.
12845 		 */
12846 		cur_len = MIN(local_sglist[i].len - local_used,
12847 			      remote_sglist[j].len - remote_used);
12848 		rq->size = cur_len;
12849 
12850 		tmp_ptr = (uint8_t *)local_sglist[i].addr;
12851 		tmp_ptr += local_used;
12852 
12853 #if 0
12854 		/* Use physical addresses when talking to ISC hardware */
12855 		if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
12856 			/* XXX KDM use busdma */
12857 			rq->local = vtophys(tmp_ptr);
12858 		} else
12859 			rq->local = tmp_ptr;
12860 #else
12861 		KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
12862 		    ("HA does not support BUS_ADDR"));
12863 		rq->local = tmp_ptr;
12864 #endif
12865 
12866 		tmp_ptr = (uint8_t *)remote_sglist[j].addr;
12867 		tmp_ptr += remote_used;
12868 		rq->remote = tmp_ptr;
12869 
12870 		rq->callback = NULL;
12871 
12872 		local_used += cur_len;
12873 		if (local_used >= local_sglist[i].len) {
12874 			i++;
12875 			local_used = 0;
12876 		}
12877 
12878 		remote_used += cur_len;
12879 		if (remote_used >= remote_sglist[j].len) {
12880 			j++;
12881 			remote_used = 0;
12882 		}
12883 		total_used += cur_len;
12884 
12885 		if (total_used >= io->scsiio.kern_data_len)
12886 			rq->callback = callback;
12887 
12888 		isc_ret = ctl_dt_single(rq);
12889 		if (isc_ret > CTL_HA_STATUS_SUCCESS)
12890 			break;
12891 	}
12892 	if (isc_ret != CTL_HA_STATUS_WAIT) {
12893 		rq->ret = isc_ret;
12894 		callback(rq);
12895 	}
12896 
12897 	return (0);
12898 }
12899 
12900 static void
12901 ctl_datamove_remote_read(union ctl_io *io)
12902 {
12903 	int retval;
12904 	uint32_t i;
12905 
12906 	/*
12907 	 * This will send an error to the other controller in the case of a
12908 	 * failure.
12909 	 */
12910 	retval = ctl_datamove_remote_sgl_setup(io);
12911 	if (retval != 0)
12912 		return;
12913 
12914 	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
12915 					  ctl_datamove_remote_read_cb);
12916 	if (retval != 0) {
12917 		/*
12918 		 * Make sure we free memory if there was an error..  The
12919 		 * ctl_datamove_remote_xfer() function will send the
12920 		 * datamove done message, or call the callback with an
12921 		 * error if there is a problem.
12922 		 */
12923 		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12924 			free(CTL_LSGLT(io)[i].addr, M_CTL);
12925 		free(CTL_RSGL(io), M_CTL);
12926 		CTL_RSGL(io) = NULL;
12927 		CTL_LSGL(io) = NULL;
12928 	}
12929 }
12930 
12931 /*
12932  * Process a datamove request from the other controller.  This is used for
12933  * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
12934  * first.  Once that is complete, the data gets DMAed into the remote
12935  * controller's memory.  For reads, we DMA from the remote controller's
12936  * memory into our memory first, and then move it out to the FETD.
12937  */
12938 static void
12939 ctl_datamove_remote(union ctl_io *io)
12940 {
12941 
12942 	mtx_assert(&((struct ctl_softc *)CTL_SOFTC(io))->ctl_lock, MA_NOTOWNED);
12943 
12944 	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12945 		ctl_failover_io(io, /*have_lock*/ 0);
12946 		return;
12947 	}
12948 
12949 	/*
12950 	 * Note that we look for an aborted I/O here, but don't do some of
12951 	 * the other checks that ctl_datamove() normally does.
12952 	 * We don't need to run the datamove delay code, since that should
12953 	 * have been done if need be on the other controller.
12954 	 */
12955 	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12956 		printf("%s: tag 0x%04x on (%u:%u:%u) aborted\n", __func__,
12957 		       io->scsiio.tag_num, io->io_hdr.nexus.initid,
12958 		       io->io_hdr.nexus.targ_port,
12959 		       io->io_hdr.nexus.targ_lun);
12960 		io->io_hdr.port_status = 31338;
12961 		ctl_send_datamove_done(io, /*have_lock*/ 0);
12962 		return;
12963 	}
12964 
12965 	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT)
12966 		ctl_datamove_remote_write(io);
12967 	else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
12968 		ctl_datamove_remote_read(io);
12969 	else {
12970 		io->io_hdr.port_status = 31339;
12971 		ctl_send_datamove_done(io, /*have_lock*/ 0);
12972 	}
12973 }
12974 
12975 static void
12976 ctl_process_done(union ctl_io *io)
12977 {
12978 	struct ctl_softc *softc = CTL_SOFTC(io);
12979 	struct ctl_port *port = CTL_PORT(io);
12980 	struct ctl_lun *lun = CTL_LUN(io);
12981 	void (*fe_done)(union ctl_io *io);
12982 	union ctl_ha_msg msg;
12983 
12984 	CTL_DEBUG_PRINT(("ctl_process_done\n"));
12985 	fe_done = port->fe_done;
12986 
12987 #ifdef CTL_TIME_IO
12988 	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12989 		char str[256];
12990 		char path_str[64];
12991 		struct sbuf sb;
12992 
12993 		ctl_scsi_path_string(io, path_str, sizeof(path_str));
12994 		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12995 
12996 		sbuf_cat(&sb, path_str);
12997 		switch (io->io_hdr.io_type) {
12998 		case CTL_IO_SCSI:
12999 			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
13000 			sbuf_printf(&sb, "\n");
13001 			sbuf_cat(&sb, path_str);
13002 			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13003 				    io->scsiio.tag_num, io->scsiio.tag_type);
13004 			break;
13005 		case CTL_IO_TASK:
13006 			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
13007 				    "Tag Type: %d\n", io->taskio.task_action,
13008 				    io->taskio.tag_num, io->taskio.tag_type);
13009 			break;
13010 		default:
13011 			panic("%s: Invalid CTL I/O type %d\n",
13012 			    __func__, io->io_hdr.io_type);
13013 		}
13014 		sbuf_cat(&sb, path_str);
13015 		sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
13016 			    (intmax_t)time_uptime - io->io_hdr.start_time);
13017 		sbuf_finish(&sb);
13018 		printf("%s", sbuf_data(&sb));
13019 	}
13020 #endif /* CTL_TIME_IO */
13021 
13022 	switch (io->io_hdr.io_type) {
13023 	case CTL_IO_SCSI:
13024 		break;
13025 	case CTL_IO_TASK:
13026 		if (ctl_debug & CTL_DEBUG_INFO)
13027 			ctl_io_error_print(io, NULL);
13028 		fe_done(io);
13029 		return;
13030 	default:
13031 		panic("%s: Invalid CTL I/O type %d\n",
13032 		    __func__, io->io_hdr.io_type);
13033 	}
13034 
13035 	if (lun == NULL) {
13036 		CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13037 				 io->io_hdr.nexus.targ_mapped_lun));
13038 		goto bailout;
13039 	}
13040 
13041 	mtx_lock(&lun->lun_lock);
13042 
13043 	/*
13044 	 * Check to see if we have any informational exception and status
13045 	 * of this command can be modified to report it in form of either
13046 	 * RECOVERED ERROR or NO SENSE, depending on MRIE mode page field.
13047 	 */
13048 	if (lun->ie_reported == 0 && lun->ie_asc != 0 &&
13049 	    io->io_hdr.status == CTL_SUCCESS &&
13050 	    (io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0) {
13051 		uint8_t mrie = lun->MODE_IE.mrie;
13052 		uint8_t per = ((lun->MODE_RWER.byte3 & SMS_RWER_PER) ||
13053 		    (lun->MODE_VER.byte3 & SMS_VER_PER));
13054 		if (((mrie == SIEP_MRIE_REC_COND && per) ||
13055 		     mrie == SIEP_MRIE_REC_UNCOND ||
13056 		     mrie == SIEP_MRIE_NO_SENSE) &&
13057 		    (ctl_get_cmd_entry(&io->scsiio, NULL)->flags &
13058 		     CTL_CMD_FLAG_NO_SENSE) == 0) {
13059 			ctl_set_sense(&io->scsiio,
13060 			      /*current_error*/ 1,
13061 			      /*sense_key*/ (mrie == SIEP_MRIE_NO_SENSE) ?
13062 			        SSD_KEY_NO_SENSE : SSD_KEY_RECOVERED_ERROR,
13063 			      /*asc*/ lun->ie_asc,
13064 			      /*ascq*/ lun->ie_ascq,
13065 			      SSD_ELEM_NONE);
13066 			lun->ie_reported = 1;
13067 		}
13068 	} else if (lun->ie_reported < 0)
13069 		lun->ie_reported = 0;
13070 
13071 	/*
13072 	 * Check to see if we have any errors to inject here.  We only
13073 	 * inject errors for commands that don't already have errors set.
13074 	 */
13075 	if (!STAILQ_EMPTY(&lun->error_list) &&
13076 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS) &&
13077 	    ((io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0))
13078 		ctl_inject_error(lun, io);
13079 
13080 	/*
13081 	 * XXX KDM how do we treat commands that aren't completed
13082 	 * successfully?
13083 	 *
13084 	 * XXX KDM should we also track I/O latency?
13085 	 */
13086 	if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13087 	    io->io_hdr.io_type == CTL_IO_SCSI) {
13088 		int type;
13089 #ifdef CTL_TIME_IO
13090 		struct bintime bt;
13091 
13092 		getbinuptime(&bt);
13093 		bintime_sub(&bt, &io->io_hdr.start_bt);
13094 #endif
13095 		if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13096 		    CTL_FLAG_DATA_IN)
13097 			type = CTL_STATS_READ;
13098 		else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13099 		    CTL_FLAG_DATA_OUT)
13100 			type = CTL_STATS_WRITE;
13101 		else
13102 			type = CTL_STATS_NO_IO;
13103 
13104 		lun->stats.bytes[type] += io->scsiio.kern_total_len;
13105 		lun->stats.operations[type] ++;
13106 		lun->stats.dmas[type] += io->io_hdr.num_dmas;
13107 #ifdef CTL_TIME_IO
13108 		bintime_add(&lun->stats.dma_time[type], &io->io_hdr.dma_bt);
13109 		bintime_add(&lun->stats.time[type], &bt);
13110 #endif
13111 
13112 		mtx_lock(&port->port_lock);
13113 		port->stats.bytes[type] += io->scsiio.kern_total_len;
13114 		port->stats.operations[type] ++;
13115 		port->stats.dmas[type] += io->io_hdr.num_dmas;
13116 #ifdef CTL_TIME_IO
13117 		bintime_add(&port->stats.dma_time[type], &io->io_hdr.dma_bt);
13118 		bintime_add(&port->stats.time[type], &bt);
13119 #endif
13120 		mtx_unlock(&port->port_lock);
13121 	}
13122 
13123 	/*
13124 	 * Run through the blocked queue of this I/O and see if anything
13125 	 * can be unblocked, now that this I/O is done and will be removed.
13126 	 * We need to do it before removal to have OOA position to start.
13127 	 */
13128 	ctl_try_unblock_others(lun, io, TRUE);
13129 
13130 	/*
13131 	 * Remove this from the OOA queue.
13132 	 */
13133 	TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13134 #ifdef CTL_TIME_IO
13135 	if (TAILQ_EMPTY(&lun->ooa_queue))
13136 		lun->last_busy = getsbinuptime();
13137 #endif
13138 
13139 	/*
13140 	 * If the LUN has been invalidated, free it if there is nothing
13141 	 * left on its OOA queue.
13142 	 */
13143 	if ((lun->flags & CTL_LUN_INVALID)
13144 	 && TAILQ_EMPTY(&lun->ooa_queue)) {
13145 		mtx_unlock(&lun->lun_lock);
13146 		ctl_free_lun(lun);
13147 	} else
13148 		mtx_unlock(&lun->lun_lock);
13149 
13150 bailout:
13151 
13152 	/*
13153 	 * If this command has been aborted, make sure we set the status
13154 	 * properly.  The FETD is responsible for freeing the I/O and doing
13155 	 * whatever it needs to do to clean up its state.
13156 	 */
13157 	if (io->io_hdr.flags & CTL_FLAG_ABORT)
13158 		ctl_set_task_aborted(&io->scsiio);
13159 
13160 	/*
13161 	 * If enabled, print command error status.
13162 	 */
13163 	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS &&
13164 	    (ctl_debug & CTL_DEBUG_INFO) != 0)
13165 		ctl_io_error_print(io, NULL);
13166 
13167 	/*
13168 	 * Tell the FETD or the other shelf controller we're done with this
13169 	 * command.  Note that only SCSI commands get to this point.  Task
13170 	 * management commands are completed above.
13171 	 */
13172 	if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
13173 	    (io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)) {
13174 		memset(&msg, 0, sizeof(msg));
13175 		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13176 		msg.hdr.serializing_sc = io->io_hdr.remote_io;
13177 		msg.hdr.nexus = io->io_hdr.nexus;
13178 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13179 		    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data),
13180 		    M_WAITOK);
13181 	}
13182 
13183 	fe_done(io);
13184 }
13185 
13186 /*
13187  * Front end should call this if it doesn't do autosense.  When the request
13188  * sense comes back in from the initiator, we'll dequeue this and send it.
13189  */
13190 int
13191 ctl_queue_sense(union ctl_io *io)
13192 {
13193 	struct ctl_softc *softc = CTL_SOFTC(io);
13194 	struct ctl_port *port = CTL_PORT(io);
13195 	struct ctl_lun *lun;
13196 	struct scsi_sense_data *ps;
13197 	uint32_t initidx, p, targ_lun;
13198 
13199 	CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13200 
13201 	targ_lun = ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13202 
13203 	/*
13204 	 * LUN lookup will likely move to the ctl_work_thread() once we
13205 	 * have our new queueing infrastructure (that doesn't put things on
13206 	 * a per-LUN queue initially).  That is so that we can handle
13207 	 * things like an INQUIRY to a LUN that we don't have enabled.  We
13208 	 * can't deal with that right now.
13209 	 * If we don't have a LUN for this, just toss the sense information.
13210 	 */
13211 	mtx_lock(&softc->ctl_lock);
13212 	if (targ_lun >= ctl_max_luns ||
13213 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
13214 		mtx_unlock(&softc->ctl_lock);
13215 		goto bailout;
13216 	}
13217 	mtx_lock(&lun->lun_lock);
13218 	mtx_unlock(&softc->ctl_lock);
13219 
13220 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
13221 	p = initidx / CTL_MAX_INIT_PER_PORT;
13222 	if (lun->pending_sense[p] == NULL) {
13223 		lun->pending_sense[p] = malloc(sizeof(*ps) * CTL_MAX_INIT_PER_PORT,
13224 		    M_CTL, M_NOWAIT | M_ZERO);
13225 	}
13226 	if ((ps = lun->pending_sense[p]) != NULL) {
13227 		ps += initidx % CTL_MAX_INIT_PER_PORT;
13228 		memset(ps, 0, sizeof(*ps));
13229 		memcpy(ps, &io->scsiio.sense_data, io->scsiio.sense_len);
13230 	}
13231 	mtx_unlock(&lun->lun_lock);
13232 
13233 bailout:
13234 	ctl_free_io(io);
13235 	return (CTL_RETVAL_COMPLETE);
13236 }
13237 
13238 /*
13239  * Primary command inlet from frontend ports.  All SCSI and task I/O
13240  * requests must go through this function.
13241  */
13242 int
13243 ctl_queue(union ctl_io *io)
13244 {
13245 	struct ctl_port *port = CTL_PORT(io);
13246 
13247 	CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13248 
13249 #ifdef CTL_TIME_IO
13250 	io->io_hdr.start_time = time_uptime;
13251 	getbinuptime(&io->io_hdr.start_bt);
13252 #endif /* CTL_TIME_IO */
13253 
13254 	/* Map FE-specific LUN ID into global one. */
13255 	io->io_hdr.nexus.targ_mapped_lun =
13256 	    ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13257 
13258 	switch (io->io_hdr.io_type) {
13259 	case CTL_IO_SCSI:
13260 	case CTL_IO_TASK:
13261 		if (ctl_debug & CTL_DEBUG_CDB)
13262 			ctl_io_print(io);
13263 		ctl_enqueue_incoming(io);
13264 		break;
13265 	default:
13266 		printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13267 		return (EINVAL);
13268 	}
13269 
13270 	return (CTL_RETVAL_COMPLETE);
13271 }
13272 
13273 #ifdef CTL_IO_DELAY
13274 static void
13275 ctl_done_timer_wakeup(void *arg)
13276 {
13277 	union ctl_io *io;
13278 
13279 	io = (union ctl_io *)arg;
13280 	ctl_done(io);
13281 }
13282 #endif /* CTL_IO_DELAY */
13283 
13284 void
13285 ctl_serseq_done(union ctl_io *io)
13286 {
13287 	struct ctl_lun *lun = CTL_LUN(io);
13288 
13289 	if (lun->be_lun == NULL ||
13290 	    lun->be_lun->serseq == CTL_LUN_SERSEQ_OFF)
13291 		return;
13292 	mtx_lock(&lun->lun_lock);
13293 	io->io_hdr.flags |= CTL_FLAG_SERSEQ_DONE;
13294 	ctl_try_unblock_others(lun, io, FALSE);
13295 	mtx_unlock(&lun->lun_lock);
13296 }
13297 
13298 void
13299 ctl_done(union ctl_io *io)
13300 {
13301 
13302 	/*
13303 	 * Enable this to catch duplicate completion issues.
13304 	 */
13305 #if 0
13306 	if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13307 		printf("%s: type %d msg %d cdb %x iptl: "
13308 		       "%u:%u:%u tag 0x%04x "
13309 		       "flag %#x status %x\n",
13310 			__func__,
13311 			io->io_hdr.io_type,
13312 			io->io_hdr.msg_type,
13313 			io->scsiio.cdb[0],
13314 			io->io_hdr.nexus.initid,
13315 			io->io_hdr.nexus.targ_port,
13316 			io->io_hdr.nexus.targ_lun,
13317 			(io->io_hdr.io_type ==
13318 			CTL_IO_TASK) ?
13319 			io->taskio.tag_num :
13320 			io->scsiio.tag_num,
13321 		        io->io_hdr.flags,
13322 			io->io_hdr.status);
13323 	} else
13324 		io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13325 #endif
13326 
13327 	/*
13328 	 * This is an internal copy of an I/O, and should not go through
13329 	 * the normal done processing logic.
13330 	 */
13331 	if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13332 		return;
13333 
13334 #ifdef CTL_IO_DELAY
13335 	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13336 		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13337 	} else {
13338 		struct ctl_lun *lun = CTL_LUN(io);
13339 
13340 		if ((lun != NULL)
13341 		 && (lun->delay_info.done_delay > 0)) {
13342 
13343 			callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
13344 			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
13345 			callout_reset(&io->io_hdr.delay_callout,
13346 				      lun->delay_info.done_delay * hz,
13347 				      ctl_done_timer_wakeup, io);
13348 			if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
13349 				lun->delay_info.done_delay = 0;
13350 			return;
13351 		}
13352 	}
13353 #endif /* CTL_IO_DELAY */
13354 
13355 	ctl_enqueue_done(io);
13356 }
13357 
13358 static void
13359 ctl_work_thread(void *arg)
13360 {
13361 	struct ctl_thread *thr = (struct ctl_thread *)arg;
13362 	struct ctl_softc *softc = thr->ctl_softc;
13363 	union ctl_io *io;
13364 	int retval;
13365 
13366 	CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
13367 	thread_lock(curthread);
13368 	sched_prio(curthread, PUSER - 1);
13369 	thread_unlock(curthread);
13370 
13371 	while (!softc->shutdown) {
13372 		/*
13373 		 * We handle the queues in this order:
13374 		 * - ISC
13375 		 * - done queue (to free up resources, unblock other commands)
13376 		 * - incoming queue
13377 		 * - RtR queue
13378 		 *
13379 		 * If those queues are empty, we break out of the loop and
13380 		 * go to sleep.
13381 		 */
13382 		mtx_lock(&thr->queue_lock);
13383 		io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
13384 		if (io != NULL) {
13385 			STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
13386 			mtx_unlock(&thr->queue_lock);
13387 			ctl_handle_isc(io);
13388 			continue;
13389 		}
13390 		io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
13391 		if (io != NULL) {
13392 			STAILQ_REMOVE_HEAD(&thr->done_queue, links);
13393 			/* clear any blocked commands, call fe_done */
13394 			mtx_unlock(&thr->queue_lock);
13395 			ctl_process_done(io);
13396 			continue;
13397 		}
13398 		io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
13399 		if (io != NULL) {
13400 			STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
13401 			mtx_unlock(&thr->queue_lock);
13402 			if (io->io_hdr.io_type == CTL_IO_TASK)
13403 				ctl_run_task(io);
13404 			else
13405 				ctl_scsiio_precheck(softc, &io->scsiio);
13406 			continue;
13407 		}
13408 		io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
13409 		if (io != NULL) {
13410 			STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
13411 			mtx_unlock(&thr->queue_lock);
13412 			retval = ctl_scsiio(&io->scsiio);
13413 			if (retval != CTL_RETVAL_COMPLETE)
13414 				CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
13415 			continue;
13416 		}
13417 
13418 		/* Sleep until we have something to do. */
13419 		mtx_sleep(thr, &thr->queue_lock, PDROP, "-", 0);
13420 	}
13421 	thr->thread = NULL;
13422 	kthread_exit();
13423 }
13424 
13425 static void
13426 ctl_thresh_thread(void *arg)
13427 {
13428 	struct ctl_softc *softc = (struct ctl_softc *)arg;
13429 	struct ctl_lun *lun;
13430 	struct ctl_logical_block_provisioning_page *page;
13431 	const char *attr;
13432 	union ctl_ha_msg msg;
13433 	uint64_t thres, val;
13434 	int i, e, set;
13435 
13436 	CTL_DEBUG_PRINT(("ctl_thresh_thread starting\n"));
13437 	thread_lock(curthread);
13438 	sched_prio(curthread, PUSER - 1);
13439 	thread_unlock(curthread);
13440 
13441 	while (!softc->shutdown) {
13442 		mtx_lock(&softc->ctl_lock);
13443 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
13444 			if ((lun->flags & CTL_LUN_DISABLED) ||
13445 			    (lun->flags & CTL_LUN_NO_MEDIA) ||
13446 			    lun->backend->lun_attr == NULL)
13447 				continue;
13448 			if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
13449 			    softc->ha_mode == CTL_HA_MODE_XFER)
13450 				continue;
13451 			if ((lun->MODE_RWER.byte8 & SMS_RWER_LBPERE) == 0)
13452 				continue;
13453 			e = 0;
13454 			page = &lun->MODE_LBP;
13455 			for (i = 0; i < CTL_NUM_LBP_THRESH; i++) {
13456 				if ((page->descr[i].flags & SLBPPD_ENABLED) == 0)
13457 					continue;
13458 				thres = scsi_4btoul(page->descr[i].count);
13459 				thres <<= CTL_LBP_EXPONENT;
13460 				switch (page->descr[i].resource) {
13461 				case 0x01:
13462 					attr = "blocksavail";
13463 					break;
13464 				case 0x02:
13465 					attr = "blocksused";
13466 					break;
13467 				case 0xf1:
13468 					attr = "poolblocksavail";
13469 					break;
13470 				case 0xf2:
13471 					attr = "poolblocksused";
13472 					break;
13473 				default:
13474 					continue;
13475 				}
13476 				mtx_unlock(&softc->ctl_lock); // XXX
13477 				val = lun->backend->lun_attr(lun->be_lun, attr);
13478 				mtx_lock(&softc->ctl_lock);
13479 				if (val == UINT64_MAX)
13480 					continue;
13481 				if ((page->descr[i].flags & SLBPPD_ARMING_MASK)
13482 				    == SLBPPD_ARMING_INC)
13483 					e = (val >= thres);
13484 				else
13485 					e = (val <= thres);
13486 				if (e)
13487 					break;
13488 			}
13489 			mtx_lock(&lun->lun_lock);
13490 			if (e) {
13491 				scsi_u64to8b((uint8_t *)&page->descr[i] -
13492 				    (uint8_t *)page, lun->ua_tpt_info);
13493 				if (lun->lasttpt == 0 ||
13494 				    time_uptime - lun->lasttpt >= CTL_LBP_UA_PERIOD) {
13495 					lun->lasttpt = time_uptime;
13496 					ctl_est_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13497 					set = 1;
13498 				} else
13499 					set = 0;
13500 			} else {
13501 				lun->lasttpt = 0;
13502 				ctl_clr_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13503 				set = -1;
13504 			}
13505 			mtx_unlock(&lun->lun_lock);
13506 			if (set != 0 &&
13507 			    lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
13508 				/* Send msg to other side. */
13509 				bzero(&msg.ua, sizeof(msg.ua));
13510 				msg.hdr.msg_type = CTL_MSG_UA;
13511 				msg.hdr.nexus.initid = -1;
13512 				msg.hdr.nexus.targ_port = -1;
13513 				msg.hdr.nexus.targ_lun = lun->lun;
13514 				msg.hdr.nexus.targ_mapped_lun = lun->lun;
13515 				msg.ua.ua_all = 1;
13516 				msg.ua.ua_set = (set > 0);
13517 				msg.ua.ua_type = CTL_UA_THIN_PROV_THRES;
13518 				memcpy(msg.ua.ua_info, lun->ua_tpt_info, 8);
13519 				mtx_unlock(&softc->ctl_lock); // XXX
13520 				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13521 				    sizeof(msg.ua), M_WAITOK);
13522 				mtx_lock(&softc->ctl_lock);
13523 			}
13524 		}
13525 		mtx_sleep(&softc->thresh_thread, &softc->ctl_lock,
13526 		    PDROP, "-", CTL_LBP_PERIOD * hz);
13527 	}
13528 	softc->thresh_thread = NULL;
13529 	kthread_exit();
13530 }
13531 
13532 static void
13533 ctl_enqueue_incoming(union ctl_io *io)
13534 {
13535 	struct ctl_softc *softc = CTL_SOFTC(io);
13536 	struct ctl_thread *thr;
13537 	u_int idx;
13538 
13539 	idx = (io->io_hdr.nexus.targ_port * 127 +
13540 	       io->io_hdr.nexus.initid) % worker_threads;
13541 	thr = &softc->threads[idx];
13542 	mtx_lock(&thr->queue_lock);
13543 	STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
13544 	mtx_unlock(&thr->queue_lock);
13545 	wakeup(thr);
13546 }
13547 
13548 static void
13549 ctl_enqueue_rtr(union ctl_io *io)
13550 {
13551 	struct ctl_softc *softc = CTL_SOFTC(io);
13552 	struct ctl_thread *thr;
13553 
13554 	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13555 	mtx_lock(&thr->queue_lock);
13556 	STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
13557 	mtx_unlock(&thr->queue_lock);
13558 	wakeup(thr);
13559 }
13560 
13561 static void
13562 ctl_enqueue_done(union ctl_io *io)
13563 {
13564 	struct ctl_softc *softc = CTL_SOFTC(io);
13565 	struct ctl_thread *thr;
13566 
13567 	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13568 	mtx_lock(&thr->queue_lock);
13569 	STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
13570 	mtx_unlock(&thr->queue_lock);
13571 	wakeup(thr);
13572 }
13573 
13574 static void
13575 ctl_enqueue_isc(union ctl_io *io)
13576 {
13577 	struct ctl_softc *softc = CTL_SOFTC(io);
13578 	struct ctl_thread *thr;
13579 
13580 	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13581 	mtx_lock(&thr->queue_lock);
13582 	STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
13583 	mtx_unlock(&thr->queue_lock);
13584 	wakeup(thr);
13585 }
13586 
13587 /*
13588  *  vim: ts=8
13589  */
13590